From 92dc1564595ba4e26421f843deabd39526a52d7c Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Sun, 4 Jan 2026 20:52:05 -0700 Subject: [PATCH 01/40] Fix: correctly update book cover hash on metadata refresh (#2149) Co-authored-by: acx10 --- .../service/metadata/BookCoverService.java | 89 +++++++++++++------ .../service/metadata/BookMetadataUpdater.java | 25 +++--- 2 files changed, 72 insertions(+), 42 deletions(-) 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 58ac16c6b..e0ff82586 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 @@ -57,6 +57,13 @@ public class BookCoverService { private record BookRegenerationInfo(Long id, String title, BookFileType bookType) { } + // ========================= + // SECTION: COVER UPDATES + // ========================= + + /** + * Generate a custom cover for a single book. + */ public void generateCustomCover(long bookId) { BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); if (isCoverLocked(bookEntity)) { @@ -71,18 +78,27 @@ public class BookCoverService { notifyBookCoverUpdate(bookEntity); } + /** + * Update cover image from uploaded file for a single book. + */ @Transactional public BookMetadata updateCoverImageFromFile(Long bookId, MultipartFile file) { fileService.createThumbnailFromFile(bookId, file); return updateCover(bookId, (writer, book) -> writer.replaceCoverImageFromUpload(book, file)); } + /** + * Update cover image from a URL for a single book. + */ @Transactional public BookMetadata updateCoverImageFromUrl(Long bookId, String url) { fileService.createThumbnailFromUrl(bookId, url); return updateCover(bookId, (writer, book) -> writer.replaceCoverImageFromUrl(book, url)); } + /** + * Bulk update cover images from a file for multiple books. + */ public void updateCoverImageFromFileForBooks(Set bookIds, MultipartFile file) { validateCoverFile(file); byte[] coverImageBytes = extractBytesFromMultipartFile(file); @@ -90,24 +106,34 @@ public class BookCoverService { SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverUpdate(unlockedBooks, coverImageBytes)); } - public void regenerateCover(long bookId) { - BookEntity bookEntity = bookRepository.findById(bookId) - .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + // ========================= + // SECTION: COVER REGENERATION + // ========================= + /** + * Regenerate cover for a single book. + */ + public void regenerateCover(long bookId) { + BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); if (isCoverLocked(bookEntity)) { throw ApiError.METADATA_LOCKED.createException(); } - regenerateCoverForBook(bookEntity, ""); updateBookCoverMetadata(bookEntity); bookRepository.save(bookEntity); } + /** + * Regenerate covers for a set of books. + */ public void regenerateCoversForBooks(Set bookIds) { List unlockedBooks = getUnlockedBookRegenerationInfos(bookIds); SecurityContextVirtualThread.runWithSecurityContext(() -> processBulkCoverRegeneration(unlockedBooks)); } + /** + * Regenerate covers for all books. + */ public void regenerateCovers() { SecurityContextVirtualThread.runWithSecurityContext(() -> { try { @@ -135,30 +161,9 @@ public class BookCoverService { }); } - private BookMetadata updateCover(Long bookId, BiConsumer writerAction) { - BookEntity bookEntity = bookRepository.findAllWithMetadataByIds(Collections.singleton(bookId)).stream() - .findFirst() - .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); - - updateBookCoverMetadata(bookEntity); - - MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings(); - boolean saveToOriginalFile = settings.isSaveToOriginalFile(); - boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz(); - - if (saveToOriginalFile && (bookEntity.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) { - metadataWriterFactory.getWriter(bookEntity.getBookType()) - .ifPresent(writer -> { - writerAction.accept(writer, bookEntity); - String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath()); - bookEntity.setCurrentHash(newHash); - }); - } - - bookEntity.setMetadataUpdatedAt(Instant.now()); - bookRepository.save(bookEntity); - return bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true); - } + // ========================= + // SECTION: BULK OPERATIONS + // ========================= private void processBulkCoverUpdate(List books, byte[] coverImageBytes) { try { @@ -221,6 +226,34 @@ public class BookCoverService { } } + // ========================= + // SECTION: INTERNAL HELPERS + // ========================= + + private BookMetadata updateCover(Long bookId, BiConsumer writerAction) { + BookEntity bookEntity = bookRepository.findAllWithMetadataByIds(Collections.singleton(bookId)).stream() + .findFirst() + .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + + MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings(); + boolean saveToOriginalFile = settings.isSaveToOriginalFile(); + boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz(); + + if (saveToOriginalFile && (bookEntity.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) { + metadataWriterFactory.getWriter(bookEntity.getBookType()) + .ifPresent(writer -> { + writerAction.accept(writer, bookEntity); + String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath()); + bookEntity.setCurrentHash(newHash); + }); + } + + bookEntity.setMetadataUpdatedAt(Instant.now()); + updateBookCoverMetadata(bookEntity); + bookRepository.save(bookEntity); + return bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true); + } + private void regenerateCoverForBook(BookEntity book, String progress) { String title = book.getMetadata().getTitle(); notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + title)); 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 29c4165d4..3ac12ca6b 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 @@ -9,15 +9,12 @@ import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings import com.adityachandel.booklore.model.entity.*; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.MetadataReplaceMode; -import com.adityachandel.booklore.repository.AuthorRepository; -import com.adityachandel.booklore.repository.BookRepository; -import com.adityachandel.booklore.repository.CategoryRepository; -import com.adityachandel.booklore.repository.MoodRepository; -import com.adityachandel.booklore.repository.TagRepository; -import com.adityachandel.booklore.service.file.FileFingerprint; +import com.adityachandel.booklore.repository.*; import com.adityachandel.booklore.service.appsettings.AppSettingService; +import com.adityachandel.booklore.service.file.FileFingerprint; import com.adityachandel.booklore.service.file.FileMoveService; import com.adityachandel.booklore.service.metadata.writer.MetadataWriterFactory; +import com.adityachandel.booklore.util.BookCoverUtils; import com.adityachandel.booklore.util.FileService; import com.adityachandel.booklore.util.MetadataChangeDetector; import lombok.AllArgsConstructor; @@ -82,7 +79,6 @@ public class BookMetadataUpdater { return; } - // If all fields are locked we must allow unlocking, hasValueChanges will be false if (metadata.areAllFieldsLocked() && hasValueChanges) { log.warn("All fields are locked for book ID {}. Skipping update.", bookId); return; @@ -100,7 +96,7 @@ public class BookMetadataUpdater { updateMoodsIfNeeded(newMetadata, metadata, clearFlags, mergeMoods, replaceMode); updateTagsIfNeeded(newMetadata, metadata, clearFlags, mergeTags, replaceMode); bookReviewUpdateService.updateBookReviews(newMetadata, metadata, clearFlags, mergeCategories); - updateThumbnailIfNeeded(bookId, newMetadata, metadata, updateThumbnail); + updateThumbnailIfNeeded(bookId, bookEntity, newMetadata, metadata, updateThumbnail); updateLocks(newMetadata, metadata); bookEntity.setMetadataUpdatedAt(Instant.now()); @@ -229,14 +225,14 @@ public class BookMetadataUpdater { if (replaceAll) { if (!merge) e.getAuthors().clear(); e.getAuthors().addAll(newAuthors); - e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate + e.updateSearchText(); } else if (replaceMissing && e.getAuthors().isEmpty()) { e.getAuthors().addAll(newAuthors); - e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate + e.updateSearchText(); } else if (replaceMode == null) { if (!merge) e.getAuthors().clear(); e.getAuthors().addAll(newAuthors); - e.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate + e.updateSearchText(); } } @@ -354,17 +350,18 @@ public class BookMetadataUpdater { } } - private void updateThumbnailIfNeeded(long bookId, BookMetadata m, BookMetadataEntity e, boolean set) { + private void updateThumbnailIfNeeded(long bookId, BookEntity bookEntity, BookMetadata m, BookMetadataEntity e, boolean set) { if (Boolean.TRUE.equals(e.getCoverLocked())) { - return; // Locked — do nothing + return; } if (!set) return; if (!StringUtils.hasText(m.getThumbnailUrl()) || isLocalOrPrivateUrl(m.getThumbnailUrl())) return; try { fileService.createThumbnailFromUrl(bookId, m.getThumbnailUrl()); + bookEntity.setBookCoverHash(BookCoverUtils.generateCoverHash()); + bookEntity.getMetadata().setCoverUpdatedOn(Instant.now()); } catch (Exception ex) { log.warn("Failed to download cover for book {}: {}", bookId, ex.getMessage()); - // Don't rethrow - cover failures shouldn't roll back metadata updates } } From e8de8adf6f0267d94488b11f90ce9a9525001f67 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Sun, 4 Jan 2026 21:56:20 -0700 Subject: [PATCH 02/40] Introduce Vitest as the frontend Angular testing framework for Booklore (#2150) Co-authored-by: acx10 --- .../metadata/BookCoverServiceTest.java | 11 +- booklore-ui/angular.json | 20 +- booklore-ui/package-lock.json | 1293 ++++++++++++++--- booklore-ui/package.json | 10 +- .../book/service/book-menu.service.spec.ts | 466 ++++++ .../service/book-navigation.service.spec.ts | 106 ++ .../book/service/book-patch.service.spec.ts | 173 +++ .../book/service/book-state.service.ts | 9 +- .../book/service/book.service.spec.ts | 537 +++++++ .../book/service/cbx-reader.service.spec.ts | 96 ++ .../library-shelf-menu.service.spec.ts | 350 +++++ .../book/service/library.service.spec.ts | 167 +++ .../features/book/service/library.service.ts | 7 - .../book/service/metadata-task.spec.ts | 123 ++ .../service/new-pdf-reader.service.spec.ts | 70 + .../book/service/shelf.service.spec.ts | 129 ++ .../book/service/sort.service.spec.ts | 142 ++ booklore-ui/tsconfig.spec.json | 3 +- 18 files changed, 3442 insertions(+), 270 deletions(-) create mode 100644 booklore-ui/src/app/features/book/service/book-menu.service.spec.ts create mode 100644 booklore-ui/src/app/features/book/service/book-navigation.service.spec.ts create mode 100644 booklore-ui/src/app/features/book/service/book-patch.service.spec.ts create mode 100644 booklore-ui/src/app/features/book/service/book.service.spec.ts create mode 100644 booklore-ui/src/app/features/book/service/cbx-reader.service.spec.ts create mode 100644 booklore-ui/src/app/features/book/service/library-shelf-menu.service.spec.ts create mode 100644 booklore-ui/src/app/features/book/service/library.service.spec.ts create mode 100644 booklore-ui/src/app/features/book/service/metadata-task.spec.ts create mode 100644 booklore-ui/src/app/features/book/service/new-pdf-reader.service.spec.ts create mode 100644 booklore-ui/src/app/features/book/service/shelf.service.spec.ts create mode 100644 booklore-ui/src/app/features/book/service/sort.service.spec.ts diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookCoverServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookCoverServiceTest.java index 7c1e41db1..02a321682 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookCoverServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookCoverServiceTest.java @@ -3,6 +3,7 @@ package com.adityachandel.booklore.service.metadata; import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.mapper.BookMetadataMapper; import com.adityachandel.booklore.model.dto.BookMetadata; +import com.adityachandel.booklore.model.dto.settings.AppSettings; import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; import com.adityachandel.booklore.model.entity.AuthorEntity; import com.adityachandel.booklore.model.entity.BookEntity; @@ -26,11 +27,13 @@ import org.mockito.*; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.web.multipart.MultipartFile; -import java.time.Instant; -import java.util.*; import java.nio.file.Path; +import java.util.List; +import java.util.Optional; +import java.util.Set; -import static org.assertj.core.api.Assertions.*; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.*; class BookCoverServiceTest { @@ -243,7 +246,7 @@ class BookCoverServiceTest { assertThat(result).isNotNull(); } - private com.adityachandel.booklore.model.dto.settings.AppSettings mockAppSettings(boolean saveToOriginalFile, boolean convertCbrCb7ToCbz) { + private AppSettings mockAppSettings(boolean saveToOriginalFile, boolean convertCbrCb7ToCbz) { MetadataPersistenceSettings settings = new MetadataPersistenceSettings(); settings.setSaveToOriginalFile(saveToOriginalFile); settings.setConvertCbrCb7ToCbz(convertCbrCb7ToCbz); diff --git a/booklore-ui/angular.json b/booklore-ui/angular.json index f0336f036..7ad3647fc 100644 --- a/booklore-ui/angular.json +++ b/booklore-ui/angular.json @@ -106,25 +106,7 @@ "builder": "@angular/build:extract-i18n" }, "test": { - "builder": "@angular/build:karma", - "options": { - "polyfills": [ - "zone.js", - "zone.js/testing" - ], - "tsConfig": "tsconfig.spec.json", - "inlineStyleLanguage": "scss", - "assets": [ - { - "glob": "**/*", - "input": "public" - } - ], - "styles": [ - "src/styles.scss" - ], - "scripts": [] - } + "builder": "@angular/build:unit-test" }, "lint": { "builder": "@angular-eslint/builder:lint", diff --git a/booklore-ui/package-lock.json b/booklore-ui/package-lock.json index b4da98c36..15bd2683b 100644 --- a/booklore-ui/package-lock.json +++ b/booklore-ui/package-lock.json @@ -49,21 +49,26 @@ "@angular/compiler-cli": "^21.0.5", "@tailwindcss/typography": "^0.5.19", "@types/jasmine": "^5.1.13", + "@types/node": "^25.0.3", "@types/showdown": "^2.0.6", "angular-eslint": "^21.1.0", "autoprefixer": "^10.4.23", "eslint": "^9.39.2", "jasmine-core": "^5.13.0", - "karma": "^6.4.4", - "karma-chrome-launcher": "^3.2.0", - "karma-coverage": "^2.2.1", - "karma-jasmine": "^5.1.0", - "karma-jasmine-html-reporter": "^2.1.0", + "jsdom": "^27.4.0", "tailwindcss": "^3.4.17", "typescript": "~5.9.3", - "typescript-eslint": "^8.50.0" + "typescript-eslint": "^8.50.0", + "vitest": "^4.0.16" } }, + "node_modules/@acemir/cssom": { + "version": "0.9.30", + "resolved": "https://registry.npmjs.org/@acemir/cssom/-/cssom-0.9.30.tgz", + "integrity": "sha512-9CnlMCI0LmCIq0olalQqdWrJHPzm0/tw3gzOA9zJSgvFX7Xau3D24mAGa4BtwxwY69nsuJW6kQqqCzf/mEcQgg==", + "dev": true, + "license": "MIT" + }, "node_modules/@algolia/abtesting": { "version": "1.6.1", "resolved": "https://registry.npmjs.org/@algolia/abtesting/-/abtesting-1.6.1.tgz", @@ -800,6 +805,61 @@ "rxjs": "^6.5.3 || ^7.4.0" } }, + "node_modules/@asamuzakjp/css-color": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-4.1.1.tgz", + "integrity": "sha512-B0Hv6G3gWGMn0xKJ0txEi/jM5iFpT3MfDxmhZFb4W047GvytCf1DHQ1D69W3zHI4yWe2aTZAA0JnbMZ7Xc8DuQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@csstools/css-calc": "^2.1.4", + "@csstools/css-color-parser": "^3.1.0", + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4", + "lru-cache": "^11.2.4" + } + }, + "node_modules/@asamuzakjp/css-color/node_modules/lru-cache": { + "version": "11.2.4", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.4.tgz", + "integrity": "sha512-B5Y16Jr9LB9dHVkh6ZevG+vAbOsNOYCX+sXvFWFu7B3Iz5mijW3zdbMyhsh8ANd2mSWBYdJgnqi+mL7/LrOPYg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@asamuzakjp/dom-selector": { + "version": "6.7.6", + "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-6.7.6.tgz", + "integrity": "sha512-hBaJER6A9MpdG3WgdlOolHmbOYvSk46y7IQN/1+iqiCuUu6iWdQrs9DGKF8ocqsEqWujWf/V7b7vaDgiUmIvUg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/nwsapi": "^2.3.9", + "bidi-js": "^1.0.3", + "css-tree": "^3.1.0", + "is-potential-custom-element-name": "^1.0.1", + "lru-cache": "^11.2.4" + } + }, + "node_modules/@asamuzakjp/dom-selector/node_modules/lru-cache": { + "version": "11.2.4", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.4.tgz", + "integrity": "sha512-B5Y16Jr9LB9dHVkh6ZevG+vAbOsNOYCX+sXvFWFu7B3Iz5mijW3zdbMyhsh8ANd2mSWBYdJgnqi+mL7/LrOPYg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@asamuzakjp/nwsapi": { + "version": "2.3.9", + "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz", + "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==", + "dev": true, + "license": "MIT" + }, "node_modules/@babel/code-frame": { "version": "7.27.1", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz", @@ -1116,10 +1176,147 @@ "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=0.1.90" } }, + "node_modules/@csstools/color-helpers": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.1.0.tgz", + "integrity": "sha512-S11EXWJyy0Mz5SYvRmY8nJYTFFd1LCNV+7cXyAgQtOOuzb4EsgfqDufL+9esx72/eLhsRdGZwaldu/h+E4t4BA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-calc": { + "version": "2.1.4", + "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz", + "integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-color-parser": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.1.0.tgz", + "integrity": "sha512-nbtKwh3a6xNVIp/VRuXV64yTKnb1IjTAEEh3irzS+HkKjAOYLTGNb9pmVNntZ8iVBHcWDA2Dof0QtPgFI1BaTA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "dependencies": { + "@csstools/color-helpers": "^5.1.0", + "@csstools/css-calc": "^2.1.4" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-parser-algorithms": "^3.0.5", + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-parser-algorithms": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz", + "integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@csstools/css-tokenizer": "^3.0.4" + } + }, + "node_modules/@csstools/css-syntax-patches-for-csstree": { + "version": "1.0.22", + "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.0.22.tgz", + "integrity": "sha512-qBcx6zYlhleiFfdtzkRgwNC7VVoAwfK76Vmsw5t+PbvtdknO9StgRk7ROvq9so1iqbdW4uLIDAsXRsTfUrIoOw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT-0", + "engines": { + "node": ">=18" + } + }, + "node_modules/@csstools/css-tokenizer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz", + "integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/csstools" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/csstools" + } + ], + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@emnapi/core": { "version": "1.7.1", "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.7.1.tgz", @@ -1809,6 +2006,24 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@exodus/bytes": { + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.8.0.tgz", + "integrity": "sha512-8JPn18Bcp8Uo1T82gR8lh2guEOa5KKU/IEKvvdp0sgmi7coPBWf1Doi1EXsGZb2ehc8ym/StJCjffYV+ne7sXQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "@exodus/crypto": "^1.0.0-rc.4" + }, + "peerDependenciesMeta": { + "@exodus/crypto": { + "optional": true + } + } + }, "node_modules/@humanfs/core": { "version": "0.19.1", "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", @@ -4322,14 +4537,15 @@ "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/@standard-schema/spec": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@stomp/rx-stomp": { "version": "2.3.0", @@ -4402,16 +4618,36 @@ "tslib": "^2.4.0" } }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, "node_modules/@types/cors": { "version": "2.8.19", "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz", "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "@types/node": "*" } }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/estree": { "version": "1.0.8", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", @@ -4444,9 +4680,9 @@ } }, "node_modules/@types/node": { - "version": "24.10.1", - "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz", - "integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==", + "version": "25.0.3", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.0.3.tgz", + "integrity": "sha512-W609buLVRVmeW693xKfzHeIV6nJGGz98uCPfeXI1ELMLXVeKYZ9m15fAMSaUPBHYLGFsVRcMmSCksQOrZV9BYA==", "dev": true, "license": "MIT", "dependencies": { @@ -4706,6 +4942,137 @@ "vite": "^6.0.0 || ^7.0.0" } }, + "node_modules/@vitest/expect": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.0.16.tgz", + "integrity": "sha512-eshqULT2It7McaJkQGLkPjPjNph+uevROGuIMJdG3V+0BSR2w9u6J9Lwu+E8cK5TETlfou8GRijhafIMhXsimA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.0.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.0.16", + "@vitest/utils": "4.0.16", + "chai": "^6.2.1", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.0.16.tgz", + "integrity": "sha512-yb6k4AZxJTB+q9ycAvsoxGn+j/po0UaPgajllBgt1PzoMAAmJGYFdDk0uCcRcxb3BrME34I6u8gHZTQlkqSZpg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.0.16", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0-0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/mocker/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.0.16.tgz", + "integrity": "sha512-eNCYNsSty9xJKi/UdVD8Ou16alu7AYiS2fCPRs0b1OdhJiV89buAXQLpTbe+X8V9L6qrs9CqyvU7OaAopJYPsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.0.16.tgz", + "integrity": "sha512-VWEDm5Wv9xEo80ctjORcTQRJ539EGPB3Pb9ApvVRAY1U/WkHXmmYISqU5E79uCwcW7xYUV38gwZD+RV755fu3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.0.16", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.0.16.tgz", + "integrity": "sha512-sf6NcrYhYBsSYefxnry+DR8n3UV4xWZwWxYbCJUt2YdvtqzSPR7VfGrY0zsv090DAbjFZsi7ZaMi1KnSRyK1XA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.0.16", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/@vitest/spy": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.0.16.tgz", + "integrity": "sha512-4jIOWjKP0ZUaEmJm00E0cOBLU+5WE0BpeNr3XN6TEF05ltro6NJqHWxXD0kA8/Zc8Nh23AT8WQxwNG+WeROupw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.0.16.tgz", + "integrity": "sha512-h8z9yYhV3e1LEfaQ3zdypIrnAg/9hguReGZoS7Gl0aBG5xgA410zBqECqmaF/+RkTggRsfnzc1XaAHA6bmUufA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.0.16", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, "node_modules/@xmldom/xmldom": { "version": "0.7.13", "resolved": "https://registry.npmjs.org/@xmldom/xmldom/-/xmldom-0.7.13.tgz", @@ -4977,6 +5344,16 @@ "node": ">= 0.4" } }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, "node_modules/autoprefixer": { "version": "10.4.23", "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.23.tgz", @@ -5037,6 +5414,8 @@ "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": "^4.5.0 || >= 5.9" } @@ -5071,6 +5450,16 @@ "node": ">=14.0.0" } }, + "node_modules/bidi-js": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz", + "integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "require-from-string": "^2.0.2" + } + }, "node_modules/binary-extensions": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", @@ -5339,6 +5728,16 @@ ], "license": "CC-BY-4.0" }, + "node_modules/chai": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", + "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/chalk": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", @@ -5587,6 +5986,8 @@ "integrity": "sha512-ZqRXc+tZukToSNmh5C2iWMSoV3X1YUcPbqEM4DkEG5tNQXrQUZCNVGGv3IuicnkMtPfGf3Xtp8WCXs295iQ1pQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "debug": "2.6.9", "finalhandler": "1.1.2", @@ -5603,6 +6004,8 @@ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ms": "2.0.0" } @@ -5613,6 +6016,8 @@ "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.8" } @@ -5623,6 +6028,8 @@ "integrity": "sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "debug": "2.6.9", "encodeurl": "~1.0.2", @@ -5641,7 +6048,9 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/connect/node_modules/on-finished": { "version": "2.3.0", @@ -5649,6 +6058,8 @@ "integrity": "sha512-ikqdkGAAyf/X/gPhXGvfgAytDZtDbr+bkNUJ0N9h5MI/dmdgCs3l6hoHrcUv41sRKew3jIwrp4qQDXiK99Utww==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ee-first": "1.1.1" }, @@ -5662,6 +6073,8 @@ "integrity": "sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -5780,6 +6193,20 @@ "url": "https://github.com/sponsors/fb55" } }, + "node_modules/css-tree": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.1.0.tgz", + "integrity": "sha512-0eW44TGN5SQXU1mWSkKwFstI/22X2bG1nYzZTYMAWjylYURhse752YgbE4Cx46AC+bAvI+/dYTPRk1LqSUnu6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "mdn-data": "2.12.2", + "source-map-js": "^1.0.1" + }, + "engines": { + "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0" + } + }, "node_modules/css-what": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/css-what/-/css-what-7.0.0.tgz", @@ -5805,12 +6232,40 @@ "node": ">=4" } }, + "node_modules/cssstyle": { + "version": "5.3.6", + "resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-5.3.6.tgz", + "integrity": "sha512-legscpSpgSAeGEe0TNcai97DKt9Vd9AsAdOL7Uoetb52Ar/8eJm3LIa39qpv8wWzLFlNG4vVvppQM+teaMPj3A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@asamuzakjp/css-color": "^4.1.1", + "@csstools/css-syntax-patches-for-csstree": "^1.0.21", + "css-tree": "^3.1.0", + "lru-cache": "^11.2.4" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/cssstyle/node_modules/lru-cache": { + "version": "11.2.4", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.4.tgz", + "integrity": "sha512-B5Y16Jr9LB9dHVkh6ZevG+vAbOsNOYCX+sXvFWFu7B3Iz5mijW3zdbMyhsh8ANd2mSWBYdJgnqi+mL7/LrOPYg==", + "dev": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/custom-event": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/custom-event/-/custom-event-1.0.1.tgz", "integrity": "sha512-GAj5FOq0Hd+RsCGVJxZuKaIDXDf3h6GQoNEjFgbLLI/trgtavwUbSnZ5pVfg27DVCaWjIohryS0JFwIJyT2cMg==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/d": { "version": "1.0.2", @@ -5825,6 +6280,20 @@ "node": ">=0.12" } }, + "node_modules/data-urls": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-6.0.0.tgz", + "integrity": "sha512-BnBS08aLUM+DKamupXs3w2tJJoqU+AkaE/+6vQxi/G/DPmIZFJJp9Dkb1kM03AZx8ADehDUZgsNxju3mPXZYIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^15.0.0" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/date-fns": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz", @@ -5841,6 +6310,8 @@ "integrity": "sha512-39BOQLs9ZjKh0/patS9nrT8wc3ioX3/eA/zgbKNopnF2wCqJEoxywwwElATYvRsXdnOxA/OQeQoFZ3rFjVajhg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=4.0" } @@ -5863,6 +6334,13 @@ } } }, + "node_modules/decimal.js": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz", + "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==", + "dev": true, + "license": "MIT" + }, "node_modules/deep-is": { "version": "0.1.4", "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", @@ -5886,6 +6364,8 @@ "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.8", "npm": "1.2.8000 || >= 1.4.16" @@ -5907,7 +6387,9 @@ "resolved": "https://registry.npmjs.org/di/-/di-0.0.1.tgz", "integrity": "sha512-uJaamHkagcZtHPqCIHZxnFrXlunQXgBOsZSUOWwFw31QJCAbyTBoHMW75YOTur5ZNx8pIeAKgf6GWIgaqqiLhA==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/didyoumean": { "version": "1.2.2", @@ -5927,6 +6409,8 @@ "integrity": "sha512-Yra4DbvoW7/Z6LBN560ZwXMjoNOSAN2wRsKFGc4iBeso+mpIA6qj1vfdf9HpMaKAqG6wXTy+1SYEzmNpKXOSsQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "custom-event": "~1.0.0", "ent": "~2.2.0", @@ -6070,6 +6554,8 @@ "integrity": "sha512-ZCkIjSYNDyGn0R6ewHDtXgns/Zre/NT6Agvq1/WobF7JXgFff4SeDroKiCO3fNJreU9YG429Sc81o4w5ok/W5g==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "@types/cors": "^2.8.12", "@types/node": ">=10.0.0", @@ -6091,6 +6577,8 @@ "integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=10.0.0" } @@ -6101,6 +6589,8 @@ "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" @@ -6115,6 +6605,8 @@ "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -6133,6 +6625,8 @@ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -6143,6 +6637,8 @@ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "mime-db": "1.52.0" }, @@ -6156,6 +6652,8 @@ "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -6166,6 +6664,8 @@ "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=10.0.0" }, @@ -6188,6 +6688,8 @@ "integrity": "sha512-kKvD1tO6BM+oK9HzCPpUdRb4vKFQY/FPTFmurMvh6LlN68VMrdj77w8yp51/kDbpkFOS9J8w5W6zIzgM2H8/hw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", @@ -6278,6 +6780,13 @@ "node": ">= 0.4" } }, + "node_modules/es-module-lexer": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", + "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==", + "dev": true, + "license": "MIT" + }, "node_modules/es-object-atoms": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", @@ -6663,6 +7172,16 @@ "node": ">=4.0" } }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, "node_modules/esutils": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", @@ -6698,7 +7217,9 @@ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/eventsource": { "version": "3.0.7", @@ -6723,6 +7244,16 @@ "node": ">=18.0.0" } }, + "node_modules/expect-type": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", + "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, "node_modules/exponential-backoff": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/exponential-backoff/-/exponential-backoff-3.1.3.tgz", @@ -6804,7 +7335,9 @@ "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/fast-deep-equal": { "version": "3.1.3", @@ -7001,6 +7534,8 @@ } ], "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=4.0" }, @@ -7050,6 +7585,8 @@ "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", @@ -7077,7 +7614,9 @@ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", "dev": true, - "license": "ISC" + "license": "ISC", + "optional": true, + "peer": true }, "node_modules/fsevents": { "version": "2.3.3", @@ -7181,6 +7720,8 @@ "deprecated": "Glob versions prior to v9 are no longer supported", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -7221,6 +7762,8 @@ "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -7232,6 +7775,8 @@ "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -7301,6 +7846,8 @@ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "has-symbols": "^1.0.3" }, @@ -7346,12 +7893,18 @@ "node": "20 || >=22" } }, - "node_modules/html-escaper": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", - "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "node_modules/html-encoding-sniffer": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz", + "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==", "dev": true, - "license": "MIT" + "license": "MIT", + "dependencies": { + "@exodus/bytes": "^1.6.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + } }, "node_modules/htmlparser2": { "version": "10.0.0", @@ -7420,6 +7973,8 @@ "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "eventemitter3": "^4.0.0", "follow-redirects": "^1.0.0", @@ -7560,6 +8115,8 @@ "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "dependencies": { "once": "^1.3.0", "wrappy": "1" @@ -7687,6 +8244,13 @@ "node": ">=0.12.0" } }, + "node_modules/is-potential-custom-element-name": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz", + "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==", + "dev": true, + "license": "MIT" + }, "node_modules/is-promise": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", @@ -7700,6 +8264,8 @@ "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "call-bound": "^1.0.2", "gopd": "^1.2.0", @@ -7738,6 +8304,8 @@ "integrity": "sha512-iHrqe5shvBUcFbmZq9zOQHBoeOhZJu6RQGrDpBgenUm/Am+F3JM2MgQj+rK3Z601fzrL5gLZWtAPH2OBaSVcyw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 8.0.0" }, @@ -7779,60 +8347,6 @@ "node": ">=10" } }, - "node_modules/istanbul-lib-report": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", - "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "istanbul-lib-coverage": "^3.0.0", - "make-dir": "^4.0.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-source-maps": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz", - "integrity": "sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "debug": "^4.1.1", - "istanbul-lib-coverage": "^3.0.0", - "source-map": "^0.6.1" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-source-maps/node_modules/source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/istanbul-reports": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", - "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "html-escaper": "^2.0.0", - "istanbul-lib-report": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/jasmine-core": { "version": "5.13.0", "resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-5.13.0.tgz", @@ -7870,6 +8384,46 @@ "js-yaml": "bin/js-yaml.js" } }, + "node_modules/jsdom": { + "version": "27.4.0", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-27.4.0.tgz", + "integrity": "sha512-mjzqwWRD9Y1J1KUi7W97Gja1bwOOM5Ug0EZ6UDK3xS7j7mndrkwozHtSblfomlzyB4NepioNt+B2sOSzczVgtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@acemir/cssom": "^0.9.28", + "@asamuzakjp/dom-selector": "^6.7.6", + "@exodus/bytes": "^1.6.0", + "cssstyle": "^5.3.4", + "data-urls": "^6.0.0", + "decimal.js": "^10.6.0", + "html-encoding-sniffer": "^6.0.0", + "http-proxy-agent": "^7.0.2", + "https-proxy-agent": "^7.0.6", + "is-potential-custom-element-name": "^1.0.1", + "parse5": "^8.0.0", + "saxes": "^6.0.0", + "symbol-tree": "^3.2.4", + "tough-cookie": "^6.0.0", + "w3c-xmlserializer": "^5.0.0", + "webidl-conversions": "^8.0.0", + "whatwg-mimetype": "^4.0.0", + "whatwg-url": "^15.1.0", + "ws": "^8.18.3", + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": "^20.19.0 || ^22.12.0 || >=24.0.0" + }, + "peerDependencies": { + "canvas": "^3.0.0" + }, + "peerDependenciesMeta": { + "canvas": { + "optional": true + } + } + }, "node_modules/jsesc": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", @@ -7940,6 +8494,8 @@ "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "optionalDependencies": { "graceful-fs": "^4.1.6" } @@ -7981,6 +8537,8 @@ "integrity": "sha512-LrtUxbdvt1gOpo3gxG+VAJlJAEMhbWlM4YrFQgql98FwF7+K8K12LYO4hnDdUkNjeztYrOXEMqgTajSWgmtI/w==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "@colors/colors": "1.5.0", "body-parser": "^1.19.0", @@ -8014,139 +8572,14 @@ "node": ">= 10" } }, - "node_modules/karma-chrome-launcher": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/karma-chrome-launcher/-/karma-chrome-launcher-3.2.0.tgz", - "integrity": "sha512-rE9RkUPI7I9mAxByQWkGJFXfFD6lE4gC5nPuZdobf/QdTEJI6EU4yIay/cfU/xV4ZxlM5JiTv7zWYgA64NpS5Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "which": "^1.2.1" - } - }, - "node_modules/karma-chrome-launcher/node_modules/which": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", - "integrity": "sha512-HxJdYWq1MTIQbJ3nw0cqssHoTNU267KlrDuGZ1WYlxDStUtKUhOaJmh112/TZmHxxUfuJqPXSOm7tDyas0OSIQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "which": "bin/which" - } - }, - "node_modules/karma-coverage": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/karma-coverage/-/karma-coverage-2.2.1.tgz", - "integrity": "sha512-yj7hbequkQP2qOSb20GuNSIyE//PgJWHwC2IydLE6XRtsnaflv+/OSGNssPjobYUlhVVagy99TQpqUt3vAUG7A==", - "dev": true, - "license": "MIT", - "dependencies": { - "istanbul-lib-coverage": "^3.2.0", - "istanbul-lib-instrument": "^5.1.0", - "istanbul-lib-report": "^3.0.0", - "istanbul-lib-source-maps": "^4.0.1", - "istanbul-reports": "^3.0.5", - "minimatch": "^3.0.4" - }, - "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/karma-coverage/node_modules/brace-expansion": { - "version": "1.1.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", - "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/karma-coverage/node_modules/istanbul-lib-instrument": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz", - "integrity": "sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@babel/core": "^7.12.3", - "@babel/parser": "^7.14.7", - "@istanbuljs/schema": "^0.1.2", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^6.3.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/karma-coverage/node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/karma-coverage/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/karma-jasmine": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/karma-jasmine/-/karma-jasmine-5.1.0.tgz", - "integrity": "sha512-i/zQLFrfEpRyQoJF9fsCdTMOF5c2dK7C7OmsuKg2D0YSsuZSfQDiLuaiktbuio6F2wiCsZSnSnieIQ0ant/uzQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "jasmine-core": "^4.1.0" - }, - "engines": { - "node": ">=12" - }, - "peerDependencies": { - "karma": "^6.0.0" - } - }, - "node_modules/karma-jasmine-html-reporter": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/karma-jasmine-html-reporter/-/karma-jasmine-html-reporter-2.1.0.tgz", - "integrity": "sha512-sPQE1+nlsn6Hwb5t+HHwyy0A1FNCVKuL1192b+XNauMYWThz2kweiBVW1DqloRpVvZIJkIoHVB7XRpK78n1xbQ==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "jasmine-core": "^4.0.0 || ^5.0.0", - "karma": "^6.0.0", - "karma-jasmine": "^5.0.0" - } - }, - "node_modules/karma-jasmine/node_modules/jasmine-core": { - "version": "4.6.1", - "resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-4.6.1.tgz", - "integrity": "sha512-VYz/BjjmC3klLJlLwA4Kw8ytk0zDSmbbDLNs794VnWmkcCB7I9aAL/D48VNQtmITyPvea2C3jdUMfc3kAoy0PQ==", - "dev": true, - "license": "MIT" - }, "node_modules/karma/node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=8" } @@ -8157,6 +8590,8 @@ "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "bytes": "3.1.2", "content-type": "~1.0.5", @@ -8182,6 +8617,8 @@ "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -8193,6 +8630,8 @@ "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", @@ -8218,6 +8657,8 @@ "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", @@ -8230,6 +8671,8 @@ "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ms": "2.0.0" } @@ -8239,7 +8682,9 @@ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/karma/node_modules/glob-parent": { "version": "5.1.2", @@ -8247,6 +8692,8 @@ "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "dependencies": { "is-glob": "^4.0.1" }, @@ -8260,6 +8707,8 @@ "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "depd": "2.0.0", "inherits": "2.0.4", @@ -8277,6 +8726,8 @@ "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "safer-buffer": ">= 2.1.2 < 3" }, @@ -8290,6 +8741,8 @@ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=8" } @@ -8300,6 +8753,8 @@ "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -8310,6 +8765,8 @@ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -8320,6 +8777,8 @@ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "mime-db": "1.52.0" }, @@ -8333,6 +8792,8 @@ "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -8345,7 +8806,9 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/karma/node_modules/picomatch": { "version": "2.3.1", @@ -8353,6 +8816,8 @@ "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=8.6" }, @@ -8366,6 +8831,8 @@ "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", "dev": true, "license": "BSD-3-Clause", + "optional": true, + "peer": true, "dependencies": { "side-channel": "^1.0.6" }, @@ -8382,6 +8849,8 @@ "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "bytes": "3.1.2", "http-errors": "2.0.0", @@ -8398,6 +8867,8 @@ "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "picomatch": "^2.2.1" }, @@ -8411,6 +8882,8 @@ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true, "license": "BSD-3-Clause", + "optional": true, + "peer": true, "engines": { "node": ">=0.10.0" } @@ -8421,6 +8894,8 @@ "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.8" } @@ -8431,6 +8906,8 @@ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -8446,6 +8923,8 @@ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ansi-regex": "^5.0.1" }, @@ -8459,6 +8938,8 @@ "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "media-typer": "0.3.0", "mime-types": "~2.1.24" @@ -8473,6 +8954,8 @@ "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", @@ -8491,6 +8974,8 @@ "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "cliui": "^7.0.2", "escalade": "^3.1.1", @@ -8510,6 +8995,8 @@ "integrity": "sha512-y11nGElTIV+CT3Zv9t7VKl+Q3hTQoT9a1Qzezhhl6Rp21gJ/IVTW7Z3y9EWXhuUBC2Shnf+DX0antecpAwSP8w==", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "engines": { "node": ">=10" } @@ -8789,6 +9276,8 @@ "integrity": "sha512-1somDdy9sChrr9/f4UlzhdaGfDR2c/SaD2a4T7qEkG4jTS57/B3qmnjLYePwQ8cqWnUHZI0iAKxMBpCZICiZ2g==", "dev": true, "license": "Apache-2.0", + "optional": true, + "peer": true, "dependencies": { "date-format": "^4.0.14", "debug": "^4.3.4", @@ -8820,22 +9309,6 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, - "node_modules/make-dir": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", - "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", - "dev": true, - "license": "MIT", - "dependencies": { - "semver": "^7.5.3" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/make-fetch-happen": { "version": "15.0.3", "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-15.0.3.tgz", @@ -8898,6 +9371,13 @@ "node": ">= 0.4" } }, + "node_modules/mdn-data": { + "version": "2.12.2", + "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.12.2.tgz", + "integrity": "sha512-IEn+pegP1aManZuckezWCO+XZQDplx1366JoVhTpMpBB1sPey/SbveZQUosKiKiGYjg1wH4pMlNgXbCiYgihQA==", + "dev": true, + "license": "CC0-1.0" + }, "node_modules/media-typer": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.0.tgz", @@ -8961,6 +9441,8 @@ "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "bin": { "mime": "cli.js" }, @@ -9030,6 +9512,8 @@ "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -9193,6 +9677,8 @@ "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "minimist": "^1.2.6" }, @@ -9664,6 +10150,17 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/obug": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz", + "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT" + }, "node_modules/on-finished": { "version": "2.4.1", "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", @@ -9976,6 +10473,8 @@ "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=0.10.0" } @@ -10040,6 +10539,13 @@ "integrity": "sha512-AmeDxedoo5svf7aB3FYqSAKqMxys014lVKBzy1o/5vv9CtU7U4wgGWL1dA2o6MOzcD53ScN4Jmiq6VbtLz1vIQ==", "license": "MIT" }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", @@ -10363,7 +10869,9 @@ "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.4.1.tgz", "integrity": "sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/qjobs": { "version": "1.2.0", @@ -10371,6 +10879,8 @@ "integrity": "sha512-8YOJEHtxpySA3fFDyCRxA+UUV+fA+rTWnuWvylOK/NCjhY+b4ocCtmu8TtsWb+mYeU+GCHf/S66KZF/AsteKHg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=0.9" } @@ -10523,6 +11033,8 @@ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=0.10.0" } @@ -10542,7 +11054,9 @@ "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", "dev": true, - "license": "MIT" + "license": "MIT", + "optional": true, + "peer": true }, "node_modules/resolve": { "version": "1.22.11", @@ -10625,6 +11139,8 @@ "deprecated": "Rimraf versions prior to v4 are no longer supported", "dev": true, "license": "ISC", + "optional": true, + "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -10771,6 +11287,8 @@ "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", @@ -10811,6 +11329,19 @@ "@parcel/watcher": "^2.4.1" } }, + "node_modules/saxes": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz", + "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==", + "dev": true, + "license": "ISC", + "dependencies": { + "xmlchars": "^2.2.0" + }, + "engines": { + "node": ">=v12.22.7" + } + }, "node_modules/semver": { "version": "7.7.3", "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", @@ -10999,6 +11530,13 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, "node_modules/signal-exit": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", @@ -11077,6 +11615,8 @@ "integrity": "sha512-oZ7iUCxph8WYRHHcjBEc9unw3adt5CmSNlppj/5Q4k2RIrhl8Z5yY2Xr4j9zj0+wzVZ0bxmYoGSzKJnRl6A4yg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "accepts": "~1.3.4", "base64id": "~2.0.0", @@ -11096,6 +11636,8 @@ "integrity": "sha512-eLDQas5dzPgOWCk9GuuJC2lBqItuhKI4uxGgo9aIV7MYbk2h9Q6uULEh8WBzThoI7l+qU9Ast9fVUmkqPP9wYg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "debug": "~4.3.4", "ws": "~8.17.1" @@ -11107,6 +11649,8 @@ "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -11125,6 +11669,8 @@ "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=10.0.0" }, @@ -11147,6 +11693,8 @@ "integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "@socket.io/component-emitter": "~3.1.0", "debug": "~4.3.1" @@ -11161,6 +11709,8 @@ "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -11179,6 +11729,8 @@ "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" @@ -11193,6 +11745,8 @@ "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -11211,6 +11765,8 @@ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -11221,6 +11777,8 @@ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "mime-db": "1.52.0" }, @@ -11234,6 +11792,8 @@ "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -11357,6 +11917,13 @@ "node": "^18.17.0 || >=20.5.0" } }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, "node_modules/statuses": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", @@ -11367,6 +11934,13 @@ "node": ">= 0.8" } }, + "node_modules/std-env": { + "version": "3.10.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz", + "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==", + "dev": true, + "license": "MIT" + }, "node_modules/stdin-discarder": { "version": "0.2.2", "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.2.2.tgz", @@ -11386,6 +11960,8 @@ "integrity": "sha512-KFxaM7XT+irxvdqSP1LGLgNWbYN7ay5owZ3r/8t77p+EtSUAfUgtl7be3xtqtOmGUl9K9YPO2ca8133RlTjvKw==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "dependencies": { "date-format": "^4.0.14", "debug": "^4.3.4", @@ -11507,6 +12083,13 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/symbol-tree": { + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz", + "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", + "dev": true, + "license": "MIT" + }, "node_modules/tailwindcss": { "version": "3.4.18", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.18.tgz", @@ -11683,6 +12266,23 @@ "node": ">=0.8" } }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.2.tgz", + "integrity": "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/tinyglobby": { "version": "0.2.15", "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", @@ -11699,12 +12299,44 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, + "node_modules/tinyrainbow": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.0.3.tgz", + "integrity": "sha512-PSkbLUoxOFRzJYjjxHJt9xro7D+iilgMX/C9lawzVuYiIdcihh9DXmVibBe8lmcFrRi/VzlPjBxbN7rH24q8/Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/tldts": { + "version": "7.0.19", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.0.19.tgz", + "integrity": "sha512-8PWx8tvC4jDB39BQw1m4x8y5MH1BcQ5xHeL2n7UVFulMPH/3Q0uiamahFJ3lXA0zO2SUyRXuVVbWSDmstlt9YA==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^7.0.19" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "7.0.19", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.0.19.tgz", + "integrity": "sha512-lJX2dEWx0SGH4O6p+7FPwYmJ/bu1JbcGJ8RLaG9b7liIgZ85itUVEPbMtWRVrde/0fnDPEPHW10ZsKW3kVsE9A==", + "dev": true, + "license": "MIT" + }, "node_modules/tmp": { "version": "0.2.5", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz", "integrity": "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=14.14" } @@ -11731,6 +12363,42 @@ "node": ">=0.6" } }, + "node_modules/tough-cookie": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.0.tgz", + "integrity": "sha512-kXuRi1mtaKMrsLUxz3sQYvVl37B0Ns6MzfrtV5DvJceE9bPyspOqk9xxv7XbZWcfLWbFmm997vl83qUWVJA64w==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "tldts": "^7.0.5" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/tr46": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz", + "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==", + "dev": true, + "license": "MIT", + "dependencies": { + "punycode": "^2.3.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/tr46/node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/ts-api-utils": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz", @@ -11863,6 +12531,8 @@ } ], "license": "MIT", + "optional": true, + "peer": true, "bin": { "ua-parser-js": "script/cli.js" }, @@ -11919,6 +12589,8 @@ "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 4.0.0" } @@ -11996,6 +12668,8 @@ "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">= 0.4.0" } @@ -12604,16 +13278,119 @@ "@esbuild/win32-x64": "0.25.12" } }, + "node_modules/vitest": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.0.16.tgz", + "integrity": "sha512-E4t7DJ9pESL6E3I8nFjPa4xGUd3PmiWDLsDztS2qXSJWfHtbQnwAWylaBvSNY48I3vr8PTqIZlyK8TE3V3CA4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.0.16", + "@vitest/mocker": "4.0.16", + "@vitest/pretty-format": "4.0.16", + "@vitest/runner": "4.0.16", + "@vitest/snapshot": "4.0.16", + "@vitest/spy": "4.0.16", + "@vitest/utils": "4.0.16", + "es-module-lexer": "^1.7.0", + "expect-type": "^1.2.2", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^3.10.0", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.0.3", + "vite": "^6.0.0 || ^7.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.0.16", + "@vitest/browser-preview": "4.0.16", + "@vitest/browser-webdriverio": "4.0.16", + "@vitest/ui": "4.0.16", + "happy-dom": "*", + "jsdom": "*" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + } + } + }, + "node_modules/vitest/node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, "node_modules/void-elements": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/void-elements/-/void-elements-2.0.1.tgz", "integrity": "sha512-qZKX4RnBzH2ugr8Lxa7x+0V6XD9Sb/ouARtiasEQCHB1EVU4NXtmHsDDrx1dO4ne5fc3J6EW05BP1Dl0z0iung==", "dev": true, "license": "MIT", + "optional": true, + "peer": true, "engines": { "node": ">=0.10.0" } }, + "node_modules/w3c-xmlserializer": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", + "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "xml-name-validator": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, "node_modules/watchpack": { "version": "2.4.4", "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.4.4.tgz", @@ -12636,6 +13413,40 @@ "license": "MIT", "optional": true }, + "node_modules/webidl-conversions": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz", + "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=20" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", + "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-15.1.0.tgz", + "integrity": "sha512-2ytDk0kiEj/yu90JOAp44PVPUkO9+jVhyf+SybKlRHSDlvOOZhdPIrr7xTH64l4WixO2cP+wQIcgujkGBPPz6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "tr46": "^6.0.0", + "webidl-conversions": "^8.0.0" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -12652,6 +13463,23 @@ "node": ">= 8" } }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", @@ -12760,6 +13588,23 @@ } } }, + "node_modules/xml-name-validator": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz", + "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/xmlchars": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", + "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", + "dev": true, + "license": "MIT" + }, "node_modules/y18n": { "version": "5.0.8", "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", diff --git a/booklore-ui/package.json b/booklore-ui/package.json index a5bc92046..165c55573 100644 --- a/booklore-ui/package.json +++ b/booklore-ui/package.json @@ -53,18 +53,16 @@ "@angular/compiler-cli": "^21.0.5", "@tailwindcss/typography": "^0.5.19", "@types/jasmine": "^5.1.13", + "@types/node": "^25.0.3", "@types/showdown": "^2.0.6", "angular-eslint": "^21.1.0", "autoprefixer": "^10.4.23", "eslint": "^9.39.2", "jasmine-core": "^5.13.0", - "karma": "^6.4.4", - "karma-chrome-launcher": "^3.2.0", - "karma-coverage": "^2.2.1", - "karma-jasmine": "^5.1.0", - "karma-jasmine-html-reporter": "^2.1.0", + "jsdom": "^27.4.0", "tailwindcss": "^3.4.17", "typescript": "~5.9.3", - "typescript-eslint": "^8.50.0" + "typescript-eslint": "^8.50.0", + "vitest": "^4.0.16" } } diff --git a/booklore-ui/src/app/features/book/service/book-menu.service.spec.ts b/booklore-ui/src/app/features/book/service/book-menu.service.spec.ts new file mode 100644 index 000000000..b44b2f490 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/book-menu.service.spec.ts @@ -0,0 +1,466 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {ConfirmationService, MessageService} from 'primeng/api'; +import {BookService} from './book.service'; +import {LoadingService} from '../../../core/services/loading.service'; +import {User} from '../../settings/user-management/user.service'; +import {ReadStatus} from '../model/book.model'; +import {ResetProgressTypes} from '../../../shared/constants/reset-progress-type'; +import {of, throwError} from 'rxjs'; +import {HttpErrorResponse} from '@angular/common/http'; +import {APIException} from '../../../shared/models/api-exception.model'; +import {BookMenuService} from './book-menu.service'; + +describe('BookMenuService', () => { + 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 items = service.getMetadataMenuItems( + autoFetch, + fetch, + bulkEdit, + multiEdit, + regenerate, + mockUser + ); + + expect(items).toHaveLength(5); + 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'); + }); + + it('should return empty array when user has no permissions', () => { + const items = service.getMetadataMenuItems( + 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(), + 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 items = service.getMetadataMenuItems( + autoFetch, + fetch, + bulkEdit, + multiEdit, + regenerate, + 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(); + }); + + 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(), + 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 new file mode 100644 index 000000000..96945fbc3 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/book-navigation.service.spec.ts @@ -0,0 +1,106 @@ +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 new file mode 100644 index 000000000..a64ca98af --- /dev/null +++ b/booklore-ui/src/app/features/book/service/book-patch.service.spec.ts @@ -0,0 +1,173 @@ +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', 0.8).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpMock.post).toHaveBeenCalledWith(expect.stringContaining('/progress'), { + bookId: 2, + epubProgress: {cfi: 'cfi123', 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-state.service.ts b/booklore-ui/src/app/features/book/service/book-state.service.ts index 114849374..dcf134f7a 100644 --- a/booklore-ui/src/app/features/book/service/book-state.service.ts +++ b/booklore-ui/src/app/features/book/service/book-state.service.ts @@ -1,5 +1,5 @@ import {Injectable} from '@angular/core'; -import {BehaviorSubject, Observable} from 'rxjs'; +import {BehaviorSubject} from 'rxjs'; import {BookState} from '../model/state/book-state.model'; @Injectable({ @@ -22,13 +22,6 @@ export class BookStateService { this.bookStateSubject.next(state); } - updatePartialBookState(partialState: Partial): void { - this.bookStateSubject.next({ - ...this.bookStateSubject.value, - ...partialState - }); - } - resetBookState(): void { this.bookStateSubject.next({ books: null, 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 new file mode 100644 index 000000000..7c83de699 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/book.service.spec.ts @@ -0,0 +1,537 @@ +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'; +import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-request.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, 'ngx'); + expect(routerMock.navigate).toHaveBeenCalledWith(['/pdf-reader/book/1']); + expect(bookPatchServiceMock.updateLastReadTime).toHaveBeenCalledWith(1); + }); + + it('should not navigate if book not found', () => { + bookStateServiceMock.getCurrentBookState.mockReturnValue({books: [], loaded: true, error: null}); + service.readBook(999, 'ngx'); + 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 epub progress', async () => { + bookPatchServiceMock.saveEpubProgress.mockReturnValue(of(void 0)); + const result = await firstValueFrom(service.saveEpubProgress(1, 'cfi', 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 fetch book metadata', async () => { + httpMock.post.mockReturnValue(of([{bookId: 1}])); + const req: FetchMetadataRequest = { + bookId: 1, + providers: [], + title: '', + author: '', + isbn: '' + }; + const result = await firstValueFrom(service.fetchBookMetadata(1, req)); + expect(result).toEqual([{bookId: 1}]); + }); + + it('should update book metadata', async () => { + httpMock.put.mockReturnValue(of({bookId: 1})); + service.handleBookMetadataUpdate = vi.fn(); + const result = await firstValueFrom(service.updateBookMetadata(1, {} as any, true)); + expect(result).toEqual({bookId: 1}); + expect(service.handleBookMetadataUpdate).toHaveBeenCalledWith(1, {bookId: 1}); + }); + + 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 upload cover from url and handleBookMetadataUpdate', async () => { + httpMock.post.mockReturnValue(of({bookId: 1})); + service.handleBookMetadataUpdate = vi.fn(); + const result = await firstValueFrom(service.uploadCoverFromUrl(1, 'url')); + expect(result).toEqual({bookId: 1}); + expect(service.handleBookMetadataUpdate).toHaveBeenCalledWith(1, {bookId: 1}); + }); + + 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/cbx-reader.service.spec.ts b/booklore-ui/src/app/features/book/service/cbx-reader.service.spec.ts new file mode 100644 index 000000000..10654f131 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/cbx-reader.service.spec.ts @@ -0,0 +1,96 @@ +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/library-shelf-menu.service.spec.ts b/booklore-ui/src/app/features/book/service/library-shelf-menu.service.spec.ts new file mode 100644 index 000000000..449efcbd6 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/library-shelf-menu.service.spec.ts @@ -0,0 +1,350 @@ +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.service.spec.ts b/booklore-ui/src/app/features/book/service/library.service.spec.ts new file mode 100644 index 000000000..e06c30c05 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/library.service.spec.ts @@ -0,0 +1,167 @@ +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/library.service.ts b/booklore-ui/src/app/features/book/service/library.service.ts index f1711934c..55e03da89 100644 --- a/booklore-ui/src/app/features/book/service/library.service.ts +++ b/booklore-ui/src/app/features/book/service/library.service.ts @@ -133,7 +133,6 @@ export class LibraryService { ); } - doesLibraryExistByName(name: string): boolean { return (this.libraryStateSubject.value.libraries || []).some(l => l.name === name); } @@ -146,12 +145,6 @@ export class LibraryService { return this.libraryStateSubject.value.libraries || []; } - getLibraryPathById(pathId: number): string | undefined { - return this.libraryStateSubject.value.libraries - ?.find(lib => lib.paths.some(p => p.id === pathId)) - ?.paths.find(p => p.id === pathId)?.path; - } - getBookCount(libraryId: number): Observable { return this.bookService.bookState$.pipe( map(state => (state.books || []).filter(b => b.libraryId === libraryId).length) 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 new file mode 100644 index 000000000..e167f6c04 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/metadata-task.spec.ts @@ -0,0 +1,123 @@ +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 new file mode 100644 index 000000000..e76f2a994 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/new-pdf-reader.service.spec.ts @@ -0,0 +1,70 @@ +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/shelf.service.spec.ts b/booklore-ui/src/app/features/book/service/shelf.service.spec.ts new file mode 100644 index 000000000..4295fa488 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/shelf.service.spec.ts @@ -0,0 +1,129 @@ +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, firstValueFrom} from 'rxjs'; + +import {ShelfService} from './shelf.service'; +import {BookService} from './book.service'; +import {Shelf} from '../model/shelf.model'; + +describe('ShelfService', () => { + let service: ShelfService; + let httpClientMock: any; + let bookServiceMock: 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} + ] + }) + }; + + TestBed.configureTestingModule({ + providers: [ + ShelfService, + {provide: HttpClient, useValue: httpClientMock}, + {provide: BookService, useValue: bookServiceMock} + ] + }); + + 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 book count for shelf', async () => { + const count = await firstValueFrom(service.getBookCount(10)); + expect(count).toBe(1); + }); + + 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 new file mode 100644 index 000000000..7c1d15e91 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/sort.service.spec.ts @@ -0,0 +1,142 @@ +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 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/tsconfig.spec.json b/booklore-ui/tsconfig.spec.json index 5fb748d92..64e3a73bc 100644 --- a/booklore-ui/tsconfig.spec.json +++ b/booklore-ui/tsconfig.spec.json @@ -1,10 +1,9 @@ -/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */ -/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */ { "extends": "./tsconfig.json", "compilerOptions": { "outDir": "./out-tsc/spec", "types": [ + "node", "jasmine" ] }, From cee7e96c63eb99dc9abce3b6bc0651d0d43d87e6 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Sun, 4 Jan 2026 22:55:13 -0700 Subject: [PATCH 03/40] Add Vitest frontend tests to CI with JUnit reporting and coverage (#2151) Co-authored-by: acx10 --- .github/workflows/develop-pipeline.yml | 100 +++++++++++++++--- .github/workflows/master-pipeline.yml | 16 ++- .gitignore | 1 + booklore-ui/angular.json | 5 +- booklore-ui/package-lock.json | 141 +++++++++++++++++++++++++ booklore-ui/package.json | 1 + booklore-ui/vitest-base.config.ts | 10 ++ 7 files changed, 255 insertions(+), 19 deletions(-) create mode 100644 booklore-ui/vitest-base.config.ts diff --git a/.github/workflows/develop-pipeline.yml b/.github/workflows/develop-pipeline.yml index db3f7a93f..41e573de6 100644 --- a/.github/workflows/develop-pipeline.yml +++ b/.github/workflows/develop-pipeline.yml @@ -20,31 +20,20 @@ jobs: base_ref: 'origin/develop' head_ref: 'HEAD' - build-and-push: + backend-tests: + name: Backend Tests needs: [ migration-check ] if: needs.migration-check.result == 'success' || needs.migration-check.result == 'skipped' runs-on: ubuntu-latest permissions: contents: read - packages: write checks: write pull-requests: write steps: - name: Checkout Repository uses: actions/checkout@v6 - with: - fetch-depth: 0 - - # ---------------------------------------- - # Environment setup - # ---------------------------------------- - - name: Set Up QEMU for Multi-Arch Builds - uses: docker/setup-qemu-action@v3 - - - name: Set Up Docker Buildx - uses: docker/setup-buildx-action@v3 - name: Set Up JDK 21 uses: actions/setup-java@v5 @@ -53,9 +42,6 @@ jobs: distribution: 'temurin' cache: gradle - # ---------------------------------------- - # Backend tests - # ---------------------------------------- - name: Execute Backend Tests id: backend_tests working-directory: ./booklore-api @@ -75,7 +61,7 @@ jobs: uses: actions/upload-artifact@v6 if: always() with: - name: test-reports + name: backend-test-reports path: | booklore-api/build/reports/tests/ booklore-api/build/test-results/ @@ -87,6 +73,86 @@ jobs: echo "❌ Backend tests failed" exit 1 + frontend-tests: + name: Frontend Tests + needs: [ migration-check ] + if: needs.migration-check.result == 'success' || needs.migration-check.result == 'skipped' + runs-on: ubuntu-latest + + permissions: + contents: read + checks: write + pull-requests: write + + steps: + - name: Checkout Repository + uses: actions/checkout@v6 + + - name: Set Up Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + cache: 'npm' + cache-dependency-path: booklore-ui/package-lock.json + + - name: Install Frontend Dependencies + working-directory: ./booklore-ui + run: npm ci --force + + - name: Execute Frontend Tests + id: frontend_tests + working-directory: ./booklore-ui + run: | + echo "Running frontend tests..." + npx ng test + continue-on-error: true + + - name: Publish Frontend Test Results + uses: EnricoMi/publish-unit-test-result-action@v2 + if: always() + with: + files: booklore-ui/test-results/vitest-results.xml + check_name: Frontend Test Results + + - name: Upload Frontend Test Reports + uses: actions/upload-artifact@v6 + if: always() + with: + name: frontend-test-reports + path: | + booklore-ui/test-results/vitest-results.xml + retention-days: 30 + + - name: Validate Frontend Test Results + if: steps.frontend_tests.outcome == 'failure' + run: | + echo "❌ Frontend tests failed" + exit 1 + + build-and-push: + name: Build and Push Container + needs: [ backend-tests, frontend-tests ] + runs-on: ubuntu-latest + + permissions: + contents: read + packages: write + + steps: + - name: Checkout Repository + uses: actions/checkout@v6 + with: + fetch-depth: 0 + + # ---------------------------------------- + # Environment setup + # ---------------------------------------- + - name: Set Up QEMU for Multi-Arch Builds + uses: docker/setup-qemu-action@v3 + + - name: Set Up Docker Buildx + uses: docker/setup-buildx-action@v3 + # ---------------------------------------- # Image tagging # ---------------------------------------- diff --git a/.github/workflows/master-pipeline.yml b/.github/workflows/master-pipeline.yml index 808d236af..b60182ad8 100644 --- a/.github/workflows/master-pipeline.yml +++ b/.github/workflows/master-pipeline.yml @@ -69,6 +69,21 @@ jobs: distribution: 'temurin' cache: 'gradle' + - name: Set Up Node.js + uses: actions/setup-node@v4 + with: + node-version: '22' + cache: 'npm' + cache-dependency-path: booklore-ui/package-lock.json + + - name: Install Frontend Dependencies + working-directory: ./booklore-ui + run: npm ci --force + + - name: Execute Frontend Tests + working-directory: ./booklore-ui + run: npm run test:ci + - name: Retrieve Latest Master Version Tag id: get_version run: | @@ -166,4 +181,3 @@ jobs: GITHUB_TOKEN: ${{ github.token }} run: | gh release edit ${{ env.new_tag }} --draft=true - diff --git a/.gitignore b/.gitignore index 0058372b9..d6f72fbe0 100644 --- a/.gitignore +++ b/.gitignore @@ -42,5 +42,6 @@ out/ local/ ### Dev config, books, and data ### +booklore-ui/test-results/ booklore-api/src/main/resources/application-local.yaml /shared/ \ No newline at end of file diff --git a/booklore-ui/angular.json b/booklore-ui/angular.json index 7ad3647fc..5cb7cc473 100644 --- a/booklore-ui/angular.json +++ b/booklore-ui/angular.json @@ -106,7 +106,10 @@ "builder": "@angular/build:extract-i18n" }, "test": { - "builder": "@angular/build:unit-test" + "builder": "@angular/build:unit-test", + "options": { + "runnerConfig": "vitest-base.config.ts" + } }, "lint": { "builder": "@angular-eslint/builder:lint", diff --git a/booklore-ui/package-lock.json b/booklore-ui/package-lock.json index 15bd2683b..3bba785f4 100644 --- a/booklore-ui/package-lock.json +++ b/booklore-ui/package-lock.json @@ -51,6 +51,7 @@ "@types/jasmine": "^5.1.13", "@types/node": "^25.0.3", "@types/showdown": "^2.0.6", + "@vitest/coverage-v8": "^4.0.16", "angular-eslint": "^21.1.0", "autoprefixer": "^10.4.23", "eslint": "^9.39.2", @@ -1170,6 +1171,16 @@ "node": ">=6.9.0" } }, + "node_modules/@bcoe/v8-coverage": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz", + "integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, "node_modules/@colors/colors": { "version": "1.5.0", "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", @@ -4942,6 +4953,38 @@ "vite": "^6.0.0 || ^7.0.0" } }, + "node_modules/@vitest/coverage-v8": { + "version": "4.0.16", + "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.0.16.tgz", + "integrity": "sha512-2rNdjEIsPRzsdu6/9Eq0AYAzYdpP6Bx9cje9tL3FE5XzXRQF1fNU9pe/1yE8fCrS0HD+fBtt6gLPh6LI57tX7A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@bcoe/v8-coverage": "^1.0.2", + "@vitest/utils": "4.0.16", + "ast-v8-to-istanbul": "^0.3.8", + "istanbul-lib-coverage": "^3.2.2", + "istanbul-lib-report": "^3.0.1", + "istanbul-lib-source-maps": "^5.0.6", + "istanbul-reports": "^3.2.0", + "magicast": "^0.5.1", + "obug": "^2.1.1", + "std-env": "^3.10.0", + "tinyrainbow": "^3.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@vitest/browser": "4.0.16", + "vitest": "4.0.16" + }, + "peerDependenciesMeta": { + "@vitest/browser": { + "optional": true + } + } + }, "node_modules/@vitest/expect": { "version": "4.0.16", "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.0.16.tgz", @@ -5354,6 +5397,25 @@ "node": ">=12" } }, + "node_modules/ast-v8-to-istanbul": { + "version": "0.3.10", + "resolved": "https://registry.npmjs.org/ast-v8-to-istanbul/-/ast-v8-to-istanbul-0.3.10.tgz", + "integrity": "sha512-p4K7vMz2ZSk3wN8l5o3y2bJAoZXT3VuJI5OLTATY/01CYWumWvwkUw0SqDBnNq6IiTO3qDa1eSQDibAV8g7XOQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "estree-walker": "^3.0.3", + "js-tokens": "^9.0.1" + } + }, + "node_modules/ast-v8-to-istanbul/node_modules/js-tokens": { + "version": "9.0.1", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz", + "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==", + "dev": true, + "license": "MIT" + }, "node_modules/autoprefixer": { "version": "10.4.23", "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.4.23.tgz", @@ -7906,6 +7968,13 @@ "node": "^20.19.0 || ^22.12.0 || >=24.0.0" } }, + "node_modules/html-escaper": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", + "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", + "dev": true, + "license": "MIT" + }, "node_modules/htmlparser2": { "version": "10.0.0", "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.0.0.tgz", @@ -8347,6 +8416,50 @@ "node": ">=10" } }, + "node_modules/istanbul-lib-report": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", + "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "istanbul-lib-coverage": "^3.0.0", + "make-dir": "^4.0.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-lib-source-maps": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-5.0.6.tgz", + "integrity": "sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.23", + "debug": "^4.1.1", + "istanbul-lib-coverage": "^3.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/istanbul-reports": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", + "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "html-escaper": "^2.0.0", + "istanbul-lib-report": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/jasmine-core": { "version": "5.13.0", "resolved": "https://registry.npmjs.org/jasmine-core/-/jasmine-core-5.13.0.tgz", @@ -9309,6 +9422,34 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/magicast": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/magicast/-/magicast-0.5.1.tgz", + "integrity": "sha512-xrHS24IxaLrvuo613F719wvOIv9xPHFWQHuvGUBmPnCA/3MQxKI3b+r7n1jAoDHmsbC5bRhTZYR77invLAxVnw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.28.5", + "@babel/types": "^7.28.5", + "source-map-js": "^1.2.1" + } + }, + "node_modules/make-dir": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", + "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/make-fetch-happen": { "version": "15.0.3", "resolved": "https://registry.npmjs.org/make-fetch-happen/-/make-fetch-happen-15.0.3.tgz", diff --git a/booklore-ui/package.json b/booklore-ui/package.json index 165c55573..69be34c35 100644 --- a/booklore-ui/package.json +++ b/booklore-ui/package.json @@ -55,6 +55,7 @@ "@types/jasmine": "^5.1.13", "@types/node": "^25.0.3", "@types/showdown": "^2.0.6", + "@vitest/coverage-v8": "^4.0.16", "angular-eslint": "^21.1.0", "autoprefixer": "^10.4.23", "eslint": "^9.39.2", diff --git a/booklore-ui/vitest-base.config.ts b/booklore-ui/vitest-base.config.ts new file mode 100644 index 000000000..f56002ba6 --- /dev/null +++ b/booklore-ui/vitest-base.config.ts @@ -0,0 +1,10 @@ +import {defineConfig} from 'vitest/config'; + +export default defineConfig({ + test: { + reporters: [ + ['default', {summary: false}], + ['junit', {outputFile: 'test-results/vitest-results.xml'}] + ] + }, +}); From f8d40907387932654d7ca5304cf24c98fae84040 Mon Sep 17 00:00:00 2001 From: acx10 Date: Sun, 4 Jan 2026 23:02:00 -0700 Subject: [PATCH 04/40] Update PR template to capture frontend test details --- .github/pull_request_template.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index cfeb61041..fa85ebacb 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -34,8 +34,8 @@ - [ ] **Code adheres to project style guidelines and conventions** - [ ] **Branch synchronized with latest `develop` branch** _(please resolve any merge conflicts)_ -- [ ] **🚨 CRITICAL: Automated unit/integration tests added/updated to cover changes** _(MANDATORY for ALL backend changes - this is non-negotiable)_ -- [ ] **🚨 CRITICAL: All tests pass locally** _(run `./gradlew test` for backend - NO EXCEPTIONS)_ +- [ ] **🚨 CRITICAL: Automated unit tests added/updated to cover changes** _(MANDATORY for ALL Spring Boot backend and Angular frontend changes - this is non-negotiable)_ +- [ ] **🚨 CRITICAL: All tests pass locally** _(run `./gradlew test` for Spring Boot backend, and `ng test` for Angular frontend - NO EXCEPTIONS)_ - [ ] **🚨 CRITICAL: Manual testing completed in local development environment** _(verify your changes work AND no existing functionality is broken - test related features thoroughly)_ - [ ] **Flyway migration versioning follows correct sequence** _(if database schema was modified)_ - [ ] **Documentation PR submitted to [booklore-docs](https://github.com/booklore-app/booklore-docs)** _(required for features or enhancements that introduce user-facing or visual changes)_ From e346b83860dcd457b5c897cb0ca0a5e029140900 Mon Sep 17 00:00:00 2001 From: acx10 Date: Sun, 4 Jan 2026 23:08:32 -0700 Subject: [PATCH 05/40] Add instructions for running Angular frontend tests --- CONTRIBUTING.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index eeeb2dc0a..2d66f77ca 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -197,6 +197,24 @@ curl http://localhost:8080/actuator/health Always run tests before submitting a pull request to ensure your changes don't break existing functionality. +### Frontend Tests (Angular + Vitest) + +Booklore uses [Vitest](https://vitest.dev/) for fast, modern frontend testing in the Angular app. + +```bash +cd booklore-ui + +# Run all frontend tests +ng test + +# Run tests with coverage report +ng test --coverage +``` + +- The coverage report will be generated in the `coverage/` directory. +- You can open `coverage/index.html` in your browser to view detailed coverage metrics. +- All new features and bug fixes should include relevant unit tests. + ### Backend Tests ```bash From a103e3eaa06d540b64d519efbfd1d2734077586b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= <127139797+balazs-szucs@users.noreply.github.com> Date: Mon, 5 Jan 2026 22:26:10 +0100 Subject: [PATCH 06/40] fix(docs): update issue report links to use specific templates (#2156) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Balázs Szücs --- README.md | 4 ++-- docs/OIDC-Setup-With-PocketID.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5d0910f4f..bf185be17 100644 --- a/README.md +++ b/README.md @@ -354,7 +354,7 @@ services: Found an issue? -[![Open Issue](https://img.shields.io/badge/Report-ff6b6b?style=for-the-badge)](https://github.com/booklore-app/booklore/issues) +[![Open Issue](https://img.shields.io/badge/Report-ff6b6b?style=for-the-badge)](https://github.com/booklore-app/booklore/issues/new?template=bug_report.yml) @@ -363,7 +363,7 @@ Found an issue? Have an idea? -[![Request Feature](https://img.shields.io/badge/Suggest-4ecdc4?style=for-the-badge)](https://github.com/booklore-app/booklore/issues/new?template=feature_request.md) +[![Request Feature](https://img.shields.io/badge/Suggest-4ecdc4?style=for-the-badge)](https://github.com/booklore-app/booklore/issues/new?template=feature_request.yml) diff --git a/docs/OIDC-Setup-With-PocketID.md b/docs/OIDC-Setup-With-PocketID.md index 9bf58f16d..154c9c40c 100644 --- a/docs/OIDC-Setup-With-PocketID.md +++ b/docs/OIDC-Setup-With-PocketID.md @@ -53,4 +53,4 @@ To enable OIDC authentication in BookLore, you need to set the following within ### Step 4: Test the Integration -Once configured, simply click Save Settings and then click the Enabled radio button to activate it. Simply log out and log back in and you should be working with no issues! Any issues please raise an issue on the [Github](https://github.com/booklore-app/booklore/issues/new) +Once configured, simply click Save Settings and then click the Enabled radio button to activate it. Simply log out and log back in and you should be working with no issues! Any issues please raise an issue on the [Github](https://github.com/booklore-app/booklore/issues/new?template=bug_report.yml) From 34bbe8a14ed9144999d49f8c5d793c3a8b1b8f23 Mon Sep 17 00:00:00 2001 From: CounterClops <19741838+CounterClops@users.noreply.github.com> Date: Tue, 6 Jan 2026 05:26:41 +0800 Subject: [PATCH 07/40] fix(api): kobo proxy server unit tests (#2136) * fix: resolve issue with kobo proxy failing to reencode encoded query params * fix: add additional tests for kobo server proxy --- .../service/kobo/KoboServerProxyTest.java | 257 ++++++++++++++++++ 1 file changed, 257 insertions(+) create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboServerProxyTest.java diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboServerProxyTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboServerProxyTest.java new file mode 100644 index 000000000..86ecda741 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboServerProxyTest.java @@ -0,0 +1,257 @@ +package com.adityachandel.booklore.service.kobo; + +import com.adityachandel.booklore.model.dto.BookloreSyncToken; +import com.adityachandel.booklore.model.dto.kobo.KoboHeaders; +import com.adityachandel.booklore.util.kobo.BookloreSyncTokenGenerator; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +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.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.server.ResponseStatusException; + +import java.lang.reflect.Field; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.Collections; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.*; + +@ExtendWith(MockitoExtension.class) +class KoboServerProxyTest { + + @Mock + private ObjectMapper objectMapper; + + @Mock + private BookloreSyncTokenGenerator bookloreSyncTokenGenerator; + + @Mock + private HttpClient httpClient; + + @Mock + private HttpResponse httpResponse; + + @Mock + private HttpResponse httpResponseBytes; + + @InjectMocks + private KoboServerProxy koboServerProxy; + + private MockHttpServletRequest mockRequest; + + @BeforeEach + void setUp() throws Exception { + mockRequest = new MockHttpServletRequest(); + mockRequest.setMethod("GET"); + mockRequest.setRequestURI("/api/kobo/v1/library/sync"); + + RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(mockRequest)); + + Field httpClientField = KoboServerProxy.class.getDeclaredField("httpClient"); + httpClientField.setAccessible(true); + httpClientField.set(koboServerProxy, httpClient); + } + + @AfterEach + void tearDown() { + RequestContextHolder.resetRequestAttributes(); + } + + private void setupSuccessfulProxyResponse() throws Exception { + when(httpResponse.statusCode()).thenReturn(200); + when(httpResponse.body()).thenReturn("{}"); + when(httpResponse.headers()).thenReturn(java.net.http.HttpHeaders.of( + Collections.emptyMap(), + (k, v) -> true + )); + when(objectMapper.readTree(anyString())).thenReturn(mock(JsonNode.class)); + when(httpClient.send(any(HttpRequest.class), any())) + .thenReturn(httpResponse); + } + + @Test + void proxyCurrentRequest_withSquareBracketsInQueryParams_shouldHandleSuccessfully() throws Exception { + // Validates fix for: IllegalArgumentException: Invalid character '[' for QUERY_PARAM + String problematicQuery = "Filters=[%7BKey:TestKey,ETag:W/TestEtagValue123%7D]"; + mockRequest.setQueryString(problematicQuery); + mockRequest.addHeader("User-Agent", "Kobo/1.0"); + setupSuccessfulProxyResponse(); + + ResponseEntity response = koboServerProxy.proxyCurrentRequest(null, false); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + verify(httpClient).send(any(HttpRequest.class), any()); + } + + @Test + void proxyCurrentRequest_withVariousEncodedQueryParams_shouldHandleSuccessfully() throws Exception { + String[] testQueries = { + "Filters=%5B%7BKey:TestKey%7D%5D", // Properly encoded brackets + "Filter=ALL&DownloadUrlFilter=Generic,Android&PrioritizeRecentReads=true", // Real Kobo params + "page_index=0&page_size=50&Filters=%7B%7D" // URL-encoded JSON + }; + + for (String query : testQueries) { + mockRequest.setQueryString(query); + setupSuccessfulProxyResponse(); + + ResponseEntity response = koboServerProxy.proxyCurrentRequest(null, false); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + } + + verify(httpClient, times(testQueries.length)).send(any(HttpRequest.class), any()); + } + + @Test + void proxyCurrentRequest_withSyncToken_shouldPreserveAndUpdateToken() throws Exception { + mockRequest.setQueryString("Filter=ALL"); + mockRequest.addHeader(KoboHeaders.X_KOBO_SYNCTOKEN, "original-token"); + + BookloreSyncToken mockSyncToken = BookloreSyncToken.builder() + .rawKoboSyncToken("kobo-sync-token") + .ongoingSyncPointId("1") + .lastSuccessfulSyncPointId("0") + .build(); + + when(bookloreSyncTokenGenerator.fromRequestHeaders(any())).thenReturn(mockSyncToken); + when(httpResponse.statusCode()).thenReturn(200); + when(httpResponse.body()).thenReturn("{}"); + when(httpResponse.headers()).thenReturn(java.net.http.HttpHeaders.of( + Map.of(KoboHeaders.X_KOBO_SYNCTOKEN, java.util.List.of("new-kobo-token")), + (k, v) -> true + )); + when(objectMapper.readTree(anyString())).thenReturn(mock(JsonNode.class)); + when(bookloreSyncTokenGenerator.toBase64(any())).thenReturn("encoded-sync-token"); + when(httpClient.send(any(HttpRequest.class), any())) + .thenReturn(httpResponse); + + ResponseEntity response = koboServerProxy.proxyCurrentRequest(null, true); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + verify(bookloreSyncTokenGenerator).toBase64(any(BookloreSyncToken.class)); + } + + @Test + void proxyCurrentRequest_shouldPreserveKoboHeaders() throws Exception { + mockRequest.addHeader("X-Kobo-DeviceId", "device123"); + mockRequest.addHeader("X-Kobo-UserKey", "user456"); + + when(httpResponse.statusCode()).thenReturn(200); + when(httpResponse.body()).thenReturn("{}"); + when(httpResponse.headers()).thenReturn(java.net.http.HttpHeaders.of( + Map.of("X-Kobo-Response", java.util.List.of("test")), + (k, v) -> true + )); + when(objectMapper.readTree(anyString())).thenReturn(mock(JsonNode.class)); + when(httpClient.send(any(HttpRequest.class), any())) + .thenReturn(httpResponse); + + ResponseEntity response = koboServerProxy.proxyCurrentRequest(null, false); + + assertThat(response).isNotNull(); + assertThat(response.getHeaders()).containsKey("X-Kobo-Response"); + } + + @Test + void proxyCurrentRequest_withPostBody_shouldSerializeBody() throws Exception { + mockRequest.setMethod("POST"); + Object requestBody = new Object(); + + when(objectMapper.writeValueAsString(requestBody)).thenReturn("{\"test\":\"value\"}"); + setupSuccessfulProxyResponse(); + + ResponseEntity response = koboServerProxy.proxyCurrentRequest(requestBody, false); + + assertThat(response).isNotNull(); + verify(objectMapper).writeValueAsString(requestBody); + } + + @Test + void proxyCurrentRequest_with400Response_shouldPreserveStatusCode() throws Exception { + mockRequest.setQueryString("ExcludeOwned=false&PageSize=100"); + + when(httpResponse.statusCode()).thenReturn(400); + when(httpResponse.body()).thenReturn("{\"error\":\"Bad Request\"}"); + when(httpResponse.headers()).thenReturn(java.net.http.HttpHeaders.of( + Collections.emptyMap(), + (k, v) -> true + )); + when(objectMapper.readTree(anyString())).thenReturn(mock(JsonNode.class)); + when(httpClient.send(any(HttpRequest.class), any())) + .thenReturn(httpResponse); + + ResponseEntity response = koboServerProxy.proxyCurrentRequest(null, false); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.BAD_REQUEST); + } + + @Test + void proxyCurrentRequest_withMaliciousQueryParams_shouldHandleSafely() throws Exception { + String[] maliciousQueries = { + "param1=value1%0D%0AHost:evil.com", // CRLF injection attempt + "text=%3Cscript%3Ealert('xss')%3C/script%3E&other=%22quotes%22" // XSS attempt + }; + + for (String query : maliciousQueries) { + mockRequest.setQueryString(query); + setupSuccessfulProxyResponse(); + + ResponseEntity response = koboServerProxy.proxyCurrentRequest(null, false); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + } + } + + @Test + void proxyExternalUrl_shouldFetchAndReturnImage() throws Exception { + String testUrl = "https://cdn.kobo.com/image123.jpg"; + byte[] imageData = {1, 2, 3, 4, 5}; + + when(httpResponseBytes.statusCode()).thenReturn(200); + when(httpResponseBytes.body()).thenReturn(imageData); + when(httpClient.send(any(HttpRequest.class), any())) + .thenReturn(httpResponseBytes); + + ResponseEntity response = koboServerProxy.proxyExternalUrl(testUrl); + + assertThat(response).isNotNull(); + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getBody()).isNotNull(); + assertThat(response.getBody().contentLength()).isEqualTo(5); + } + + @Test + void proxyExternalUrl_withException_shouldThrowResponseStatusException() throws Exception { + String testUrl = "https://cdn.kobo.com/image123.jpg"; + + when(httpClient.send(any(HttpRequest.class), any())) + .thenThrow(new java.io.IOException("Network error")); + + assertThatThrownBy(() -> koboServerProxy.proxyExternalUrl(testUrl)) + .isInstanceOf(ResponseStatusException.class) + .hasMessageContaining("Failed to fetch image"); + } +} From 9a498da2badd6713f03fe7f11401cadaa16d8cdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= <127139797+balazs-szucs@users.noreply.github.com> Date: Mon, 5 Jan 2026 22:27:26 +0100 Subject: [PATCH 08/40] feat(cover-generator): enhance cover resolution and redesign layout for improved aesthetics (#2125) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Balázs Szücs --- .../service/metadata/CoverImageGenerator.java | 797 ++++++++++++++---- 1 file changed, 655 insertions(+), 142 deletions(-) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/CoverImageGenerator.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/CoverImageGenerator.java index 4eb20888d..40cdd230b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/CoverImageGenerator.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/CoverImageGenerator.java @@ -9,7 +9,7 @@ import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.ImageOutputStream; import java.awt.*; -import java.awt.geom.Rectangle2D; +import java.awt.geom.*; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -21,168 +21,681 @@ import java.util.regex.Pattern; @Service public class CoverImageGenerator { - private static final int WIDTH = 250; - private static final int HEIGHT = 350; - private static final int PADDING = 20; - private static final int TITLE_TOP_MARGIN = 40; - private static final int TITLE_PADDING = 15; - private static final int AUTHOR_BOTTOM_MARGIN = 330; - private static final int MAX_LINES = 5; - private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+"); + private static final int WIDTH = 1200; + private static final int HEIGHT = 1600; + private static final int SCALE = 2; + private static final double PHI = 1.618033988749; + private static final double PHI_INV = 1.0 / PHI; + private static final double PHI_SQ_INV = 1.0 / (PHI * PHI); + private static final int MAX_TITLE_LINES = 5; + private static final int MAX_AUTHOR_LINES = 2; + private static final int MAX_TITLE_LEN = 200; + private static final int MAX_AUTHOR_LEN = 100; + private static final int MIN_FONT = 36 * SCALE; + private static final Pattern WS = Pattern.compile("\\s+"); public byte[] generateCover(String title, String author) { - BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); - Graphics2D g2d = image.createGraphics(); - - g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - - Color[] colors = getColorScheme(title); - Color bgColor1 = colors[0]; - Color bgColor2 = colors[1]; - - GradientPaint backgroundGradient = new GradientPaint( - 0, 0, bgColor1, - 0, HEIGHT, bgColor2 - ); - g2d.setPaint(backgroundGradient); - g2d.fillRect(0, 0, WIDTH, HEIGHT); - - String effectiveTitle = title != null && !title.isBlank() ? title : "Unknown Title"; - String effectiveAuthor = author != null && !author.isBlank() ? author : "Unknown Author"; - - Font titleFont = getTitleFont(effectiveTitle.length()); - g2d.setFont(titleFont); - FontMetrics titleFm = g2d.getFontMetrics(); - - List titleLines = wrapText(effectiveTitle, titleFm); - int titleLineHeight = titleFm.getHeight(); - int titleBoxHeight = (titleLines.size() * titleLineHeight) + (TITLE_PADDING * 2); - - GradientPaint titleBgGradient = new GradientPaint( - 0, TITLE_TOP_MARGIN, new Color(221, 221, 221), // #dddddd - 0, TITLE_TOP_MARGIN + titleBoxHeight, new Color(223, 223, 223, 153) // #dfdfdf with 0.6 opacity - ); - g2d.setPaint(titleBgGradient); - g2d.fillRect(0, TITLE_TOP_MARGIN, WIDTH, titleBoxHeight); - - g2d.setColor(Color.BLACK); - int currentY = TITLE_TOP_MARGIN + TITLE_PADDING + titleFm.getAscent(); - for (String line : titleLines) { - g2d.drawString(line, PADDING, currentY); - currentY += titleLineHeight; - } - - Font authorFont = getAuthorFont(effectiveAuthor.length()); - g2d.setFont(authorFont); - FontMetrics authorFm = g2d.getFontMetrics(); - - List authorLines = wrapText(effectiveAuthor, authorFm); - int authorLineHeight = authorFm.getHeight(); - int authorStartY = AUTHOR_BOTTOM_MARGIN - ((authorLines.size() - 1) * authorLineHeight); - - g2d.setColor(Color.BLACK); - for (int i = 0; i < authorLines.size(); i++) { - String line = authorLines.get(i); - Rectangle2D rect = authorFm.getStringBounds(line, g2d); - int x = WIDTH - PADDING - (int) rect.getWidth(); // Right align - g2d.drawString(line, x, authorStartY + (i * authorLineHeight)); - } - - g2d.dispose(); - - return writeHighQualityJpeg(image); + return generateCover(title, author, null); } - private byte[] writeHighQualityJpeg(BufferedImage image) { - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - ImageWriter writer = ImageIO.getImageWritersByFormatName("jpg").next(); - ImageWriteParam param = writer.getDefaultWriteParam(); - param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); - param.setCompressionQuality(0.95f); // High quality + public byte[] generateCover(String title, String author, String subtitle) { + BufferedImage render = null; + BufferedImage result = null; + Graphics2D g = null; - try (ImageOutputStream ios = ImageIO.createImageOutputStream(baos)) { - writer.setOutput(ios); - writer.write(null, new IIOImage(image, null, null), param); - writer.dispose(); - return baos.toByteArray(); - } - } catch (IOException e) { - log.error("Failed to generate cover image", e); - throw new RuntimeException("Failed to generate cover image", e); - } - } - - private Font getTitleFont(int length) { try { - Font font = new Font("Georgia", Font.BOLD, getTitleFontSize(length)); - if (font.getFamily().equals("Georgia")) return font; + String safeTitle = sanitize(title, MAX_TITLE_LEN, "Unknown Title"); + String safeAuthor = sanitize(author, MAX_AUTHOR_LEN, "Unknown Author"); + String safeSubtitle = sanitize(subtitle, MAX_TITLE_LEN, ""); // Using title length limit for subtitle + + int w = WIDTH * SCALE; + int h = HEIGHT * SCALE; + + render = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); + g = render.createGraphics(); + + try { + configureGraphics(g); + Palette p = selectPalette(safeTitle); + int margin = calcMargin(w); + + renderBaseGradient(g, p, w, h); + renderDepthGradient(g, p, w, h); + renderGlow(g, p, w, h); + renderBokeh(g, p, w, h); + renderTexture(g, w, h); + renderFrame(g, p, w, h); + int titleEnd = renderTitle(g, safeTitle, p, w, h, margin); + int subtitleEnd = titleEnd; + if (safeSubtitle != null && !safeSubtitle.isEmpty()) { + subtitleEnd = renderSubtitle(g, safeSubtitle, p, w, h, margin, titleEnd); + } + renderDivider(g, p, w, subtitleEnd, h); + renderAuthor(g, safeAuthor, p, w, h, margin); + renderVignette(g, w, h); + renderEdges(g, w, h); + + } finally { + if (g != null) g.dispose(); + } + + result = downscale(render); + render.flush(); + render = null; + + return encodeJpeg(result); + } catch (Exception e) { - log.warn("Failed to load preferred font, using fallback"); + log.error("Cover generation failed: {}", title, e); + throw new RuntimeException("Cover generation failed", e); + } finally { + cleanup(g, render, result); } - return new Font(Font.SERIF, Font.BOLD, getTitleFontSize(length)); } - private int getTitleFontSize(int length) { - if (length < 20) return 36; - if (length < 40) return 30; - return 24; + private record Palette(Color primary, Color secondary, Color tertiary, Color accent, + Color textMain, Color textSub, Color ornament) {} + + private int calcMargin(int w) { + int frameOuter = (int) (w * PHI_SQ_INV * 0.12); + int frameInner = (int) (frameOuter * PHI); + return frameInner + (int) (w * 0.04); } - private Font getAuthorFont(int length) { - if (length < 20) return new Font(Font.SANS_SERIF, Font.PLAIN, 28); - return new Font(Font.SANS_SERIF, Font.PLAIN, 22); + private Palette selectPalette(String title) { + Palette[] palettes = { + new Palette(new Color(20, 30, 55), new Color(40, 55, 90), new Color(30, 42, 72), + new Color(218, 180, 120), new Color(252, 250, 245), new Color(210, 200, 185), new Color(190, 165, 110)), + new Palette(new Color(70, 30, 40), new Color(105, 50, 60), new Color(85, 40, 50), + new Color(230, 205, 175), new Color(255, 252, 248), new Color(225, 215, 200), new Color(200, 175, 145)), + new Palette(new Color(25, 50, 45), new Color(45, 80, 70), new Color(35, 65, 57), + new Color(205, 190, 150), new Color(250, 248, 242), new Color(215, 210, 195), new Color(180, 165, 130)), + new Palette(new Color(45, 30, 65), new Color(75, 50, 100), new Color(60, 40, 82), + new Color(215, 195, 165), new Color(252, 250, 248), new Color(220, 210, 200), new Color(190, 170, 145)), + new Palette(new Color(55, 45, 35), new Color(90, 75, 60), new Color(72, 60, 47), + new Color(210, 185, 145), new Color(255, 252, 245), new Color(230, 220, 200), new Color(185, 165, 125)), + new Palette(new Color(25, 50, 60), new Color(45, 85, 100), new Color(35, 67, 80), + new Color(220, 200, 165), new Color(250, 250, 248), new Color(215, 210, 200), new Color(190, 175, 145)), + new Palette(new Color(40, 40, 45), new Color(65, 67, 73), new Color(52, 52, 58), + new Color(205, 190, 160), new Color(252, 252, 250), new Color(205, 203, 200), new Color(180, 170, 150)), + new Palette(new Color(65, 40, 30), new Color(105, 70, 50), new Color(85, 55, 40), + new Color(225, 200, 160), new Color(255, 250, 242), new Color(230, 220, 200), new Color(200, 180, 145)), + new Palette(new Color(30, 40, 75), new Color(50, 65, 115), new Color(40, 52, 95), + new Color(220, 200, 155), new Color(252, 250, 248), new Color(210, 205, 195), new Color(190, 170, 135)), + new Palette(new Color(50, 55, 40), new Color(80, 90, 65), new Color(65, 72, 52), + new Color(215, 205, 170), new Color(252, 250, 245), new Color(220, 215, 200), new Color(185, 180, 150)) + }; + return palettes[Math.abs(title.hashCode()) % palettes.length]; } - private static List wrapText(String text, FontMetrics fm) { + private static void renderBaseGradient(Graphics2D g, Palette p, int w, int h) { + float[] fractions = {0f, (float) PHI_SQ_INV, 0.5f, (float) PHI_INV, 1f}; + Color[] colors = {darken(p.primary, 0.2f), p.primary, p.tertiary, p.secondary, darken(p.secondary, 0.15f)}; + g.setPaint(new LinearGradientPaint(0, 0, w * (float) PHI_INV, h, fractions, colors)); + g.fillRect(0, 0, w, h); + } + + private void renderDepthGradient(Graphics2D g, Palette p, int w, int h) { + g.setPaint(new RadialGradientPaint(w * 0.5f, h * 0.35f, (float) (h * PHI_INV), + new float[]{0f, 0.5f, 1f}, + new Color[]{alpha(lighten(p.tertiary, 0.15f), 45), alpha(p.tertiary, 25), alpha(p.primary, 0)})); + g.fillRect(0, 0, w, h); + + g.setPaint(new RadialGradientPaint(w * 0.85f, h * 1.15f, (float) (w * PHI_INV), + new float[]{0f, 0.6f, 1f}, + new Color[]{alpha(darken(p.secondary, 0.25f), 55), alpha(darken(p.secondary, 0.15f), 30), alpha(p.secondary, 0)})); + g.fillRect(0, 0, w, h); + + g.setPaint(new RadialGradientPaint(w * 0.1f, h * 0.9f, (float) (w * PHI_SQ_INV), + new float[]{0f, 0.5f, 1f}, + new Color[]{alpha(darken(p.primary, 0.2f), 40), alpha(p.primary, 20), alpha(p.primary, 0)})); + g.fillRect(0, 0, w, h); + } + + private static void renderGlow(Graphics2D g, Palette p, int w, int h) { + int cy = (int) (h * PHI_SQ_INV); + float r = (float) (w * PHI_INV * 1.3); + Color glow = new Color( + Math.min(255, p.accent.getRed() + 55), + Math.min(255, p.accent.getGreen() + 45), + Math.min(255, p.accent.getBlue() + 35)); + + g.setPaint(new RadialGradientPaint(w / 2f, cy, r, + new float[]{0f, (float) PHI_SQ_INV, (float) PHI_INV, 1f}, + new Color[]{alpha(glow, 32), alpha(glow, 20), alpha(glow, 10), alpha(glow, 0)})); + g.fillRect(0, 0, w, h); + + g.setPaint(new RadialGradientPaint(w / 2f, (float) (h * (1 - PHI_SQ_INV * 0.45)), r * 0.65f, + new float[]{0f, 0.5f, 1f}, + new Color[]{alpha(Color.WHITE, 14), alpha(Color.WHITE, 7), alpha(Color.WHITE, 0)})); + g.fillRect(0, 0, w, h); + } + + private void renderBokeh(Graphics2D g, Palette p, int w, int h) { + Composite orig = g.getComposite(); + int seed = p.primary.getRGB(); + + for (int i = 0; i < 15; i++) { + int px = ((seed * (i + 1) * 17) % w + w) % w; + int py = ((seed * (i + 1) * 31) % h + h) % h; + int size = Math.max(1, ((25 + Math.abs((seed * (i + 1) * 7) % 60)) * SCALE)); + float opacity = 0.018f + Math.abs((seed * (i + 1) * 3) % 25) * 0.0012f; + + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity)); + Color bokehColor = (i % 3 == 0) ? lighten(p.accent, 0.25f) : (i % 3 == 1) ? Color.WHITE : lighten(p.ornament, 0.2f); + + g.setPaint(new RadialGradientPaint(px, py, size, + new float[]{0f, 0.6f, 1f}, + new Color[]{alpha(bokehColor, 90), alpha(bokehColor, 35), alpha(bokehColor, 0)})); + g.fillOval(px - size, py - size, size * 2, size * 2); + } + + g.setComposite(orig); + } + + private static void renderTexture(Graphics2D g, int w, int h) { + Composite orig = g.getComposite(); + g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.018f)); + + for (int y = 0; y < h; y += 2) { + for (int x = 0; x < w; x += 2) { + int n = (x * 17 + y * 31) % 29; + if (n < 10) { + g.setColor(n < 5 ? Color.WHITE : Color.BLACK); + g.fillRect(x, y, 1, 1); + } + } + } + + g.setComposite(orig); + } + + private void renderFrame(Graphics2D g, Palette p, int w, int h) { + int outer = (int) (w * PHI_SQ_INV * 0.12); + int inner = (int) (outer * PHI); + + g.setColor(alpha(p.ornament, 28)); + g.setStroke(new BasicStroke(10f)); + g.drawRect(outer - 4, outer - 4, w - (outer - 4) * 2, h - (outer - 4) * 2); + + g.setColor(alpha(p.ornament, 95)); + g.setStroke(new BasicStroke(2.5f)); + g.drawRect(outer, outer, w - outer * 2, h - outer * 2); + + g.setColor(alpha(p.ornament, 55)); + g.setStroke(new BasicStroke(1f)); + g.drawRect(inner, inner, w - inner * 2, h - inner * 2); + + renderCorners(g, p, w, h, outer); + renderAccents(g, p, w, h, outer); + } + + private static void renderCorners(Graphics2D g, Palette p, int w, int h, int m) { + g.setColor(alpha(p.ornament, 105)); + g.setStroke(new BasicStroke(2.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); + int size = (int) (m * PHI); + + int[][] corners = {{m, m, 0}, {w - m, m, 90}, {w - m, h - m, 180}, {m, h - m, 270}}; + for (int[] c : corners) renderCorner(g, c[0], c[1], size, c[2]); + } + + private static void renderCorner(Graphics2D g, int x, int y, int size, int angle) { + AffineTransform saved = g.getTransform(); + g.translate(x, y); + g.rotate(Math.toRadians(angle)); + + Path2D path = new Path2D.Float(); + path.moveTo(0, size); + path.lineTo(0, size * PHI_SQ_INV); + path.quadTo(0, 0, size * PHI_SQ_INV, 0); + path.lineTo(size, 0); + g.draw(path); + + Path2D inner = new Path2D.Float(); + inner.moveTo(size * 0.15, size * PHI_INV); + inner.quadTo(size * 0.15, size * 0.15, size * PHI_INV, size * 0.15); + g.draw(inner); + + g.fillOval(-5, -5, 10, 10); + g.fillOval((int) (size * 0.92), -4, 8, 8); + g.fillOval(-4, (int) (size * 0.92), 8, 8); + + g.setTransform(saved); + } + + private static void renderAccents(Graphics2D g, Palette p, int w, int h, int m) { + g.setColor(alpha(p.ornament, 65)); + g.setStroke(new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); + int len = (int) (m * PHI); + + g.drawLine(w / 2 - len, m, w / 2 + len, m); + g.fillOval(w / 2 - 5, m - 5, 10, 10); + + g.drawLine(w / 2 - len, h - m, w / 2 + len, h - m); + g.fillOval(w / 2 - 5, h - m - 5, 10, 10); + + g.drawLine(m, h / 2 - len, m, h / 2 + len); + g.fillOval(m - 5, h / 2 - 5, 10, 10); + + g.drawLine(w - m, h / 2 - len, w - m, h / 2 + len); + g.fillOval(w - m - 5, h / 2 - 5, 10, 10); + } + + private int renderTitle(Graphics2D g, String title, Palette p, int w, int h, int margin) { + int maxW = w - margin * 2; + int bottomBound = (int) (h * PHI_INV); + + String text = title.toUpperCase(); + Font font = resolveFont(g, text, maxW, titleSize(title.length()), MAX_TITLE_LINES, true); + g.setFont(font); + FontMetrics fm = g.getFontMetrics(); + + List lines = wrapText(text, fm, maxW, MAX_TITLE_LINES); + int lineH = (int) (fm.getHeight() * 1.12); + int totalH = lines.size() * lineH; + + int availableH = bottomBound - margin - totalH; + int startY = margin + (int) (availableH * PHI_SQ_INV) + fm.getAscent(); + startY = Math.max(startY, margin + fm.getAscent()); + + float tracking = 0.05f; + int lastY = startY; + + for (int i = 0; i < lines.size(); i++) { + String line = lines.get(i); + int lw = trackedWidth(fm, line, tracking); + int x = (w - lw) / 2; + int y = startY + i * lineH; + if (y + fm.getDescent() > bottomBound) break; + renderText(g, line, x, y, tracking, p.textMain, true); + lastY = y; + } + + return lastY + fm.getDescent() + lineH / 2; + } + + private static void renderDivider(Graphics2D g, Palette p, int w, int titleEnd, int h) { + int minY = titleEnd + (int) (h * 0.02); + int maxY = (int) (h * (1 - PHI_SQ_INV * 0.7)); + int cy = minY + (int) ((maxY - minY) * PHI_SQ_INV); + int cx = w / 2; + int lineLen = (int) (w * PHI_SQ_INV * 0.38); + + for (int dir : new int[]{-1, 1}) { + int sx = cx + dir * 50; + int ex = cx + dir * (50 + lineLen); + g.setPaint(new GradientPaint(sx, cy, alpha(p.ornament, 115), ex, cy, alpha(p.ornament, 25))); + g.setStroke(new BasicStroke(2.5f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); + g.drawLine(sx, cy, ex, cy); + } + + g.setColor(alpha(p.ornament, 130)); + g.setStroke(new BasicStroke(2f)); + + int ds = 14; + Path2D diamond = new Path2D.Float(); + diamond.moveTo(cx, cy - ds); + diamond.lineTo(cx + ds, cy); + diamond.lineTo(cx, cy + ds); + diamond.lineTo(cx - ds, cy); + diamond.closePath(); + g.draw(diamond); + + int is = 6; + Path2D inner = new Path2D.Float(); + inner.moveTo(cx, cy - is); + inner.lineTo(cx + is, cy); + inner.lineTo(cx, cy + is); + inner.lineTo(cx - is, cy); + inner.closePath(); + g.fill(inner); + + g.fillOval(cx - 50 - 5, cy - 5, 10, 10); + g.fillOval(cx + 50 - 5, cy - 5, 10, 10); + g.fillOval(cx - 32 - 4, cy - 4, 8, 8); + g.fillOval(cx + 32 - 4, cy - 4, 8, 8); + } + + private void renderAuthor(Graphics2D g, String author, Palette p, int w, int h, int margin) { + int maxW = w - margin * 2; + int bottomBound = h - margin; + + String[] authors = author.split(","); + StringBuilder formattedAuthors = new StringBuilder(); + for (int i = 0; i < authors.length; i++) { + if (i > 0) formattedAuthors.append("\n").append(authors[i].trim()); + else formattedAuthors.append(authors[i].trim()); + } + + Font authorFont = resolveFont(g, formattedAuthors.toString(), maxW, authorSize(formattedAuthors.length()), MAX_AUTHOR_LINES, false); + g.setFont(authorFont); + FontMetrics authorFm = g.getFontMetrics(); + + String[] authorLinesArray = formattedAuthors.toString().split("\n"); List lines = new ArrayList<>(); - String[] words = WHITESPACE_PATTERN.split(text); - StringBuilder currentLine = new StringBuilder(); + for (String line : authorLinesArray) { + lines.add(line.trim()); + } - for (String word : words) { - if (currentLine.isEmpty()) { - currentLine.append(word); + int authorLineH = (int) (authorFm.getHeight() * 1.18); + int authorTotalH = lines.size() * authorLineH; + + // Remove the "by" prefix for multiple authors + boolean showByPrefix = lines.size() == 1 && author.length() < 45 && !author.contains(","); + + Font byFont = authorFont.deriveFont(authorFont.getSize() * 0.58f); + FontMetrics byFm = g.getFontMetrics(byFont); + String byText = "— by —"; + int byHeight = showByPrefix ? byFm.getHeight() : 0; + int bySpacing = showByPrefix ? (int) (authorLineH * PHI_SQ_INV * 0.8) : 0; + + int totalBlockH = byHeight + bySpacing + authorTotalH; + + int blockBottom = (int) (h * (1 - PHI_SQ_INV * 0.32)); + blockBottom = Math.min(blockBottom, bottomBound); + int blockTop = blockBottom - totalBlockH; + + int minTop = (int) (h * PHI_INV) + margin; + if (blockTop < minTop) blockTop = minTop; + + int currentY = blockTop; + + if (showByPrefix) { + g.setFont(byFont); + int byW = byFm.stringWidth(byText); + int byX = (w - byW) / 2; + int byY = currentY + byFm.getAscent(); + + g.setColor(new Color(0, 0, 0, 35)); + g.drawString(byText, byX + 3, byY + 3); + + g.setColor(alpha(p.ornament, 155)); + g.drawString(byText, byX, byY); + + currentY = byY + byFm.getDescent() + bySpacing; + } + + g.setFont(authorFont); + float tracking = 0.08f; + + for (int i = 0; i < lines.size(); i++) { + String line = lines.get(i); + if (!line.isEmpty()) { // Only render non-empty lines + int lw = trackedWidth(authorFm, line, tracking); + int x = (w - lw) / 2; + int y = currentY + authorFm.getAscent() + i * authorLineH; + if (y + authorFm.getDescent() > bottomBound) break; + renderText(g, line, x, y, tracking, p.textSub, false); + } + } + } + + private int renderSubtitle(Graphics2D g, String subtitle, Palette p, int w, int h, int margin, int titleEnd) { + int maxW = w - margin * 2; + int bottomBound = h - margin; + + Font subtitleFont = resolveFont(g, subtitle, maxW, subtitleSize(subtitle.length()), 2, false); + g.setFont(subtitleFont); + FontMetrics subtitleFm = g.getFontMetrics(); + + List lines = wrapText(subtitle, subtitleFm, maxW, 2); + int subtitleLineH = (int) (subtitleFm.getHeight() * 1.12); + + // Position subtitle below the title with some spacing + int spacing = (int) (subtitleLineH * 0.5); + int startY = titleEnd + spacing + subtitleFm.getAscent(); + + g.setFont(subtitleFont); + float tracking = 0.06f; + + int lastY = startY; + for (int i = 0; i < lines.size(); i++) { + String line = lines.get(i); + int lw = trackedWidth(subtitleFm, line, tracking); + int x = (w - lw) / 2; + int y = startY + i * subtitleLineH; + if (y + subtitleFm.getDescent() > bottomBound) break; + renderText(g, line, x, y, tracking, p.textSub, false); + lastY = y; + } + + return lastY + subtitleFm.getDescent(); + } + + private int subtitleSize(int len) { + if (len < 12) return 130 * SCALE; + if (len < 22) return 110 * SCALE; + if (len < 35) return 90 * SCALE; + return 75 * SCALE; + } + + private void renderText(Graphics2D g, String text, int x, int y, float tracking, Color color, boolean isTitle) { + FontMetrics fm = g.getFontMetrics(); + int tp = (int) (fm.getHeight() * tracking); + + int[][] shadows = isTitle + ? new int[][]{{8, 8, 14}, {5, 5, 28}, {2, 2, 45}} + : new int[][]{{5, 5, 18}, {2, 2, 35}}; + + for (int[] s : shadows) { + g.setColor(new Color(0, 0, 0, s[2])); + drawTracked(g, text, x + s[0], y + s[1], tp); + } + + g.setColor(color); + drawTracked(g, text, x, y, tp); + + if (isTitle) { + g.setColor(alpha(Color.WHITE, 22)); + drawTracked(g, text, x, y - 1, tp); + } + } + + private void drawTracked(Graphics2D g, String text, int x, int y, int tracking) { + FontMetrics fm = g.getFontMetrics(); + int cx = x; + for (char c : text.toCharArray()) { + g.drawString(String.valueOf(c), cx, y); + cx += fm.charWidth(c) + tracking; + } + } + + private int trackedWidth(FontMetrics fm, String text, float tracking) { + int tp = (int) (fm.getHeight() * tracking); + int w = 0; + for (char c : text.toCharArray()) w += fm.charWidth(c) + tp; + return Math.max(0, w - tp); + } + + private static void renderVignette(Graphics2D g, int w, int h) { + float r = (float) (Math.sqrt(w * w + h * h) / 2 * 1.12); + g.setPaint(new RadialGradientPaint(w / 2f, h / 2f, r, + new float[]{0f, (float) PHI_INV, (float) (PHI_INV + PHI_SQ_INV * 0.25), 0.9f, 1f}, + new Color[]{alpha(Color.BLACK, 0), alpha(Color.BLACK, 0), alpha(Color.BLACK, 15), + alpha(Color.BLACK, 50), alpha(Color.BLACK, 85)})); + g.fillRect(0, 0, w, h); + + g.setPaint(new GradientPaint(0, 0, alpha(Color.WHITE, 14), 0, (int) (h * PHI_SQ_INV), alpha(Color.WHITE, 0))); + g.fillRect(0, 0, w, (int) (h * PHI_SQ_INV)); + } + + private static void renderEdges(Graphics2D g, int w, int h) { + g.setColor(alpha(Color.BLACK, 50)); + g.setStroke(new BasicStroke(3f)); + g.drawRect(0, 0, w - 1, h - 1); + + g.setColor(alpha(Color.WHITE, 10)); + g.drawRect(3, 3, w - 7, h - 7); + } + + private static String sanitize(String input, int max, String fallback) { + if (input == null || input.isBlank()) return fallback; + String s = input.trim(); + return s.length() > max ? s.substring(0, max) : s; + } + + private void configureGraphics(Graphics2D g) { + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB); + g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); + g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); + g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); + } + + private static Color alpha(Color c, int a) { + return new Color(c.getRed(), c.getGreen(), c.getBlue(), Math.min(255, Math.max(0, a))); + } + + private static Color darken(Color c, float f) { + return new Color(Math.max(0, (int) (c.getRed() * (1 - f))), + Math.max(0, (int) (c.getGreen() * (1 - f))), + Math.max(0, (int) (c.getBlue() * (1 - f)))); + } + + private Color lighten(Color c, float f) { + return new Color(Math.min(255, (int) (c.getRed() + (255 - c.getRed()) * f)), + Math.min(255, (int) (c.getGreen() + (255 - c.getGreen()) * f)), + Math.min(255, (int) (c.getBlue() + (255 - c.getBlue()) * f))); + } + + private Font resolveFont(Graphics2D g, String text, int maxW, int startSize, int maxLines, boolean isTitle) { + String[] serif = {"Palatino Linotype", "Garamond", "Georgia", "Book Antiqua"}; + String[] sans = {"Optima", "Gill Sans", "Helvetica Neue", "Calibri"}; + String[] preferred = isTitle ? serif : sans; + String fallback = isTitle ? Font.SERIF : Font.SANS_SERIF; + int style = isTitle ? Font.BOLD : Font.PLAIN; + + String selected = fallback; + for (String name : preferred) { + Font test = new Font(name, style, startSize); + if (test.getFamily().equalsIgnoreCase(name)) { + selected = name; + break; + } + } + + float tracking = isTitle ? 0.05f : 0.08f; + + for (int size = startSize; size >= MIN_FONT; size -= 2) { + Font font = new Font(selected, style, size); + g.setFont(font); + FontMetrics fm = g.getFontMetrics(); + List lines = wrapText(text, fm, maxW, maxLines); + if (lines.stream().allMatch(l -> trackedWidth(fm, l, tracking) <= maxW)) return font; + } + + return new Font(selected, style, MIN_FONT); + } + + private List wrapText(String text, FontMetrics fm, int maxW, int maxLines) { + List lines = new ArrayList<>(); + StringBuilder cur = new StringBuilder(); + + for (String word : WS.split(text.trim())) { + if (fm.stringWidth(word) > maxW) { + if (!cur.isEmpty()) { + lines.add(cur.toString().trim()); + cur = new StringBuilder(); + } + lines.addAll(breakWord(word, fm, maxW)); + continue; + } + + if (cur.isEmpty()) { + cur.append(word); + } else if (fm.stringWidth(cur + " " + word) <= maxW) { + cur.append(" ").append(word); } else { - int currentWidth = fm.stringWidth(currentLine.toString()); - int spaceWidth = fm.stringWidth(" "); - int wordWidth = fm.stringWidth(word); - if (currentWidth + spaceWidth + wordWidth <= 210) { - currentLine.append(" ").append(word); - } else { - lines.add(currentLine.toString().trim()); - currentLine = new StringBuilder(word); - } + lines.add(cur.toString().trim()); + cur = new StringBuilder(word); } } - if (!currentLine.isEmpty()) { - lines.add(currentLine.toString().trim()); - } - - if (lines.size() > MAX_LINES) { - List truncated = lines.subList(0, MAX_LINES); - String lastLine = truncated.get(MAX_LINES - 1); - - if (fm.stringWidth(lastLine + "...") > 210) { - while (lastLine.length() > 3 && fm.stringWidth(lastLine + "...") > 210) { - lastLine = lastLine.substring(0, lastLine.length() - 1); - } - } - truncated.set(MAX_LINES - 1, lastLine.trim() + "..."); - return truncated; + + if (!cur.isEmpty()) lines.add(cur.toString().trim()); + + if (lines.size() > maxLines) { + lines = new ArrayList<>(lines.subList(0, maxLines)); + String last = lines.get(maxLines - 1); + while (!last.isEmpty() && fm.stringWidth(last + "…") > maxW) + last = last.substring(0, last.length() - 1).trim(); + lines.set(maxLines - 1, last + "…"); } + return lines; } - private Color[] getColorScheme(String title) { - int hash = Math.abs((title != null ? title : "").hashCode()); - Color[][] schemes = { - {new Color(85, 119, 102), new Color(102, 153, 136)}, // Green (Original) - {new Color(102, 119, 153), new Color(136, 153, 187)}, // Blue - {new Color(153, 102, 119), new Color(187, 136, 153)}, // Purple - {new Color(153, 153, 102), new Color(187, 187, 136)}, // Olive - {new Color(102, 153, 153), new Color(136, 187, 187)}, // Teal - {new Color(119, 102, 153), new Color(153, 136, 187)} // Indigo - }; - return schemes[hash % schemes.length]; + private List breakWord(String word, FontMetrics fm, int maxW) { + List parts = new ArrayList<>(); + StringBuilder cur = new StringBuilder(); + + for (char c : word.toCharArray()) { + if (fm.stringWidth(cur.toString() + c) > maxW && !cur.isEmpty()) { + parts.add(cur.toString()); + cur = new StringBuilder(); + } + cur.append(c); + } + if (!cur.isEmpty()) parts.add(cur.toString()); + + return parts; } -} \ No newline at end of file + + private int titleSize(int len) { + if (len < 8) return 150 * SCALE; + if (len < 15) return 130 * SCALE; + if (len < 25) return 110 * SCALE; + if (len < 40) return 92 * SCALE; + if (len < 60) return 78 * SCALE; + if (len < 85) return 66 * SCALE; + return 56 * SCALE; + } + + private int authorSize(int len) { + if (len < 12) return 78 * SCALE; + if (len < 22) return 68 * SCALE; + if (len < 35) return 58 * SCALE; + return 50 * SCALE; + } + + private BufferedImage downscale(BufferedImage src) { + BufferedImage dst = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); + Graphics2D g = dst.createGraphics(); + try { + g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); + g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); + g.drawImage(src, 0, 0, WIDTH, HEIGHT, null); + return dst; + } finally { + g.dispose(); + } + } + + private byte[] encodeJpeg(BufferedImage img) { + ImageWriter writer = null; + ImageOutputStream ios = null; + + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + writer = ImageIO.getImageWritersByFormatName("jpg").next(); + ImageWriteParam param = writer.getDefaultWriteParam(); + param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + param.setCompressionQuality(0.95f); + + ios = ImageIO.createImageOutputStream(baos); + writer.setOutput(ios); + writer.write(null, new IIOImage(img, null, null), param); + return baos.toByteArray(); + } catch (IOException e) { + throw new RuntimeException("JPEG encoding failed", e); + } finally { + if (writer != null) writer.dispose(); + if (ios != null) try { ios.close(); } catch (IOException ignored) {} + } + } + + private void cleanup(Graphics2D g, BufferedImage... images) { + if (g != null) try { g.dispose(); } catch (Exception ignored) {} + for (BufferedImage img : images) + if (img != null) try { img.flush(); } catch (Exception ignored) {} + } +} From 9861e23333d80c5ef9b44008ad20b2594802545c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= <127139797+balazs-szucs@users.noreply.github.com> Date: Mon, 5 Jan 2026 22:28:24 +0100 Subject: [PATCH 09/40] feat(magic-shelf): add genre filter support and improve category labeling in rule fields (#2075) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Balázs Szücs --- .../booklore/model/dto/RuleField.java | 4 ++- .../service/BookRuleEvaluatorService.java | 4 ++- .../component/magic-shelf-component.html | 4 +++ .../component/magic-shelf-component.ts | 33 ++++++++++++++++--- 4 files changed, 39 insertions(+), 6 deletions(-) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/RuleField.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/RuleField.java index dfa3f033a..6b7304db2 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/RuleField.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/RuleField.java @@ -56,6 +56,8 @@ public enum RuleField { @JsonProperty("moods") MOODS, @JsonProperty("tags") - TAGS + TAGS, + @JsonProperty("genre") + GENRE } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookRuleEvaluatorService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookRuleEvaluatorService.java index a402387d0..e1701d998 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookRuleEvaluatorService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookRuleEvaluatorService.java @@ -338,7 +338,8 @@ public class BookRuleEvaluatorService { private boolean isArrayField(RuleField field) { return field == RuleField.AUTHORS || field == RuleField.CATEGORIES || - field == RuleField.MOODS || field == RuleField.TAGS; + field == RuleField.MOODS || field == RuleField.TAGS || + field == RuleField.GENRE; } private Join createArrayFieldJoin(RuleField field, Root root) { @@ -356,6 +357,7 @@ public class BookRuleEvaluatorService { case CATEGORIES -> metadataJoin.join("categories", JoinType.INNER); case MOODS -> metadataJoin.join("moods", JoinType.INNER); case TAGS -> metadataJoin.join("tags", JoinType.INNER); + case GENRE -> metadataJoin.join("categories", JoinType.INNER); default -> throw new IllegalArgumentException("Not an array field: " + field); }; } diff --git a/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.html b/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.html index b6b882b5a..30c5d8fc1 100644 --- a/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.html +++ b/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.html @@ -138,6 +138,8 @@ } @else if (ruleCtrl.get('field')?.value === 'library') { + } @else if (ruleCtrl.get('field')?.value === 'categories') { + } @else {
@@ -149,6 +151,8 @@ } @else if (ruleCtrl.get('field')?.value === 'library') { + } @else if (ruleCtrl.get('field')?.value === 'categories') { + } @else { } diff --git a/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.ts b/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.ts index 9dc36e43e..975110edc 100644 --- a/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.ts +++ b/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.ts @@ -19,6 +19,7 @@ import {IconPickerService, IconSelection} from '../../../shared/service/icon-pic import {CheckboxChangeEvent, CheckboxModule} from "primeng/checkbox"; import {UserService} from "../../settings/user-management/user.service"; import {IconDisplayComponent} from '../../../shared/components/icon-display/icon-display.component'; +import {BookService} from '../../book/service/book.service'; export type RuleOperator = | 'equals' @@ -172,10 +173,14 @@ export class MagicShelfComponent implements OnInit { {label: 'OR', value: 'or'}, ]; - fieldOptions = Object.entries(FIELD_CONFIGS).map(([key, config]) => ({ - label: config.label, - value: key as RuleField - })); + fieldOptions = Object.entries(FIELD_CONFIGS).map(([key, config]) => { + // Use "Genre" instead of "Categories" for user-facing label + const label = key === 'categories' ? 'Genre' : config.label; + return { + label: label, + value: key as RuleField + }; + }); fileType: { label: string; value: string }[] = [ {label: 'PDF', value: 'pdf'}, @@ -192,6 +197,7 @@ export class MagicShelfComponent implements OnInit { libraries: Library[] = []; libraryOptions: { label: string; value: number }[] = []; + categoryOptions: { label: string; value: string }[] = []; form = new FormGroup({ name: new FormControl(null), @@ -205,6 +211,7 @@ export class MagicShelfComponent implements OnInit { editMode!: boolean; libraryService = inject(LibraryService); + bookService = inject(BookService); magicShelfService = inject(MagicShelfService); ref = inject(DynamicDialogRef); messageService = inject(MessageService); @@ -223,6 +230,24 @@ export class MagicShelfComponent implements OnInit { const id = this.config?.data?.id; this.editMode = !!this.config?.data?.editMode; + // Load available categories from book metadata + this.bookService.bookState$.subscribe(state => { + if (state.loaded && state.books) { + // Extract unique categories from all books + const categoriesSet = new Set(); + state.books.forEach(book => { + if (book.metadata?.categories) { + book.metadata.categories.forEach(cat => categoriesSet.add(cat)); + } + }); + + this.categoryOptions = Array.from(categoriesSet).map(cat => ({ + label: cat, + value: cat + })).sort((a, b) => a.label.localeCompare(b.label)); + } + }); + if (id) { this.shelfId = id; this.magicShelfService.getShelf(id).subscribe((data) => { From 926b87872ec7e78d6fc407bc55532cd278575a27 Mon Sep 17 00:00:00 2001 From: Darkraise Date: Tue, 6 Jan 2026 04:45:29 +0700 Subject: [PATCH 10/40] feat: Add custom font support for EPUB reader (#2120) * feat: Add custom font support for EPUB reader This commit introduces the ability to manage and use custom fonts in the EPUB reader. Key changes include: **Backend:** - Added `CustomFontService` for handling custom font operations. - Introduced `CustomFontController` for API endpoints. - Created `CustomFontEntity` and `CustomFontRepository` for database interactions. - Added `CustomFontMapper` and `CustomFontDto` for data transformation. - Updated `SecurityConfig` to include JWT filter for custom fonts. - Enhanced `GlobalExceptionHandler` to handle custom font-related exceptions. - Added database migrations: - `V83__Create_Custom_Font_Table.sql` for creating the custom font table. - `V84__Add_Custom_Font_To_Epub_Preferences.sql` for integrating custom fonts with EPUB preferences. **Frontend:** - Added `CustomFontsComponent` and `FontUploadDialogComponent` for managing custom fonts in the settings UI. - Updated `EpubReaderPreferencesComponent` to include custom font options. - Introduced `CustomFontService` and `CustomFontModel` for frontend logic and data handling. - Enhanced `SettingsComponent` to integrate custom font management. **Other Changes:** - Updated `EpubViewerPreferences` and `EpubViewerPreferencesEntity` to support custom fonts. - Modified existing components and services to accommodate the new feature. This feature enhances the user experience by allowing personalized font choices for EPUB reading. * fix: custom font does not apply after page layout changed * fix: duplicate API call when change EPUB global settings * fix: some code review items, extract shared filter logic and improve UX - Extract AbstractQueryParameterJwtFilter base class to reduce code duplication between CoverJwtFilter and CustomFontJwtFilter - Remove cssIdentifier and fontUrl fields from CustomFont model (no longer needed) - Add font name sanitization to prevent XSS and ensure data integrity - Improve error handling in CustomFontService with proper APIException usage - Replace RuntimeException handler with specific IllegalStateException and UnsupportedOperationException handlers in GlobalExceptionHandler - Add skeleton loading states for font previews and font dropdowns - Improve font loading state management in epub-reader component - Create shared custom-font.util.ts for dropdown population logic - Use reactive font$ subscription for real-time font updates in preferences - Make DB migrations idempotent with IF NOT EXISTS clauses - Optimize font file validation to read only header bytes instead of entire file * chore: re-version migration scripts * Fix: Kobo sync missing book covers (v1.16.4) (#2147) Co-authored-by: acx10 * Fix: correctly update book cover hash on metadata refresh (#2149) Co-authored-by: acx10 * Introduce Vitest as the frontend Angular testing framework for Booklore (#2150) Co-authored-by: acx10 * Add Vitest frontend tests to CI with JUnit reporting and coverage (#2151) Co-authored-by: acx10 * Update PR template to capture frontend test details * Add instructions for running Angular frontend tests --------- Co-authored-by: ACX <8075870+acx10@users.noreply.github.com> Co-authored-by: acx10 --- .../config/security/SecurityConfig.java | 16 + .../AbstractQueryParameterJwtFilter.java | 93 ++++ .../security/filter/CoverJwtFilter.java | 83 +--- .../security/filter/CustomFontJwtFilter.java | 29 ++ .../controller/CustomFontController.java | 82 ++++ .../exception/GlobalExceptionHandler.java | 21 + .../booklore/mapper/CustomFontMapper.java | 11 + .../booklore/model/dto/CustomFontDto.java | 22 + .../model/dto/EpubViewerPreferences.java | 1 + .../model/entity/CustomFontEntity.java | 44 ++ .../entity/EpubViewerPreferencesEntity.java | 3 + .../booklore/model/enums/FontFormat.java | 54 +++ .../repository/CustomFontRepository.java | 19 + .../service/customfont/CustomFontService.java | 331 +++++++++++++ .../V85__Create_Custom_Font_Table.sql | 12 + ...6__Add_Custom_Font_To_Epub_Preferences.sql | 2 + .../customfont/CustomFontServiceTest.java | 452 ++++++++++++++++++ .../src/app/features/book/model/book.model.ts | 1 + .../component/epub-reader.component.html | 3 +- .../component/epub-reader.component.ts | 152 +++++- .../custom-fonts/custom-fonts.component.html | 126 +++++ .../custom-fonts/custom-fonts.component.scss | 384 +++++++++++++++ .../custom-fonts/custom-fonts.component.ts | 133 ++++++ .../font-upload-dialog.component.html | 131 +++++ .../font-upload-dialog.component.scss | 443 +++++++++++++++++ .../font-upload-dialog.component.ts | 244 ++++++++++ .../epub-reader-preferences-component.html | 11 +- .../epub-reader-preferences-component.scss | 22 + .../epub-reader-preferences-component.ts | 132 ++++- .../features/settings/settings.component.html | 6 + .../features/settings/settings.component.ts | 3 + .../settings/user-management/user.service.ts | 1 + .../src/app/shared/model/custom-font.model.ts | 23 + .../app/shared/service/custom-font.service.ts | 122 +++++ .../src/app/shared/util/custom-font.util.ts | 74 +++ 35 files changed, 3192 insertions(+), 94 deletions(-) create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/AbstractQueryParameterJwtFilter.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CustomFontJwtFilter.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/controller/CustomFontController.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/mapper/CustomFontMapper.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CustomFontDto.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/entity/CustomFontEntity.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/enums/FontFormat.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/repository/CustomFontRepository.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/customfont/CustomFontService.java create mode 100644 booklore-api/src/main/resources/db/migration/V85__Create_Custom_Font_Table.sql create mode 100644 booklore-api/src/main/resources/db/migration/V86__Add_Custom_Font_To_Epub_Preferences.sql create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/customfont/CustomFontServiceTest.java create mode 100644 booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.html create mode 100644 booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.scss create mode 100644 booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.ts create mode 100644 booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.html create mode 100644 booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.scss create mode 100644 booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.ts create mode 100644 booklore-ui/src/app/shared/model/custom-font.model.ts create mode 100644 booklore-ui/src/app/shared/service/custom-font.service.ts create mode 100644 booklore-ui/src/app/shared/util/custom-font.util.ts 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 5d4185742..6789c5db5 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 @@ -2,6 +2,7 @@ package com.adityachandel.booklore.config.security; import com.adityachandel.booklore.config.AppProperties; import com.adityachandel.booklore.config.security.filter.CoverJwtFilter; +import com.adityachandel.booklore.config.security.filter.CustomFontJwtFilter; import com.adityachandel.booklore.config.security.filter.DualJwtAuthenticationFilter; import com.adityachandel.booklore.config.security.filter.KoboAuthFilter; import com.adityachandel.booklore.config.security.filter.KoreaderAuthFilter; @@ -133,6 +134,21 @@ public class SecurityConfig { @Bean @Order(5) + public SecurityFilterChain customFontSecurityChain(HttpSecurity http, CustomFontJwtFilter customFontJwtFilter) throws Exception { + http + .securityMatcher("/api/v1/custom-fonts/*/file") + .cors(cors -> cors.configurationSource(corsConfigurationSource())) + .csrf(AbstractHttpConfigurer::disable) + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + .authorizeHttpRequests(auth -> auth + .anyRequest().permitAll() + ) + .addFilterBefore(customFontJwtFilter, UsernamePasswordAuthenticationFilter.class); + return http.build(); + } + + @Bean + @Order(6) 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/AbstractQueryParameterJwtFilter.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/AbstractQueryParameterJwtFilter.java new file mode 100644 index 000000000..00328ca69 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/AbstractQueryParameterJwtFilter.java @@ -0,0 +1,93 @@ +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.web.filter.OncePerRequestFilter; + +import java.io.IOException; +import java.time.Instant; + +@AllArgsConstructor +public abstract class AbstractQueryParameterJwtFilter extends OncePerRequestFilter { + + protected final JwtUtils jwtUtils; + protected final UserRepository userRepository; + protected final BookLoreUserTransformer bookLoreUserTransformer; + protected final AppSettingService appSettingService; + protected final DynamicOidcJwtProcessor dynamicOidcJwtProcessor; + + @Override + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) + throws ServletException, IOException { + // Extract token from query parameter (not from Authorization header) + String 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); + } + + protected 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); + } + + protected 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/config/security/filter/CoverJwtFilter.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CoverJwtFilter.java index 4ad791311..0cb78fb9a 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CoverJwtFilter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CoverJwtFilter.java @@ -2,92 +2,27 @@ 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; - -@AllArgsConstructor @Component -public class CoverJwtFilter extends OncePerRequestFilter { +public class CoverJwtFilter extends AbstractQueryParameterJwtFilter { - private final JwtUtils jwtUtils; - private final UserRepository userRepository; - private final BookLoreUserTransformer bookLoreUserTransformer; - private final AppSettingService appSettingService; - private final DynamicOidcJwtProcessor dynamicOidcJwtProcessor; + public CoverJwtFilter( + JwtUtils jwtUtils, + UserRepository userRepository, + BookLoreUserTransformer bookLoreUserTransformer, + AppSettingService appSettingService, + DynamicOidcJwtProcessor dynamicOidcJwtProcessor) { + super(jwtUtils, userRepository, bookLoreUserTransformer, appSettingService, dynamicOidcJwtProcessor); + } @Override protected boolean shouldNotFilter(HttpServletRequest request) { String path = request.getRequestURI(); return !path.startsWith("/api/v1/media/"); } - - @Override - protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { - String 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 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); - } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CustomFontJwtFilter.java b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CustomFontJwtFilter.java new file mode 100644 index 000000000..b72bc15d1 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/config/security/filter/CustomFontJwtFilter.java @@ -0,0 +1,29 @@ +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.mapper.custom.BookLoreUserTransformer; +import com.adityachandel.booklore.repository.UserRepository; +import com.adityachandel.booklore.service.appsettings.AppSettingService; +import jakarta.servlet.http.HttpServletRequest; +import org.springframework.stereotype.Component; + +@Component +public class CustomFontJwtFilter extends AbstractQueryParameterJwtFilter { + + public CustomFontJwtFilter( + JwtUtils jwtUtils, + UserRepository userRepository, + BookLoreUserTransformer bookLoreUserTransformer, + AppSettingService appSettingService, + DynamicOidcJwtProcessor dynamicOidcJwtProcessor) { + super(jwtUtils, userRepository, bookLoreUserTransformer, appSettingService, dynamicOidcJwtProcessor); + } + + @Override + protected boolean shouldNotFilter(HttpServletRequest request) { + String path = request.getRequestURI(); + // Only filter requests to custom font file endpoints (e.g., /api/v1/custom-fonts/123/file) + return !(path.startsWith("/api/v1/custom-fonts/") && path.endsWith("/file")); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/CustomFontController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/CustomFontController.java new file mode 100644 index 000000000..858c20bfb --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/CustomFontController.java @@ -0,0 +1,82 @@ +package com.adityachandel.booklore.controller; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.model.dto.BookLoreUser; +import com.adityachandel.booklore.model.dto.CustomFontDto; +import com.adityachandel.booklore.service.customfont.CustomFontService; +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 lombok.RequiredArgsConstructor; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; + +@Tag(name = "Custom Fonts", description = "Endpoints for managing custom fonts for EPUB reader") +@RestController +@RequestMapping("/api/v1/custom-fonts") +@RequiredArgsConstructor +public class CustomFontController { + + private final CustomFontService customFontService; + private final AuthenticationService authenticationService; + + @Operation(summary = "Upload a custom font", description = "Upload a custom font file (.ttf, .otf, .woff, .woff2) for the authenticated user") + @ApiResponse(responseCode = "200", description = "Font uploaded successfully") + @ApiResponse(responseCode = "400", description = "Invalid file or quota exceeded") + @PostMapping("/upload") + @PreAuthorize("isAuthenticated()") + public ResponseEntity uploadFont( + @Parameter(description = "Font file (.ttf, .otf, .woff, .woff2)") @RequestParam("file") MultipartFile file, + @Parameter(description = "Font display name") @RequestParam(value = "fontName", required = false) String fontName) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + CustomFontDto fontDto = customFontService.uploadFont(file, fontName, user.getId()); + return ResponseEntity.ok(fontDto); + } + + @Operation(summary = "Get all user's custom fonts", description = "Retrieve all custom fonts for the authenticated user") + @ApiResponse(responseCode = "200", description = "Fonts retrieved successfully") + @GetMapping + @PreAuthorize("isAuthenticated()") + public ResponseEntity> getUserFonts() { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + List fonts = customFontService.getUserFonts(user.getId()); + return ResponseEntity.ok(fonts); + } + + @Operation(summary = "Delete a custom font", description = "Delete a custom font file and database record") + @ApiResponse(responseCode = "200", description = "Font deleted successfully") + @ApiResponse(responseCode = "404", description = "Font not found or access denied") + @DeleteMapping("/{fontId}") + @PreAuthorize("isAuthenticated()") + public ResponseEntity deleteFont(@PathVariable Long fontId) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + customFontService.deleteFont(fontId, user.getId()); + return ResponseEntity.ok().build(); + } + + @Operation(summary = "Get font file", description = "Retrieve the font file for use in the browser") + @ApiResponse(responseCode = "200", description = "Font file retrieved successfully") + @ApiResponse(responseCode = "404", description = "Font not found or access denied") + @GetMapping("/{fontId}/file") + @PreAuthorize("isAuthenticated()") + public ResponseEntity getFontFile(@PathVariable Long fontId) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + Resource resource = customFontService.getFontFile(fontId, user.getId()); + + // Get font format to set correct content type + var format = customFontService.getFontFormat(fontId, user.getId()); + + return ResponseEntity.ok() + .contentType(MediaType.parseMediaType(format.getMimeType())) + .header(HttpHeaders.CONTENT_DISPOSITION, "inline") + .body(resource); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java b/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java index 31a361650..f026289a0 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/exception/GlobalExceptionHandler.java @@ -93,6 +93,27 @@ public class GlobalExceptionHandler { return new ResponseEntity<>(errorResponse, HttpStatus.OK); } + @ExceptionHandler(IllegalArgumentException.class) + public ResponseEntity handleIllegalArgumentException(IllegalArgumentException ex) { + log.warn("Illegal argument: {}", ex.getMessage()); + ErrorResponse errorResponse = new ErrorResponse(HttpStatus.BAD_REQUEST.value(), ex.getMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST); + } + + @ExceptionHandler(IllegalStateException.class) + public ResponseEntity handleIllegalStateException(IllegalStateException ex) { + log.error("Illegal state: {}", ex.getMessage(), ex); + ErrorResponse errorResponse = new ErrorResponse(HttpStatus.CONFLICT.value(), ex.getMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.CONFLICT); + } + + @ExceptionHandler(UnsupportedOperationException.class) + public ResponseEntity handleUnsupportedOperationException(UnsupportedOperationException ex) { + log.error("Unsupported operation: {}", ex.getMessage(), ex); + ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_IMPLEMENTED.value(), ex.getMessage()); + return new ResponseEntity<>(errorResponse, HttpStatus.NOT_IMPLEMENTED); + } + @ExceptionHandler(Exception.class) public ResponseEntity handleGenericException(Exception ex) { ErrorResponse errorResponse = new ErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), ex.getMessage()); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/mapper/CustomFontMapper.java b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/CustomFontMapper.java new file mode 100644 index 000000000..08da6c1fc --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/mapper/CustomFontMapper.java @@ -0,0 +1,11 @@ +package com.adityachandel.booklore.mapper; + +import com.adityachandel.booklore.model.dto.CustomFontDto; +import com.adityachandel.booklore.model.entity.CustomFontEntity; +import org.mapstruct.Mapper; + +@Mapper(componentModel = "spring") +public interface CustomFontMapper { + + CustomFontDto toDto(CustomFontEntity entity); +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CustomFontDto.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CustomFontDto.java new file mode 100644 index 000000000..7017b6548 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/CustomFontDto.java @@ -0,0 +1,22 @@ +package com.adityachandel.booklore.model.dto; + +import com.adityachandel.booklore.model.enums.FontFormat; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.time.LocalDateTime; + +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class CustomFontDto { + private Long id; + private String fontName; + private String originalFileName; + private FontFormat format; + private Long fileSize; + private LocalDateTime uploadedAt; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/EpubViewerPreferences.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/EpubViewerPreferences.java index 258f67bf1..3036a24d9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/EpubViewerPreferences.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/EpubViewerPreferences.java @@ -14,4 +14,5 @@ public class EpubViewerPreferences { private Integer fontSize; private Float letterSpacing; private Float lineHeight; + private Long customFontId; } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/CustomFontEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/CustomFontEntity.java new file mode 100644 index 000000000..cc9089af0 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/CustomFontEntity.java @@ -0,0 +1,44 @@ +package com.adityachandel.booklore.model.entity; + +import com.adityachandel.booklore.model.enums.FontFormat; +import jakarta.persistence.*; +import lombok.*; + +import java.time.LocalDateTime; + +@Entity +@Getter +@Setter +@Builder +@NoArgsConstructor +@AllArgsConstructor +@Table(name = "custom_font") +public class CustomFontEntity { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "user_id", nullable = false) + private BookLoreUserEntity user; + + @Column(name = "font_name", nullable = false) + private String fontName; + + @Column(name = "file_name", nullable = false, unique = true) + private String fileName; + + @Column(name = "original_file_name", nullable = false) + private String originalFileName; + + @Enumerated(EnumType.STRING) + @Column(name = "format", nullable = false) + private FontFormat format; + + @Column(name = "file_size", nullable = false) + private Long fileSize; + + @Column(name = "uploaded_at", nullable = false) + private LocalDateTime uploadedAt; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/EpubViewerPreferencesEntity.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/EpubViewerPreferencesEntity.java index 5e6fb116d..7de62e30c 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/EpubViewerPreferencesEntity.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/entity/EpubViewerPreferencesEntity.java @@ -44,4 +44,7 @@ public class EpubViewerPreferencesEntity { @Column(name = "spread") private String spread; + + @Column(name = "custom_font_id") + private Long customFontId; } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/FontFormat.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/FontFormat.java new file mode 100644 index 000000000..b7163af85 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/enums/FontFormat.java @@ -0,0 +1,54 @@ +package com.adityachandel.booklore.model.enums; + +import lombok.Getter; + +@Getter +public enum FontFormat { + TTF("font/ttf", ".ttf"), + OTF("font/otf", ".otf"), + WOFF("font/woff", ".woff"), + WOFF2("font/woff2", ".woff2"); + + private final String mimeType; + private final String extension; + + FontFormat(String mimeType, String extension) { + this.mimeType = mimeType; + this.extension = extension; + } + + public static FontFormat fromExtension(String extension) { + String normalizedExt = extension.toLowerCase(); + if (!normalizedExt.startsWith(".")) { + normalizedExt = "." + normalizedExt; + } + for (FontFormat format : values()) { + if (format.extension.equals(normalizedExt)) { + return format; + } + } + throw new IllegalArgumentException("Unsupported font format: " + extension); + } + + public static FontFormat fromMimeType(String mimeType) { + for (FontFormat format : values()) { + if (format.mimeType.equals(mimeType)) { + return format; + } + } + throw new IllegalArgumentException("Unsupported MIME type: " + mimeType); + } + + public static boolean isSupportedExtension(String extension) { + String normalizedExt = extension.toLowerCase(); + if (!normalizedExt.startsWith(".")) { + normalizedExt = "." + normalizedExt; + } + for (FontFormat format : values()) { + if (format.extension.equals(normalizedExt)) { + return true; + } + } + return false; + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/CustomFontRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/CustomFontRepository.java new file mode 100644 index 000000000..9276465ef --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/CustomFontRepository.java @@ -0,0 +1,19 @@ +package com.adityachandel.booklore.repository; + +import com.adityachandel.booklore.model.entity.CustomFontEntity; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; + +@Repository +public interface CustomFontRepository extends JpaRepository { + + List findByUserId(Long userId); + + int countByUserId(Long userId); + + Optional findByIdAndUserId(Long id, Long userId); + +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/customfont/CustomFontService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/customfont/CustomFontService.java new file mode 100644 index 000000000..42b0c3dd2 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/customfont/CustomFontService.java @@ -0,0 +1,331 @@ +package com.adityachandel.booklore.service.customfont; + +import com.adityachandel.booklore.config.AppProperties; +import com.adityachandel.booklore.exception.APIException; +import com.adityachandel.booklore.mapper.CustomFontMapper; +import com.adityachandel.booklore.model.dto.CustomFontDto; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.model.entity.CustomFontEntity; +import com.adityachandel.booklore.model.enums.FontFormat; +import com.adityachandel.booklore.repository.CustomFontRepository; +import com.adityachandel.booklore.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.io.FileSystemResource; +import org.springframework.core.io.Resource; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.LocalDateTime; +import java.util.List; +import java.util.UUID; +import java.util.stream.Collectors; + +@Slf4j +@Service +@RequiredArgsConstructor +public class CustomFontService { + + private final CustomFontRepository customFontRepository; + private final UserRepository userRepository; + private final CustomFontMapper customFontMapper; + private final AppProperties appProperties; + + private static final int MAX_FONTS_PER_USER = 10; + private static final long MAX_FILE_SIZE_BYTES = 5L * 1024 * 1024; + private static final String CUSTOM_FONTS_DIR = "custom-fonts"; + private static final int MAX_FONT_NAME_LENGTH = 100; + + @Transactional + public CustomFontDto uploadFont(MultipartFile file, String fontName, Long userId) { + Path fontPath = null; + CustomFontEntity savedEntity = null; + + try { + validateFontUpload(file, userId); + + BookLoreUserEntity user = userRepository.findById(userId) + .orElseThrow(() -> new IllegalArgumentException("User not found")); + + String originalFilename = file.getOriginalFilename(); + if (originalFilename == null || originalFilename.isEmpty()) { + throw new IllegalArgumentException("Invalid file name"); + } + + String extension = getFileExtension(originalFilename); + FontFormat format = FontFormat.fromExtension(extension); + + String uuid = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + String fileName = String.format("user_%d_font_%s%s", userId, uuid, format.getExtension()); + + Path fontDir = getFontDirectory(userId); + Files.createDirectories(fontDir); + fontPath = fontDir.resolve(fileName); + + validatePath(fontPath, fontDir); + + file.transferTo(fontPath.toFile()); + + validateFontMagicBytes(fontPath, format); + + String sanitizedFontName = sanitizeFontName(fontName, originalFilename); + + CustomFontEntity entity = CustomFontEntity.builder() + .user(user) + .fontName(sanitizedFontName) + .fileName(fileName) + .originalFileName(originalFilename) + .format(format) + .fileSize(file.getSize()) + .uploadedAt(LocalDateTime.now()) + .build(); + + savedEntity = customFontRepository.save(entity); + log.info("Font uploaded successfully for user {}: {} ({})", userId, sanitizedFontName, fileName); + + return customFontMapper.toDto(savedEntity); + + } catch (IOException e) { + log.error("Failed to upload font for user {}: {}", userId, e.getMessage(), e); + throw new APIException("Failed to upload font. Please try again or contact support if the problem persists.", HttpStatus.INTERNAL_SERVER_ERROR); + } finally { + if (fontPath != null && savedEntity == null) { + try { + Files.deleteIfExists(fontPath); + log.debug("Cleaned up orphaned font file after upload failure: {}", fontPath); + } catch (IOException e) { + log.warn("Failed to cleanup orphaned font file: {}", fontPath, e); + } + } + } + } + + public List getUserFonts(Long userId) { + List fonts = customFontRepository.findByUserId(userId); + return fonts.stream() + .map(customFontMapper::toDto) + .collect(Collectors.toList()); + } + + @Transactional + public void deleteFont(Long fontId, Long userId) { + CustomFontEntity font = customFontRepository.findByIdAndUserId(fontId, userId) + .orElseThrow(() -> new IllegalArgumentException("Font not found or access denied")); + + IOException fileDeleteException = null; + + try { + Path fontDir = getFontDirectory(userId); + Path fontPath = fontDir.resolve(font.getFileName()); + + validatePath(fontPath, fontDir); + + Files.deleteIfExists(fontPath); + } catch (IOException e) { + log.error("Failed to delete font file for user {}: {}", userId, e.getMessage(), e); + fileDeleteException = e; + } + + try { + customFontRepository.delete(font); + log.info("Font deleted successfully for user {}: {} ({})", userId, font.getFontName(), font.getFileName()); + } catch (Exception dbException) { + log.error("Failed to delete font from database for user {}: {}", userId, dbException.getMessage(), dbException); + + if (fileDeleteException != null) { + log.error("Additionally, file deletion also failed for font: {}", font.getFileName(), fileDeleteException); + } + + throw new APIException("Failed to delete font. Please try again or contact support if the problem persists.", HttpStatus.INTERNAL_SERVER_ERROR); + } + + if (fileDeleteException != null) { + log.warn("Font deleted from database but failed to delete file for user {}: {}", userId, font.getFileName(), fileDeleteException); + } + } + + public Resource getFontFile(Long fontId, Long userId) { + CustomFontEntity font = customFontRepository.findByIdAndUserId(fontId, userId) + .orElseThrow(() -> new IllegalArgumentException("Font not found or access denied")); + + Path fontDir = getFontDirectory(userId); + Path fontPath = fontDir.resolve(font.getFileName()); + + try { + validatePath(fontPath, fontDir); + } catch (IOException e) { + log.error("Invalid font path for user {}: {}", userId, fontPath, e); + throw new IllegalArgumentException("Invalid font file path"); + } + + File fontFile = fontPath.toFile(); + + if (!fontFile.exists()) { + throw new IllegalArgumentException("Font file not found on disk"); + } + + return new FileSystemResource(fontFile); + } + + public FontFormat getFontFormat(Long fontId, Long userId) { + CustomFontEntity font = customFontRepository.findByIdAndUserId(fontId, userId) + .orElseThrow(() -> new IllegalArgumentException("Font not found or access denied")); + return font.getFormat(); + } + + private void validateFontUpload(MultipartFile file, Long userId) { + if (file.isEmpty()) { + throw new IllegalArgumentException("File is empty"); + } + + if (file.getSize() > MAX_FILE_SIZE_BYTES) { + throw new IllegalArgumentException("File size exceeds maximum limit of 5MB"); + } + + int currentFontCount = customFontRepository.countByUserId(userId); + if (currentFontCount >= MAX_FONTS_PER_USER) { + throw new IllegalArgumentException(String.format("Font limit exceeded. Maximum %d fonts per user allowed", MAX_FONTS_PER_USER)); + } + + String originalFilename = file.getOriginalFilename(); + if (originalFilename == null || originalFilename.isEmpty()) { + throw new IllegalArgumentException("Invalid file name"); + } + + String extension = getFileExtension(originalFilename); + if (!FontFormat.isSupportedExtension(extension)) { + throw new IllegalArgumentException("Unsupported font format. Allowed formats: .ttf, .otf, .woff, .woff2"); + } + + String contentType = file.getContentType(); + if (contentType != null && !isSupportedMimeType(contentType)) { + log.warn("Potentially invalid MIME type for font: {}", contentType); + } + } + + private boolean isSupportedMimeType(String mimeType) { + return mimeType.equals("font/ttf") || + mimeType.equals("font/otf") || + mimeType.equals("font/woff") || + mimeType.equals("font/woff2") || + mimeType.equals("application/x-font-ttf") || + mimeType.equals("application/x-font-opentype") || + mimeType.equals("application/font-woff") || + mimeType.equals("application/font-woff2") || + mimeType.equals("application/octet-stream"); + } + + private String getFileExtension(String filename) { + int lastDotIndex = filename.lastIndexOf('.'); + if (lastDotIndex == -1 || lastDotIndex == filename.length() - 1) { + throw new IllegalArgumentException("File has no extension"); + } + return filename.substring(lastDotIndex); + } + + private Path getFontDirectory(Long userId) { + return Paths.get(appProperties.getPathConfig(), CUSTOM_FONTS_DIR, String.valueOf(userId)); + } + + /** + * Validates that the resolved path stays within the expected parent directory + * to prevent directory traversal attacks. + */ + private void validatePath(Path resolvedPath, Path expectedParent) throws IOException { + Path normalizedPath = resolvedPath.toAbsolutePath().normalize(); + Path normalizedParent = expectedParent.toAbsolutePath().normalize(); + + if (!normalizedPath.startsWith(normalizedParent)) { + log.error("Path traversal attempt detected: {} does not start with {}", normalizedPath, normalizedParent); + throw new IOException("Invalid file path: path traversal detected"); + } + } + + /** + * Validates font file format by checking magic bytes. + * Prevents malicious files from being uploaded with font extensions. + */ + private void validateFontMagicBytes(Path fontPath, FontFormat expectedFormat) throws IOException { + byte[] header = new byte[4]; + + try (var inputStream = Files.newInputStream(fontPath)) { + int bytesRead = inputStream.read(header); + + if (bytesRead < 4) { + throw new IllegalArgumentException("Invalid font file: file too small"); + } + } + + boolean isValid = false; + String detectedFormat = "Unknown"; + + // Check TTF signature: 0x00 0x01 0x00 0x00 or "true" (0x74 0x72 0x75 0x65) + if ((header[0] == 0x00 && header[1] == 0x01 && header[2] == 0x00 && header[3] == 0x00) || + (header[0] == 0x74 && header[1] == 0x72 && header[2] == 0x75 && header[3] == 0x65)) { + isValid = (expectedFormat == FontFormat.TTF); + detectedFormat = "TTF"; + } + // Check OTF signature: "OTTO" (0x4F 0x54 0x54 0x4F) + else if (header[0] == 0x4F && header[1] == 0x54 && header[2] == 0x54 && header[3] == 0x4F) { + isValid = (expectedFormat == FontFormat.OTF); + detectedFormat = "OTF"; + } + // Check WOFF signature: "wOFF" (0x77 0x4F 0x46 0x46) + else if (header[0] == 0x77 && header[1] == 0x4F && header[2] == 0x46 && header[3] == 0x46) { + isValid = (expectedFormat == FontFormat.WOFF); + detectedFormat = "WOFF"; + } + // Check WOFF2 signature: "wOF2" (0x77 0x4F 0x46 0x32) + else if (header[0] == 0x77 && header[1] == 0x4F && header[2] == 0x46 && header[3] == 0x32) { + isValid = (expectedFormat == FontFormat.WOFF2); + detectedFormat = "WOFF2"; + } + + if (!isValid) { + log.error("Font file magic bytes validation failed. Expected: {}, Detected: {}", expectedFormat, detectedFormat); + throw new IllegalArgumentException( + String.format("Invalid font file format. File appears to be %s but extension indicates %s", + detectedFormat, expectedFormat) + ); + } + + log.debug("Font file magic bytes validated successfully: {}", detectedFormat); + } + + /** + * Sanitizes font name to prevent XSS and ensure data integrity. + */ + private String sanitizeFontName(String fontName, String fallbackName) { + if (fontName == null || fontName.trim().isEmpty()) { + fontName = fallbackName; + } + + String sanitized = fontName.trim(); + + sanitized = sanitized.replaceAll("[\\p{Cntrl}\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]", ""); + + sanitized = sanitized.replaceAll("<[^>]*>", ""); + sanitized = sanitized.replaceAll("[<>\"'`]", ""); + + sanitized = sanitized.replaceAll("\\s+", " "); + + sanitized = sanitized.trim(); + + if (sanitized.isEmpty()) { + sanitized = fallbackName; + } + + if (sanitized.length() > MAX_FONT_NAME_LENGTH) { + sanitized = sanitized.substring(0, MAX_FONT_NAME_LENGTH).trim(); + } + + return sanitized; + } +} diff --git a/booklore-api/src/main/resources/db/migration/V85__Create_Custom_Font_Table.sql b/booklore-api/src/main/resources/db/migration/V85__Create_Custom_Font_Table.sql new file mode 100644 index 000000000..333d5feb7 --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V85__Create_Custom_Font_Table.sql @@ -0,0 +1,12 @@ +CREATE TABLE IF NOT EXISTS custom_font ( + id BIGINT AUTO_INCREMENT PRIMARY KEY, + user_id BIGINT NOT NULL, + font_name VARCHAR(255) NOT NULL, + file_name VARCHAR(255) NOT NULL UNIQUE, + original_file_name VARCHAR(255) NOT NULL, + format VARCHAR(10) NOT NULL, + file_size BIGINT NOT NULL, + uploaded_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + INDEX idx_user_id (user_id) +); diff --git a/booklore-api/src/main/resources/db/migration/V86__Add_Custom_Font_To_Epub_Preferences.sql b/booklore-api/src/main/resources/db/migration/V86__Add_Custom_Font_To_Epub_Preferences.sql new file mode 100644 index 000000000..31f0d942a --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V86__Add_Custom_Font_To_Epub_Preferences.sql @@ -0,0 +1,2 @@ +ALTER TABLE epub_viewer_preference ADD COLUMN IF NOT EXISTS custom_font_id BIGINT NULL; +ALTER TABLE epub_viewer_preference ADD FOREIGN KEY (custom_font_id) REFERENCES custom_font(id) ON DELETE SET NULL; diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/customfont/CustomFontServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/customfont/CustomFontServiceTest.java new file mode 100644 index 000000000..6d9c58942 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/customfont/CustomFontServiceTest.java @@ -0,0 +1,452 @@ +package com.adityachandel.booklore.service.customfont; + +import com.adityachandel.booklore.config.AppProperties; +import com.adityachandel.booklore.mapper.CustomFontMapper; +import com.adityachandel.booklore.model.dto.CustomFontDto; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.model.entity.CustomFontEntity; +import com.adityachandel.booklore.model.enums.FontFormat; +import com.adityachandel.booklore.repository.CustomFontRepository; +import com.adityachandel.booklore.repository.UserRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.springframework.core.io.Resource; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class CustomFontServiceTest { + + @TempDir + Path tempDir; + + @Mock + CustomFontRepository customFontRepository; + @Mock + UserRepository userRepository; + @Mock + CustomFontMapper customFontMapper; + + AppProperties appProperties; + CustomFontService service; + + @BeforeEach + void setUp() { + MockitoAnnotations.openMocks(this); + appProperties = new AppProperties(); + appProperties.setPathConfig(tempDir.toString()); + service = new CustomFontService(customFontRepository, userRepository, customFontMapper, appProperties); + } + + @Test + @DisplayName("uploadFont_withValidFile_shouldSaveSuccessfully") + void uploadFont_withValidFile_shouldSaveSuccessfully() throws IOException { + // Arrange + Long userId = 1L; + String fontName = "My Custom Font"; + // Create valid TTF magic bytes: 0x00 0x01 0x00 0x00 + byte[] fontContent = new byte[]{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", fontContent); + + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(userId); + + CustomFontEntity savedEntity = CustomFontEntity.builder() + .id(1L) + .user(user) + .fontName(fontName) + .fileName("user_1_font_123.ttf") + .originalFileName("font.ttf") + .format(FontFormat.TTF) + .fileSize((long) fontContent.length) + .build(); + + CustomFontDto expectedDto = new CustomFontDto(); + expectedDto.setId(1L); + expectedDto.setFontName(fontName); + + when(userRepository.findById(userId)).thenReturn(Optional.of(user)); + when(customFontRepository.countByUserId(userId)).thenReturn(0); + when(customFontRepository.save(any(CustomFontEntity.class))).thenReturn(savedEntity); + when(customFontMapper.toDto(savedEntity)).thenReturn(expectedDto); + + // Act + CustomFontDto result = service.uploadFont(file, fontName, userId); + + // Assert + assertThat(result).isNotNull(); + assertThat(result.getFontName()).isEqualTo(fontName); + verify(customFontRepository).save(any(CustomFontEntity.class)); + + // Verify file was saved + Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + assertThat(Files.exists(userFontDir)).isTrue(); + assertThat(Files.list(userFontDir).count()).isEqualTo(1); + } + + @Test + @DisplayName("uploadFont_whenQuotaExceeded_shouldThrowException") + void uploadFont_whenQuotaExceeded_shouldThrowException() { + // Arrange + Long userId = 1L; + MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", "content".getBytes()); + + when(customFontRepository.countByUserId(userId)).thenReturn(10); // Max quota + + // Act & Assert + assertThatThrownBy(() -> service.uploadFont(file, "Font", userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Font limit exceeded"); + + verify(customFontRepository, never()).save(any()); + } + + @Test + @DisplayName("uploadFont_withOversizedFile_shouldThrowException") + void uploadFont_withOversizedFile_shouldThrowException() { + // Arrange + Long userId = 1L; + byte[] largeContent = new byte[6 * 1024 * 1024]; // 6MB (exceeds 5MB limit) + MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", largeContent); + + when(customFontRepository.countByUserId(userId)).thenReturn(0); + + // Act & Assert + assertThatThrownBy(() -> service.uploadFont(file, "Font", userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("File size exceeds maximum limit"); + + verify(customFontRepository, never()).save(any()); + } + + @Test + @DisplayName("uploadFont_withInvalidExtension_shouldThrowException") + void uploadFont_withInvalidExtension_shouldThrowException() { + // Arrange + Long userId = 1L; + MultipartFile file = new MockMultipartFile("font.exe", "font.exe", "application/octet-stream", "content".getBytes()); + + when(customFontRepository.countByUserId(userId)).thenReturn(0); + + // Act & Assert + assertThatThrownBy(() -> service.uploadFont(file, "Font", userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported font format"); + + verify(customFontRepository, never()).save(any()); + } + + @Test + @DisplayName("uploadFont_withInvalidMagicBytes_shouldThrowException") + void uploadFont_withInvalidMagicBytes_shouldThrowException() throws IOException { + // Arrange + Long userId = 1L; + // File has .ttf extension but contains malicious content (not TTF magic bytes) + byte[] maliciousContent = "This is not a font file".getBytes(); + MultipartFile file = new MockMultipartFile("malicious.ttf", "malicious.ttf", "font/ttf", maliciousContent); + + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(userId); + + when(userRepository.findById(userId)).thenReturn(Optional.of(user)); + when(customFontRepository.countByUserId(userId)).thenReturn(0); + + // Act & Assert + assertThatThrownBy(() -> service.uploadFont(file, "Font", userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid font file format"); + + verify(customFontRepository, never()).save(any()); + + // Verify file was cleaned up + Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + if (Files.exists(userFontDir)) { + assertThat(Files.list(userFontDir).count()).isEqualTo(0); + } + } + + @Test + @DisplayName("uploadFont_whenDatabaseSaveFails_shouldCleanupFile") + void uploadFont_whenDatabaseSaveFails_shouldCleanupFile() throws IOException { + // Arrange + Long userId = 1L; + // Create valid TTF magic bytes + byte[] fontContent = new byte[]{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + MultipartFile file = new MockMultipartFile("font.ttf", "font.ttf", "font/ttf", fontContent); + + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(userId); + + when(userRepository.findById(userId)).thenReturn(Optional.of(user)); + when(customFontRepository.countByUserId(userId)).thenReturn(0); + when(customFontRepository.save(any(CustomFontEntity.class))) + .thenThrow(new RuntimeException("Database error")); + + // Act & Assert + assertThatThrownBy(() -> service.uploadFont(file, "Font", userId)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("Database error"); + + // Verify file was cleaned up + Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + if (Files.exists(userFontDir)) { + assertThat(Files.list(userFontDir).count()).isEqualTo(0); + } + } + + @Test + @DisplayName("deleteFont_withValidId_shouldDeleteFileAndRecord") + void deleteFont_withValidId_shouldDeleteFileAndRecord() throws IOException { + // Arrange + Long userId = 1L; + Long fontId = 1L; + String fileName = "user_1_font_123.ttf"; + + // Create actual font file + Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + Files.createDirectories(userFontDir); + Path fontFile = userFontDir.resolve(fileName); + Files.writeString(fontFile, "font content"); + + CustomFontEntity font = CustomFontEntity.builder() + .id(fontId) + .fontName("Test Font") + .fileName(fileName) + .build(); + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font)); + + // Act + service.deleteFont(fontId, userId); + + // Assert + verify(customFontRepository).delete(font); + assertThat(Files.exists(fontFile)).isFalse(); + } + + @Test + @DisplayName("deleteFont_whenFileDeletionFails_shouldStillDeleteRecord") + void deleteFont_whenFileDeletionFails_shouldStillDeleteRecord() { + // Arrange + Long userId = 1L; + Long fontId = 1L; + String fileName = "non_existent_font.ttf"; + + CustomFontEntity font = CustomFontEntity.builder() + .id(fontId) + .fontName("Test Font") + .fileName(fileName) + .build(); + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font)); + + // Act + // Files.deleteIfExists doesn't throw when file doesn't exist, so this should succeed + assertThatCode(() -> service.deleteFont(fontId, userId)) + .doesNotThrowAnyException(); + + // Database record should be deleted + verify(customFontRepository, times(1)).delete(font); + } + + @Test + @DisplayName("deleteFont_withInvalidId_shouldThrowException") + void deleteFont_withInvalidId_shouldThrowException() { + // Arrange + Long userId = 1L; + Long fontId = 999L; + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.empty()); + + // Act & Assert + assertThatThrownBy(() -> service.deleteFont(fontId, userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Font not found or access denied"); + + verify(customFontRepository, never()).delete(any()); + } + + @Test + @DisplayName("getFontFile_withValidId_shouldReturnResource") + void getFontFile_withValidId_shouldReturnResource() throws IOException { + // Arrange + Long userId = 1L; + Long fontId = 1L; + String fileName = "user_1_font_123.ttf"; + + // Create actual font file + Path userFontDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + Files.createDirectories(userFontDir); + Path fontFile = userFontDir.resolve(fileName); + Files.writeString(fontFile, "font content"); + + CustomFontEntity font = CustomFontEntity.builder() + .id(fontId) + .fontName("Test Font") + .fileName(fileName) + .build(); + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font)); + + // Act + Resource result = service.getFontFile(fontId, userId); + + // Assert + assertThat(result).isNotNull(); + assertThat(result.exists()).isTrue(); + assertThat(result.getFile().toPath()).isEqualTo(fontFile); + } + + @Test + @DisplayName("getFontFile_whenUserNotOwner_shouldThrowException") + void getFontFile_whenUserNotOwner_shouldThrowException() { + // Arrange + Long userId = 1L; + Long otherUserId = 2L; + Long fontId = 1L; + + when(customFontRepository.findByIdAndUserId(fontId, otherUserId)).thenReturn(Optional.empty()); + + // Act & Assert + assertThatThrownBy(() -> service.getFontFile(fontId, otherUserId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Font not found or access denied"); + } + + @Test + @DisplayName("getFontFile_withNonExistentFile_shouldThrowException") + void getFontFile_withNonExistentFile_shouldThrowException() { + // Arrange + Long userId = 1L; + Long fontId = 1L; + String fileName = "non_existent.ttf"; + + CustomFontEntity font = CustomFontEntity.builder() + .id(fontId) + .fontName("Test Font") + .fileName(fileName) + .build(); + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font)); + + // Act & Assert + assertThatThrownBy(() -> service.getFontFile(fontId, userId)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Font file not found on disk"); + } + + @Test + @DisplayName("validatePath_withPathTraversal_shouldThrowException") + void validatePath_withPathTraversal_shouldThrowException() throws IOException { + // Arrange + Long userId = 1L; + // Use valid font extension to pass extension validation + String maliciousFileName = "../../../etc/passwd.ttf"; + // Create valid TTF magic bytes to pass magic byte validation + byte[] fontContent = new byte[]{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; + MultipartFile file = new MockMultipartFile( + maliciousFileName, + maliciousFileName, + "font/ttf", + fontContent + ); + + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(userId); + + when(userRepository.findById(userId)).thenReturn(Optional.of(user)); + when(customFontRepository.countByUserId(userId)).thenReturn(0); + + // Mock repository save to complete the upload + when(customFontRepository.save(any(CustomFontEntity.class))).thenAnswer(invocation -> { + CustomFontEntity entity = invocation.getArgument(0); + entity.setId(1L); + return entity; + }); + + CustomFontDto mockDto = new CustomFontDto(); + mockDto.setId(1L); + when(customFontMapper.toDto(any(CustomFontEntity.class))).thenReturn(mockDto); + + // Act & Assert + // The service generates safe filenames, so even with malicious input, the path is safe + assertThatCode(() -> service.uploadFont(file, "Test", userId)) + .doesNotThrowAnyException(); // Safe because service generates safe filename + + // Verify no files were created outside the expected directory + Path expectedDir = tempDir.resolve("custom-fonts").resolve(String.valueOf(userId)); + Path parentDir = tempDir.resolve("custom-fonts"); + + // Count files in user directory + long userDirFiles = Files.exists(expectedDir) ? Files.list(expectedDir).count() : 0; + + // Count files in parent directory (should only be the user directory) + long parentDirEntries = Files.list(parentDir).count(); + + assertThat(userDirFiles).isGreaterThanOrEqualTo(0); + assertThat(parentDirEntries).isEqualTo(1); // Only user directory, no escaped files + } + + @Test + @DisplayName("getUserFonts_shouldReturnAllUserFonts") + void getUserFonts_shouldReturnAllUserFonts() { + // Arrange + Long userId = 1L; + List entities = List.of( + CustomFontEntity.builder().id(1L).fontName("Font 1").build(), + CustomFontEntity.builder().id(2L).fontName("Font 2").build() + ); + + CustomFontDto dto1 = new CustomFontDto(); + dto1.setId(1L); + CustomFontDto dto2 = new CustomFontDto(); + dto2.setId(2L); + + when(customFontRepository.findByUserId(userId)).thenReturn(entities); + when(customFontMapper.toDto(entities.get(0))).thenReturn(dto1); + when(customFontMapper.toDto(entities.get(1))).thenReturn(dto2); + + // Act + List result = service.getUserFonts(userId); + + // Assert + assertThat(result).hasSize(2); + assertThat(result.get(0).getId()).isEqualTo(1L); + assertThat(result.get(1).getId()).isEqualTo(2L); + } + + @Test + @DisplayName("getFontFormat_shouldReturnCorrectFormat") + void getFontFormat_shouldReturnCorrectFormat() { + // Arrange + Long userId = 1L; + Long fontId = 1L; + + CustomFontEntity font = CustomFontEntity.builder() + .id(fontId) + .fontName("Test Font") + .format(FontFormat.WOFF2) + .build(); + + when(customFontRepository.findByIdAndUserId(fontId, userId)).thenReturn(Optional.of(font)); + + // Act + FontFormat result = service.getFontFormat(fontId, userId); + + // Assert + assertThat(result).isEqualTo(FontFormat.WOFF2); + } +} diff --git a/booklore-ui/src/app/features/book/model/book.model.ts b/booklore-ui/src/app/features/book/model/book.model.ts index d9c8ec3f2..773592002 100644 --- a/booklore-ui/src/app/features/book/model/book.model.ts +++ b/booklore-ui/src/app/features/book/model/book.model.ts @@ -201,6 +201,7 @@ export interface EpubViewerSetting { lineHeight: number; letterSpacing: number; spread: string; + customFontId?: number | null; } export interface CbxViewerSetting { diff --git a/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.html b/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.html index 7abcc1680..a3f6251f6 100644 --- a/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.html +++ b/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.html @@ -166,7 +166,8 @@ [(ngModel)]="selectedFontType" (onChange)="changeFontType()" [style]="{ width: '100%' }" - placeholder="Select font"> + [loading]="!customFontsReady" + placeholder="Loading fonts...">
diff --git a/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.ts b/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.ts index cb3ebbe99..f7618820e 100644 --- a/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.ts +++ b/booklore-ui/src/app/features/readers/epub-reader/component/epub-reader.component.ts @@ -1,7 +1,7 @@ import {Component, ElementRef, inject, NgZone, OnDestroy, OnInit, ViewChild} from '@angular/core'; import ePub from 'epubjs'; import {Drawer} from 'primeng/drawer'; -import {forkJoin, Subscription} from 'rxjs'; +import {firstValueFrom, forkJoin, Subscription} from 'rxjs'; import {Button} from 'primeng/button'; import {InputText} from 'primeng/inputtext'; import {CommonModule, Location} from '@angular/common'; @@ -25,6 +25,9 @@ import {IconField} from 'primeng/iconfield'; import {InputIcon} from 'primeng/inputicon'; import {BookmarkEditDialogComponent} from './bookmark-edit-dialog.component'; import {BookmarkViewDialogComponent} from './bookmark-view-dialog.component'; +import {CustomFontService} from '../../../../shared/service/custom-font.service'; +import {CustomFont} from '../../../../shared/model/custom-font.model'; +import {addCustomFontsToDropdown} from '../../../../shared/util/custom-font.util'; @Component({ selector: 'app-epub-reader', @@ -85,6 +88,9 @@ export class EpubReaderComponent implements OnInit, OnDestroy { selectedSpread?: string = 'double'; lineHeight?: number; letterSpacing?: number; + selectedCustomFontId?: number | null = null; + customFonts: CustomFont[] = []; + customFontsReady = false; fontTypes: any[] = [ {label: "Publisher's Default", value: null}, @@ -122,14 +128,30 @@ export class EpubReaderComponent implements OnInit, OnDestroy { private pageTitle = inject(PageTitleService); private bookMarkService = inject(BookMarkService); private readingSessionService = inject(ReadingSessionService); + private customFontService = inject(CustomFontService); epub!: Book; ngOnInit(): void { - this.routeSubscription = this.route.paramMap.subscribe((params) => { + this.routeSubscription = this.route.paramMap.subscribe(async (params) => { this.isLoading = true; const bookId = +params.get('bookId')!; + // Load custom fonts FIRST and wait for them + try { + const fonts = await firstValueFrom(this.customFontService.getUserFonts()); + this.customFonts = fonts; + // Wait for all fonts to load into the browser + await this.customFontService.loadAllFonts(fonts); + // Add custom fonts to dropdown + addCustomFontsToDropdown(fonts, this.fontTypes, 'select'); + } catch (err) { + console.error('Failed to load custom fonts:', err); + } finally { + // Mark fonts as ready even if loading fails (allows UI to proceed) + this.customFontsReady = true; + } + const myself$ = this.userService.getMyself(); const epub$ = this.bookService.getBookByIdFromAPI(bookId, false); const epubData$ = this.bookService.getFileContent(bookId); @@ -159,6 +181,7 @@ export class EpubReaderComponent implements OnInit, OnDestroy { const resolvedLineHeight = settingScope === 'Global' ? globalSettings.lineHeight : individualSetting?.lineHeight; const resolvedLetterSpacing = settingScope === 'Global' ? globalSettings.letterSpacing : individualSetting?.letterSpacing; const resolvedSpread = settingScope === 'Global' ? globalSettings.spread || 'double' : individualSetting?.spread || 'double'; + const resolvedCustomFontId = settingScope === 'Global' ? globalSettings.customFontId : individualSetting?.customFontId; if (resolvedTheme != null) this.selectedTheme = resolvedTheme; if (resolvedFontFamily != null) this.selectedFontType = resolvedFontFamily; @@ -168,6 +191,12 @@ export class EpubReaderComponent implements OnInit, OnDestroy { if (resolvedFlow != null) this.selectedFlow = resolvedFlow; if (resolvedSpread != null) this.selectedSpread = resolvedSpread; + // Set font type from settings (including custom font format) + // Don't set selectedCustomFontId yet - let applyEpubTheme() set it after verification + if (resolvedCustomFontId != null) { + this.selectedFontType = `custom:${resolvedCustomFontId}`; + } + this.initBook(); this.initRendition(); }; @@ -267,15 +296,103 @@ export class EpubReaderComponent implements OnInit, OnDestroy { } } - changeFontType(): void { - if (this.rendition) { - if (this.selectedFontType) { - this.rendition.themes.font(this.selectedFontType); - } else { - this.rendition.themes.font(''); - } - this.updateViewerSetting(); + async changeFontType(): Promise { + const result = await this.applyEpubTheme(); + + // Update state based on result + if (!result.success) { + // Font loading failed, clear the selection + this.selectedFontType = null; + this.selectedCustomFontId = null; + } else if (result.customFontId !== undefined) { + // Custom font loaded successfully or cleared + this.selectedCustomFontId = result.customFontId; } + + this.updateViewerSetting(); + } + + private async applyEpubTheme(): Promise<{ success: boolean, customFontId?: number | null }> { + if (!this.rendition) return { success: false }; + + // Determine font family - handle custom fonts + let fontFamily = this.selectedFontType; + let customFontToInject: CustomFont | null = null; + let customFontId: number | null = null; + + if (this.selectedFontType?.startsWith('custom:')) { + const fontId = parseInt(this.selectedFontType.split(':')[1]); + const customFont = this.customFonts.find(f => f.id === fontId); + if (customFont) { + try { + await this.customFontService.loadFontFace(customFont); + if (this.customFontService.isFontLoaded(customFont.fontName)) { + fontFamily = customFont.fontName; + customFontId = fontId; + customFontToInject = customFont; + } else { + // Font didn't load properly + return { success: false }; + } + } catch (error) { + // Font loading failed + console.error('Failed to load custom font:', error); + this.messageService.add({ + severity: 'warn', + summary: 'Custom fonts not loaded', + detail: 'Your custom fonts could not be loaded. The reader will use default fonts instead.', + }); + return { success: false }; + } + } + } else { + customFontId = null; + } + + // Inject or clear @font-face rules + if (customFontToInject) { + const fontUrl = this.customFontService.getFontUrl(customFontToInject.id); + const fontUrlWithToken = this.customFontService.appendToken(fontUrl); + this.rendition.themes.default({ + '@font-face': [{ + 'font-family': `"${customFontToInject.fontName}"`, + 'src': `url(${fontUrlWithToken})`, + 'font-weight': 'normal', + 'font-style': 'normal' + }] + }); + } else { + this.rendition.themes.default({}); + } + + // Apply font using EPUB.js font() method + if (fontFamily) { + this.rendition.themes.font(customFontToInject ? `"${fontFamily}"` : fontFamily); + } else { + this.rendition.themes.font(''); + } + + // Apply theme with other settings + const baseTheme = EpubThemeUtil.themesMap.get(this.selectedTheme ?? 'black') || {}; + const combinedTheme = { + ...baseTheme, + body: { + ...baseTheme.body, + ...(this.lineHeight != null ? {'line-height': this.lineHeight} : {}), + ...(this.letterSpacing != null ? {'letter-spacing': `${this.letterSpacing}em`} : {}), + }, + '*': { + ...baseTheme['*'], + ...(this.lineHeight != null ? {'line-height': this.lineHeight} : {}), + ...(this.letterSpacing != null ? {'letter-spacing': `${this.letterSpacing}em`} : {}), + }, + }; + + this.rendition.themes.override('font-size', `${this.fontSize}%`); + this.rendition.themes.register('custom', combinedTheme); + this.rendition.themes.select('custom'); + + return { success: true, customFontId }; } increaseFontSize(): void { @@ -298,6 +415,7 @@ export class EpubReaderComponent implements OnInit, OnDestroy { if (this.selectedSpread === 'single' || this.selectedSpread === 'double') epubSettings.spread = this.selectedSpread; if (this.lineHeight) epubSettings.lineHeight = this.lineHeight; if (this.letterSpacing) epubSettings.letterSpacing = this.letterSpacing; + if (this.selectedCustomFontId != null) epubSettings.customFontId = this.selectedCustomFontId; const bookSetting: BookSetting = { epubSettings: epubSettings @@ -651,7 +769,6 @@ export class EpubReaderComponent implements OnInit, OnDestroy { ...baseTheme, body: { ...(baseTheme.body || {}), - ...(this.selectedFontType ? {'font-family': this.selectedFontType} : {}), ...(this.lineHeight != null ? {'line-height': this.lineHeight} : {}), ...(this.letterSpacing != null ? {'letter-spacing': `${this.letterSpacing}em`} : {}), }, @@ -670,7 +787,18 @@ export class EpubReaderComponent implements OnInit, OnDestroy { ? this.rendition.display(targetCfi) : (this.epub?.epubProgress?.cfi ? this.rendition.display(this.epub.epubProgress.cfi) : this.rendition.display()); - displayPromise.then(() => { + displayPromise.then(async () => { + // Apply custom font after rendition is displayed + const result = await this.applyEpubTheme(); + + // If font loading failed during initialization, clear the selection + if (!result.success) { + this.selectedFontType = null; + this.selectedCustomFontId = null; + } else if (result.customFontId !== undefined) { + this.selectedCustomFontId = result.customFontId; + } + this.updateCurrentChapter(this.rendition.currentLocation()); this.setupKeyListener(); this.trackProgress(); diff --git a/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.html b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.html new file mode 100644 index 000000000..78c8594fe --- /dev/null +++ b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.html @@ -0,0 +1,126 @@ +
+
+
+
+

+ + Custom Fonts +

+

+ Upload and manage your own fonts for a personalized reading experience in the EPUB reader. + You have {{ customFonts.length }} of {{ maxFonts }} custom fonts. +

+
+ +
+
+ +
+ + @if (customFonts.length === 0 && !isLoading) { +
+
+
+ +
+

No Custom Fonts Yet

+

+ Upload your favorite fonts to personalize your reading experience.
+ Click the "Add New Font" button above to get started. +

+

+ + Supported formats: TTF, OTF, WOFF, WOFF2 +

+
+
+ } @else { +
+
+

+ + Your Font Library + ({{ customFonts.length }}) +

+

+ Manage your uploaded custom fonts. Each font can be selected in the EPUB reader settings. +

+
+ +
+ @for (font of customFonts; track font.id) { +
+
+
+

{{ font.fontName }}

+ {{ font.format }} +
+ +
+ +
+ + @if (!fontsLoadedInBrowser) { +
+ + + + + + +
+ } @else { +
+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +

+

+ Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. +

+
+ ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 +
+
+ } +
+ + +
+ } +
+
+ } +
+
+ + diff --git a/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.scss b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.scss new file mode 100644 index 000000000..76b6a3e0e --- /dev/null +++ b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.scss @@ -0,0 +1,384 @@ +.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); + } +} + +.enclosing-container { + border-color: var(--p-content-border-color); + background: var(--p-content-background); +} + +.settings-header { + margin-top: 1rem; + margin-bottom: 2rem; + + .header-content { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 2rem; + + @media (max-width: 768px) { + flex-direction: column; + gap: 1rem; + } + } + + .header-text { + flex: 1; + } +} + +.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; + } +} + +.settings-description { + color: var(--p-text-muted-color); + font-size: 0.875rem; + line-height: 1.5; + margin-bottom: 0; +} + +.settings-content { + display: flex; + flex-direction: column; + gap: 2rem; +} + +.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); + } + + .font-count { + color: var(--p-text-muted-color); + font-size: 1rem; + font-weight: 500; + } +} + +.section-description { + color: var(--p-text-muted-color); + font-size: 0.875rem; + line-height: 1.5; + margin: 0; +} + +.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: 1rem; +} + +// ==================== Empty State ==================== +.empty-state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + text-align: center; + padding: 3rem 1.5rem; + min-height: 300px; + + .empty-icon-wrapper { + display: flex; + align-items: center; + justify-content: center; + width: 80px; + height: 80px; + background: color-mix(in srgb, var(--p-primary-color) 10%, transparent); + border-radius: 50%; + margin-bottom: 1.5rem; + border: 3px dashed var(--p-primary-color); + + .empty-icon { + font-size: 2.5rem; + color: var(--p-primary-color); + opacity: 0.7; + } + } + + .empty-title { + margin: 0 0 0.75rem 0; + font-size: 1.25rem; + font-weight: 600; + color: var(--p-text-color); + } + + .empty-description { + margin: 0 0 1rem 0; + font-size: 0.9375rem; + color: var(--p-text-muted-color); + max-width: 500px; + line-height: 1.6; + } + + .empty-hint { + display: flex; + align-items: center; + justify-content: center; + gap: 0.5rem; + margin: 0; + padding: 0.75rem 1.25rem; + background: color-mix(in srgb, var(--p-primary-color) 5%, transparent); + border: 1px solid color-mix(in srgb, var(--p-primary-color) 20%, transparent); + border-radius: 6px; + font-size: 0.8125rem; + color: var(--p-text-muted-color); + max-width: 500px; + + i { + color: var(--p-primary-color); + font-size: 0.875rem; + flex-shrink: 0; + } + + strong { + color: var(--p-text-color); + font-weight: 600; + } + } + + @media (max-width: 768px) { + padding: 2rem 1rem; + min-height: 250px; + + .empty-icon-wrapper { + width: 70px; + height: 70px; + margin-bottom: 1rem; + + .empty-icon { + font-size: 2rem; + } + } + + .empty-title { + font-size: 1.125rem; + } + + .empty-description { + font-size: 0.875rem; + max-width: 100%; + } + + .empty-hint { + font-size: 0.75rem; + padding: 0.625rem 1rem; + max-width: 100%; + flex-direction: column; + text-align: center; + gap: 0.375rem; + } + } +} + +// ==================== Fonts Grid ==================== +.fonts-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); + gap: 1.5rem; + + @media (max-width: 768px) { + grid-template-columns: 1fr; + } +} + +// ==================== Font Card ==================== +.font-card { + padding: 0; + gap: 0; + + .font-card-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 1rem; + padding: 1rem 1rem 0.75rem; + border-bottom: 1px solid var(--p-content-border-color); + + .font-title-group { + flex: 1; + display: flex; + align-items: center; + gap: 0.75rem; + flex-wrap: wrap; + + .font-name { + margin: 0; + font-size: 1rem; + font-weight: 600; + color: var(--p-text-color); + } + + .format-tag { + display: inline-block; + padding: 0.1875rem 0.5rem; + border-radius: 4px; + background: transparent; + border: 1px solid var(--p-primary-color); + color: var(--p-primary-color); + font-size: 0.6875rem; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.025em; + } + } + } + + .font-preview-area { + padding: 1rem; + border-bottom: 1px solid var(--p-content-border-color); + + .preview-label { + display: flex; + align-items: center; + gap: 0.375rem; + font-size: 0.75rem; + font-weight: 600; + color: var(--p-text-muted-color); + text-transform: uppercase; + letter-spacing: 0.025em; + margin-bottom: 0.75rem; + + i { + font-size: 0.75rem; + } + } + + .font-preview { + padding: 1rem; + border: 1px solid var(--p-content-border-color); + border-radius: 6px; + background: color-mix(in srgb, var(--p-surface-ground) 30%, var(--p-content-background)); + display: flex; + flex-direction: column; + gap: 0.75rem; + + .preview-paragraph { + color: var(--p-text-color); + font-size: 0.9375rem; + line-height: 1.7; + margin: 0; + text-align: justify; + font-weight: 400; + } + + .preview-paragraph-small { + color: var(--p-text-color); + font-size: 0.8125rem; + line-height: 1.6; + margin: 0; + text-align: justify; + font-weight: 400; + } + + .preview-characters { + display: flex; + flex-direction: column; + gap: 0.25rem; + padding-top: 0.5rem; + margin-top: 0.25rem; + border-top: 1px solid var(--p-content-border-color); + + span { + font-size: 0.6875rem; + color: var(--p-text-muted-color); + letter-spacing: 0.025em; + font-weight: 400; + } + } + } + + .font-preview-skeleton { + padding: 1rem; + border: 1px solid var(--p-content-border-color); + border-radius: 6px; + background: color-mix(in srgb, var(--p-surface-ground) 30%, var(--p-content-background)); + display: flex; + flex-direction: column; + gap: 0.75rem; + } + } + + .font-metadata { + padding: 1rem; + background: color-mix(in srgb, var(--p-surface-ground) 20%, var(--p-content-background)); + + .metadata-row { + display: flex; + justify-content: space-between; + align-items: center; + gap: 1rem; + padding: 0.375rem 0; + + &:not(:last-child) { + border-bottom: 1px solid var(--p-content-border-color); + } + + .meta-label { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.8125rem; + color: var(--p-text-muted-color); + font-weight: 500; + + i { + color: var(--p-primary-color); + font-size: 0.75rem; + } + } + + .meta-value { + font-size: 0.8125rem; + color: var(--p-text-color); + font-weight: 500; + text-align: right; + word-break: break-word; + } + } + } +} diff --git a/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.ts b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.ts new file mode 100644 index 000000000..d40cc7bb2 --- /dev/null +++ b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.ts @@ -0,0 +1,133 @@ +import {Component, OnInit} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {Button} from 'primeng/button'; +import {MessageService} from 'primeng/api'; +import {CustomFontService} from '../../../shared/service/custom-font.service'; +import {CustomFont, formatFileSize} from '../../../shared/model/custom-font.model'; +import {ConfirmDialog} from 'primeng/confirmdialog'; +import {ConfirmationService} from 'primeng/api'; +import {Tooltip} from 'primeng/tooltip'; +import {DialogService, DynamicDialogRef} from 'primeng/dynamicdialog'; +import {FontUploadDialogComponent} from './font-upload-dialog/font-upload-dialog.component'; +import {Skeleton} from 'primeng/skeleton'; + +@Component({ + selector: 'app-custom-fonts', + standalone: true, + imports: [CommonModule, Button, ConfirmDialog, Tooltip, Skeleton], + templateUrl: './custom-fonts.component.html', + styleUrls: ['./custom-fonts.component.scss'], + providers: [ConfirmationService, DialogService] +}) +export class CustomFontsComponent implements OnInit { + customFonts: CustomFont[] = []; + isLoading = true; + fontsLoadedInBrowser = false; + uploadDialogRef: DynamicDialogRef | null = null; + + readonly maxFonts = 10; + + constructor( + private customFontService: CustomFontService, + private messageService: MessageService, + private confirmationService: ConfirmationService, + private dialogService: DialogService + ) {} + + ngOnInit(): void { + this.loadFonts(); + } + + async loadFonts(): Promise { + this.fontsLoadedInBrowser = false; + + try { + const fonts = await new Promise((resolve, reject) => { + this.customFontService.getUserFonts().subscribe({ + next: resolve, + error: reject + }); + }); + + this.customFonts = fonts; + this.isLoading = false; + + await this.customFontService.loadAllFonts(fonts); + + this.fontsLoadedInBrowser = true; + } catch (error) { + console.error('Failed to load fonts:', error); + this.messageService.add({ + severity: 'error', + summary: 'Error', + detail: 'Failed to load custom fonts' + }); + this.isLoading = false; + this.fontsLoadedInBrowser = true; + } + } + + openUploadDialog(): void { + if (this.customFonts.length >= this.maxFonts) { + this.messageService.add({ + severity: 'error', + summary: 'Quota Exceeded', + detail: `Maximum ${this.maxFonts} fonts allowed per user` + }); + return; + } + + this.uploadDialogRef = this.dialogService.open(FontUploadDialogComponent, { + showHeader: false, + styleClass: 'dynamic-dialog-minimal', + modal: true, + dismissableMask: false, + closable: false, + width: '700px', + breakpoints: { + '768px': '95vw' + } + }); + + if (this.uploadDialogRef) { + this.uploadDialogRef.onClose.subscribe((font: CustomFont | null) => { + if (font) { + this.customFonts.push(font); + } + this.uploadDialogRef = null; + }); + } + } + + deleteFont(font: CustomFont): void { + this.confirmationService.confirm({ + message: `Are you sure you want to delete the font "${font.fontName}"?`, + header: 'Delete Font', + icon: 'pi pi-exclamation-triangle', + accept: () => { + this.customFontService.deleteFont(font.id).subscribe({ + next: () => { + this.customFonts = this.customFonts.filter(f => f.id !== font.id); + this.messageService.add({ + severity: 'success', + summary: 'Success', + detail: `Font "${font.fontName}" deleted successfully` + }); + }, + error: (error) => { + console.error('Failed to delete font:', error); + this.messageService.add({ + severity: 'error', + summary: 'Delete Failed', + detail: 'Failed to delete font' + }); + } + }); + } + }); + } + + formatFileSize(bytes: number): string { + return formatFileSize(bytes); + } +} diff --git a/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.html b/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.html new file mode 100644 index 000000000..687ff1e90 --- /dev/null +++ b/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.html @@ -0,0 +1,131 @@ +
+
+
+ +
+
+

Add New Font

+

+ Upload a custom font for your EPUB reader +

+
+ +
+ +
+
+
+ + + Select Font File + +
+ + @if (!selectedFile) { +
+ +
+
+ +
+

Drag and Drop Font File

+

+ Supported formats: TTF, OTF, WOFF, WOFF2 +
+ Maximum file size: 5 MB +

+
+
+ } @else { +
+
+ +
+ {{ selectedFile.name }} + {{ formatFileSize(selectedFile.size) }} • {{ selectedFile.name.split('.').pop()?.toUpperCase() }} +
+
+ + @if (previewFontFamily) { +
+ +
+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. + Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. +

+

+ Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. + Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. +

+
+ ABCDEFGHIJKLMNOPQRSTUVWXYZ + abcdefghijklmnopqrstuvwxyz + 0123456789 !@#$%^&*() +
+
+
+ } + +
+
+ +

+ This name will appear in the font selector when reading EPUB books. +

+
+
+ +
+
+
+ } +
+ + +
diff --git a/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.scss b/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.scss new file mode 100644 index 000000000..91b3fa411 --- /dev/null +++ b/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.scss @@ -0,0 +1,443 @@ +.font-upload-dialog { + width: 700px; + max-width: 700px; + display: flex; + flex-direction: column; + + @media (max-width: 768px) { + width: 100%; + max-width: 100%; + } +} + +.panel-header { + position: relative; + display: flex; + align-items: center; + gap: 1rem; + padding: 1.5rem 1.5rem 1.25rem 1.5rem; + border-radius: 10px 10px 0 0; + border: 1px solid var(--border-color); + border-bottom: none; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08); + + .header-icon-wrapper { + display: flex; + align-items: center; + justify-content: center; + width: 48px; + height: 48px; + background: var(--primary-color); + border-radius: 10px; + + .header-icon { + font-size: 1.5rem; + color: var(--primary-contrast-color); + } + } + + .header-text { + flex: 1; + + .panel-title { + margin: 0 0 0.25rem 0; + font-size: 1.25rem; + font-weight: 600; + color: var(--text-color); + } + + .panel-description { + margin: 0; + font-size: 0.875rem; + color: var(--text-secondary-color); + } + } + + .close-button { + position: absolute; + top: 0.75rem; + right: 0.75rem; + } + + @media (max-width: 480px) { + padding: 1rem; + + .header-icon-wrapper { + width: 40px; + height: 40px; + + .header-icon { + font-size: 1.25rem; + } + } + + .header-text { + .panel-title { + font-size: 1.125rem; + } + + .panel-description { + font-size: 0.8rem; + } + } + + .close-button { + top: 0.5rem; + right: 0.5rem; + + ::ng-deep .p-button { + width: 2rem; + height: 2rem; + } + } + } +} + +.upload-container { + display: flex; + flex-direction: column; + gap: 1rem; + padding: 1.75rem; + background: var(--card-background); + border: 1px solid var(--border-color); + border-radius: 0 0 10px 10px; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08); + + @media (max-width: 480px) { + padding: 1rem; + gap: 1rem; + } +} + +.file-upload-section { + display: flex; + flex-direction: column; + + .section-header { + display: flex; + align-items: center; + justify-content: center; + padding: 0.625rem 0.875rem; + background: var(--overlay-background); + border-radius: 6px; + + .section-title { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 0.9rem; + font-weight: 600; + color: var(--text-color); + + i { + color: var(--primary-color); + font-size: 1rem; + } + } + + @media (max-width: 480px) { + padding: 0.5rem 0.625rem; + + .section-title { + font-size: 0.85rem; + } + } + } + + .empty-state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + text-align: center; + padding: 1.5rem 1rem; + + .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; + border: 3px dashed var(--border-color); + + .empty-icon { + font-size: 2.5rem; + color: var(--text-secondary-color); + opacity: 0.6; + } + } + + .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: 450px; + line-height: 1.5; + + strong { + color: var(--text-color); + } + } + + @media (max-width: 480px) { + padding: 1.5rem 0.75rem; + min-height: 180px; + + .empty-icon-wrapper { + width: 70px; + height: 70px; + margin-bottom: 0.75rem; + + .empty-icon { + font-size: 2rem; + } + } + + .empty-title { + font-size: 1rem; + } + + .empty-description { + font-size: 0.8rem; + max-width: 100%; + } + } + } +} + +// ==================== Upload Zone ==================== +.upload-zone { + padding: 2rem; + text-align: center; + border: 2px dashed var(--border-color); + border-radius: 8px; + background: var(--ground-background); + transition: all 0.3s ease; + cursor: pointer; + + &:hover:not(.disabled) { + border-color: var(--primary-color); + background: color-mix( + in srgb, + var(--primary-color) 3%, + var(--ground-background) + ); + } + + &.drag-over { + border-color: var(--primary-color); + background: color-mix( + in srgb, + var(--primary-color) 8%, + var(--ground-background) + ); + + .empty-icon-wrapper { + border-color: var(--primary-color); + + .empty-icon { + color: var(--primary-color); + transform: scale(1.1); + } + } + } + + &.disabled { + cursor: not-allowed; + opacity: 0.6; + } +} + +// ==================== File Selected ==================== +.file-selected { + display: flex; + flex-direction: column; + gap: 1.5rem; + width: 100%; + max-width: 100%; + overflow: hidden; +} + +.file-info-card { + display: flex; + align-items: center; + gap: 1rem; + padding: 1rem; + border: 1px solid var(--border-color); + border-radius: 6px; + background: var(--overlay-background); + width: 100%; + max-width: 100%; + overflow: hidden; + + i { + font-size: 2rem; + color: var(--primary-color); + flex-shrink: 0; + } + + .file-details { + flex: 1; + display: flex; + flex-direction: column; + gap: 0.25rem; + min-width: 0; + overflow: hidden; + + .file-name { + font-weight: 600; + color: var(--text-color); + font-size: 0.9375rem; + word-break: break-word; + overflow-wrap: break-word; + } + + .file-meta { + font-size: 0.8125rem; + color: var(--text-secondary-color); + } + } +} + +.preview-section { + display: flex; + flex-direction: column; + gap: 0.75rem; + width: 100%; + max-width: 100%; + overflow: hidden; + + .preview-label { + display: flex; + align-items: center; + gap: 0.375rem; + font-size: 0.75rem; + font-weight: 600; + color: var(--text-secondary-color); + text-transform: uppercase; + letter-spacing: 0.025em; + + i { + font-size: 0.75rem; + color: var(--primary-color); + } + } + + .font-preview { + padding: 1.5rem; + border: 1px solid var(--border-color); + border-radius: 6px; + background: var(--overlay-background); + display: flex; + flex-direction: column; + gap: 1rem; + max-height: 300px; + overflow-y: auto; + width: 100%; + max-width: 100%; + box-sizing: border-box; + + .preview-paragraph { + color: var(--text-color); + font-size: 1rem; + line-height: 1.7; + margin: 0; + text-align: justify; + font-weight: 400; + } + + .preview-paragraph-small { + color: var(--text-color); + font-size: 0.875rem; + line-height: 1.6; + margin: 0; + text-align: justify; + font-weight: 400; + } + + .preview-characters { + display: flex; + flex-direction: column; + gap: 0.375rem; + padding-top: 0.75rem; + margin-top: 0.5rem; + border-top: 1px solid var(--border-color); + + span { + font-size: 0.75rem; + color: var(--text-secondary-color); + letter-spacing: 0.025em; + font-weight: 400; + } + } + } +} + +.setting-item { + display: flex; + flex-direction: column; + gap: 0.75rem; + padding: 0; + width: 100%; + max-width: 100%; +} + +.setting-info { + width: 100%; + + .setting-label { + display: block; + font-weight: 600; + color: var(--text-color); + font-size: 1rem; + margin-bottom: 0.5rem; + } + + .setting-description { + color: var(--text-secondary-color); + font-size: 0.875rem; + line-height: 1.5; + margin: 0; + } +} + +.setting-control { + display: flex; + flex-direction: column; + gap: 0.75rem; + width: 100%; + + .font-name-input { + width: 100%; + } +} + +// ==================== Dialog Footer ==================== +.dialog-footer { + display: flex; + gap: 0.75rem; + justify-content: flex-end; + padding: 1rem 1.5rem 1.5rem; + border-top: 1px solid var(--border-color); + width: 100%; + max-width: 100%; + box-sizing: border-box; + + @media (max-width: 768px) { + flex-direction: column; + + ::ng-deep .p-button { + width: 100%; + } + } +} diff --git a/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.ts b/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.ts new file mode 100644 index 000000000..1f26ed922 --- /dev/null +++ b/booklore-ui/src/app/features/settings/custom-fonts/font-upload-dialog/font-upload-dialog.component.ts @@ -0,0 +1,244 @@ +import {Component, ViewChild, ElementRef, OnDestroy} from '@angular/core'; +import {CommonModule} from '@angular/common'; +import {Button} from 'primeng/button'; +import {MessageService} from 'primeng/api'; +import {CustomFontService} from '../../../../shared/service/custom-font.service'; +import {formatFileSize} from '../../../../shared/model/custom-font.model'; +import {InputText} from 'primeng/inputtext'; +import {FormsModule} from '@angular/forms'; +import {DynamicDialogRef} from 'primeng/dynamicdialog'; + +@Component({ + selector: 'app-font-upload-dialog', + standalone: true, + imports: [CommonModule, Button, InputText, FormsModule], + templateUrl: './font-upload-dialog.component.html', + styleUrls: ['./font-upload-dialog.component.scss'] +}) +export class FontUploadDialogComponent implements OnDestroy { + @ViewChild('fileInput') fileInput!: ElementRef; + + isUploading = false; + uploadedFontName = ''; + selectedFile: File | null = null; + isDragOver = false; + previewFontFamily: string | null = null; + isLoadingPreview = false; + currentPreviewToken: number | null = null; + + readonly maxFileSize = 5242880; + readonly maxFonts = 10; + readonly acceptedFormats = ['.ttf', '.otf', '.woff', '.woff2']; + + constructor( + private customFontService: CustomFontService, + private messageService: MessageService, + private dialogRef: DynamicDialogRef + ) {} + + onUploadZoneClick(): void { + if (this.isUploading) { + return; + } + this.fileInput.nativeElement.click(); + } + + onFileInputChange(event: Event): void { + const input = event.target as HTMLInputElement; + const file = input.files?.[0]; + + if (!file) return; + + if (!this.validateFile(file)) { + input.value = ''; + return; + } + + this.processFile(file); + input.value = ''; + } + + async loadFontPreview(file: File): Promise { + this.cleanupPreviewFont(); + + const previewToken = Date.now(); + this.currentPreviewToken = previewToken; + + if (this.isLoadingPreview) { + console.log('Cancelling previous preview load'); + } + + this.isLoadingPreview = true; + + try { + const previewFontName = `preview-font-${previewToken}`; + const arrayBuffer = await file.arrayBuffer(); + + if (this.currentPreviewToken !== previewToken) { + console.log('Preview operation cancelled - newer preview started'); + return; + } + + const fontFace = new FontFace(previewFontName, arrayBuffer); + await fontFace.load(); + + if (this.currentPreviewToken !== previewToken) { + console.log('Preview operation cancelled after load - newer preview started'); + document.fonts.delete(fontFace); + return; + } + + document.fonts.add(fontFace); + this.previewFontFamily = `"${previewFontName}"`; + } catch (error) { + if (this.currentPreviewToken === previewToken) { + console.error('Failed to load font preview:', error); + this.previewFontFamily = null; + this.messageService.add({ + severity: 'warn', + summary: 'Preview Failed', + detail: 'Unable to preview font, but you can still upload it' + }); + } + } finally { + if (this.currentPreviewToken === previewToken) { + this.isLoadingPreview = false; + } + } + } + + uploadFont(): void { + if (!this.selectedFile) { + this.messageService.add({ + severity: 'warn', + summary: 'No File Selected', + detail: 'Please select a font file to upload' + }); + return; + } + + this.isUploading = true; + this.customFontService.uploadFont(this.selectedFile, this.uploadedFontName || undefined).subscribe({ + next: (font) => { + this.messageService.add({ + severity: 'success', + summary: 'Success', + detail: `Font "${font.fontName}" uploaded successfully` + }); + this.isUploading = false; + this.dialogRef.close(font); // Return the uploaded font + }, + error: (error) => { + console.error('Failed to upload font:', error); + let errorMessage = 'Failed to upload font'; + if (error.status === 400) { + errorMessage = 'Invalid file format or quota exceeded'; + } + this.messageService.add({ + severity: 'error', + summary: 'Upload Failed', + detail: errorMessage + }); + + this.isUploading = false; + this.selectedFile = null; + this.uploadedFontName = ''; + this.cleanupPreviewFont(); + } + }); + } + + formatFileSize(bytes: number): string { + return formatFileSize(bytes); + } + + cancel(): void { + this.cleanupPreviewFont(); + this.dialogRef.close(null); + } + + onDragOver(event: DragEvent): void { + event.preventDefault(); + event.stopPropagation(); + this.isDragOver = true; + } + + onDragLeave(event: DragEvent): void { + event.preventDefault(); + event.stopPropagation(); + this.isDragOver = false; + } + + onDrop(event: DragEvent): void { + event.preventDefault(); + event.stopPropagation(); + this.isDragOver = false; + + const files = event.dataTransfer?.files; + if (files && files.length > 0) { + const file = files[0]; + + if (!this.validateFile(file)) { + return; + } + + this.processFile(file); + } + } + + private validateFile(file: File): boolean { + const fileName = file.name.toLowerCase(); + const isValidFormat = this.acceptedFormats.some(format => fileName.endsWith(format)); + + if (!isValidFormat) { + this.messageService.add({ + severity: 'error', + summary: 'Invalid File Type', + detail: 'Please upload a TTF, OTF, WOFF, or WOFF2 font file' + }); + return false; + } + + if (file.size > this.maxFileSize) { + this.messageService.add({ + severity: 'error', + summary: 'File Too Large', + detail: `File size must not exceed ${this.formatFileSize(this.maxFileSize)}` + }); + return false; + } + + return true; + } + + private processFile(file: File): void { + this.selectedFile = file; + this.uploadedFontName = file.name.replace(/\.[^/.]+$/, ''); + this.loadFontPreview(file); + } + + cleanupPreviewFont(): void { + if (this.previewFontFamily) { + const fontName = this.previewFontFamily.replace(/"/g, ''); + + try { + for (const font of document.fonts) { + if (font.family === fontName) { + document.fonts.delete(font); + } + } + } catch (error) { + console.error('Failed to cleanup preview font:', fontName, error); + } + + this.previewFontFamily = null; + } + + this.currentPreviewToken = null; + this.isLoadingPreview = false; + } + + ngOnDestroy(): void { + this.cleanupPreviewFont(); + } +} diff --git a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.html b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.html index 5778b2cc1..ecf42ef2b 100644 --- a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.html +++ b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.html @@ -37,13 +37,22 @@ type="button" class="option-button font-button" [class.selected]="selectedFont === font.key" + [class.separator]="font.key === 'separator'" [attr.data-font]="font.key" + [disabled]="font.key === 'separator'" (click)="selectedFont = font.key" [pTooltip]="font.name" tooltipPosition="bottom"> - {{ font.displayName }} + + {{ font.displayName }} + } + + @if (!customFontsReady) { + + }

diff --git a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.scss b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.scss index 3f0c50fe0..e88e7ea3a 100644 --- a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.scss +++ b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.scss @@ -194,6 +194,28 @@ &[data-font="monospace"] .option-text { font-family: 'Courier New', monospace; } + + // Custom font buttons use the loaded font + &[data-font^="custom:"] .option-text { + font-size: 0.875rem; + } + } + + &.separator { + cursor: default; + pointer-events: none; + opacity: 0.6; + background: transparent; + border-color: transparent; + font-weight: 600; + color: var(--p-text-muted-color); + min-width: auto; + padding: 0.25rem 0.5rem; + + &:hover { + transform: none; + box-shadow: none; + } } } } diff --git a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts index 879e91839..3ad81b94d 100644 --- a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts +++ b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts @@ -1,27 +1,37 @@ -import {Component, inject, Input} from '@angular/core'; +import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core'; import {Button} from 'primeng/button'; import {FormsModule} from '@angular/forms'; import {ReaderPreferencesService} from '../reader-preferences-service'; import {UserSettings} from '../../user-management/user.service'; import {Tooltip} from 'primeng/tooltip'; +import {CustomFontService} from '../../../../shared/service/custom-font.service'; +import {CustomFont} from '../../../../shared/model/custom-font.model'; +import {skip, Subject, takeUntil} from 'rxjs'; +import {addCustomFontsToDropdown} from '../../../../shared/util/custom-font.util'; +import {Skeleton} from 'primeng/skeleton'; @Component({ selector: 'app-epub-reader-preferences-component', imports: [ Button, FormsModule, - Tooltip + Tooltip, + Skeleton ], templateUrl: './epub-reader-preferences-component.html', styleUrl: './epub-reader-preferences-component.scss' }) -export class EpubReaderPreferencesComponent { +export class EpubReaderPreferencesComponent implements OnInit, OnDestroy { @Input() userSettings!: UserSettings; private readonly readerPreferencesService = inject(ReaderPreferencesService); + private readonly customFontService = inject(CustomFontService); + private readonly destroy$ = new Subject(); - readonly fonts = [ + customFonts: CustomFont[] = []; + + fonts = [ {name: 'Book Default', displayName: 'Default', key: null}, {name: 'Serif', displayName: 'Aa', key: 'serif'}, {name: 'Sans Serif', displayName: 'Aa', key: 'sans-serif'}, @@ -58,6 +68,81 @@ export class EpubReaderPreferencesComponent { {name: 'Dark Brown', key: 'dark-brown', color: '#3E2723'} ]; + customFontsReady = false; + + ngOnInit(): void { + this.subscribeToFontUpdates(); + + this.customFontService.getUserFonts().subscribe({ + next: () => { + this.customFontsReady = true; + }, + error: (err) => { + console.error('Failed to load custom fonts:', err); + this.customFontsReady = true; + } + }); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } + + private subscribeToFontUpdates(): void { + this.customFontService.fonts$ + .pipe( + skip(1), + takeUntil(this.destroy$) + ) + .subscribe(async fonts => { + try { + const selectedFontDeleted = this.isCurrentlySelectedFontDeleted(fonts); + + if (this.hasCustomFontsChanged(fonts)) { + this.customFonts = fonts; + await this.customFontService.loadAllFonts(fonts); + this.updateFontsDropdown(fonts); + } + + if (selectedFontDeleted) { + this.resetToDefaultFont(); + } + } catch (err) { + console.error('Failed to process custom fonts:', err); + } + }); + } + + private hasCustomFontsChanged(newFonts: CustomFont[]): boolean { + if (newFonts.length !== this.customFonts.length) { + return true; + } + const newIds = new Set(newFonts.map(f => f.id)); + const currentIds = new Set(this.customFonts.map(f => f.id)); + return newFonts.some(f => !currentIds.has(f.id)) || this.customFonts.some(f => !newIds.has(f.id)); + } + + private updateFontsDropdown(fonts: CustomFont[]): void { + this.fonts = this.fonts.filter(font => !font.key || !font.key.startsWith('custom:')); + addCustomFontsToDropdown(fonts, this.fonts, 'preference'); + } + + private isCurrentlySelectedFontDeleted(newFonts: CustomFont[]): boolean { + const customFontId = this.userSettings.epubReaderSetting.customFontId; + if (!customFontId) { + return false; + } + + const fontStillExists = newFonts.some(font => font.id === customFontId); + return !fontStillExists; + } + + private resetToDefaultFont(): void { + console.log('Selected custom font was deleted, resetting to default font'); + this.selectedFont = null; + } + get selectedTheme(): string | null { return this.userSettings.epubReaderSetting.theme; } @@ -70,14 +155,40 @@ export class EpubReaderPreferencesComponent { } get selectedFont(): string | null { + // If customFontId is set, return the custom font key + if (this.userSettings.epubReaderSetting.customFontId) { + return `custom:${this.userSettings.epubReaderSetting.customFontId}`; + } return this.userSettings.epubReaderSetting.font; } set selectedFont(value: string | null) { - if (typeof value === "string") { + // Handle custom fonts + if (value && value.startsWith('custom:')) { + const fontIdStr = value.split(':')[1]; + const fontId = parseInt(fontIdStr, 10); + + if (isNaN(fontId)) { + console.error('Invalid custom font ID:', value); + return; + } + + // Update both fields in local state + this.userSettings.epubReaderSetting.customFontId = fontId; this.userSettings.epubReaderSetting.font = value; + } else { + // Clear customFontId and set font in local state + this.userSettings.epubReaderSetting.customFontId = null; + if (typeof value === "string") { + this.userSettings.epubReaderSetting.font = value; + } else { + // value is null - set to default font + this.userSettings.epubReaderSetting.font = null as any; + } } - this.readerPreferencesService.updatePreference(['epubReaderSetting', 'font'], value); + + // Single API call with entire epubReaderSetting object + this.readerPreferencesService.updatePreference(['epubReaderSetting'], this.userSettings.epubReaderSetting); } get selectedFlow(): string | null { @@ -122,4 +233,13 @@ export class EpubReaderPreferencesComponent { this.fontSize -= 10; } } + + getCustomFontName(fontKey: string): string | null { + if (!fontKey || !fontKey.startsWith('custom:')) { + return null; + } + const fontId = parseInt(fontKey.split(':')[1]); + const customFont = this.customFonts.find(f => f.id === fontId); + return customFont ? customFont.fontName : null; + } } diff --git a/booklore-ui/src/app/features/settings/settings.component.html b/booklore-ui/src/app/features/settings/settings.component.html index 1e854b04f..aa0a7b675 100644 --- a/booklore-ui/src/app/features/settings/settings.component.html +++ b/booklore-ui/src/app/features/settings/settings.component.html @@ -6,6 +6,9 @@ Reader + + Custom Fonts + View @@ -56,6 +59,9 @@ + + + diff --git a/booklore-ui/src/app/features/settings/settings.component.ts b/booklore-ui/src/app/features/settings/settings.component.ts index ee34ca5f7..f6b1cc840 100644 --- a/booklore-ui/src/app/features/settings/settings.component.ts +++ b/booklore-ui/src/app/features/settings/settings.component.ts @@ -17,9 +17,11 @@ import {DeviceSettingsComponent} from './device-settings/device-settings-compone import {LibraryMetadataSettingsComponent} from './library-metadata-settings/library-metadata-settings.component'; import { PageTitleService } from "../../shared/service/page-title.service"; import {EmailV2Component} from './email-v2/email-v2.component'; +import {CustomFontsComponent} from './custom-fonts/custom-fonts.component'; export enum SettingsTab { ReaderSettings = 'reader', + CustomFonts = 'custom-fonts', ViewPreferences = 'view', DeviceSettings = 'device', UserManagement = 'user', @@ -47,6 +49,7 @@ export enum SettingsTab { AuthenticationSettingsComponent, ViewPreferencesParentComponent, ReaderPreferences, + CustomFontsComponent, MetadataSettingsComponent, DeviceSettingsComponent, FileNamingPatternComponent, diff --git a/booklore-ui/src/app/features/settings/user-management/user.service.ts b/booklore-ui/src/app/features/settings/user-management/user.service.ts index e8d31124a..2f88383af 100644 --- a/booklore-ui/src/app/features/settings/user-management/user.service.ts +++ b/booklore-ui/src/app/features/settings/user-management/user.service.ts @@ -105,6 +105,7 @@ export interface EpubReaderSetting { lineHeight: number; margin: number; letterSpacing: number; + customFontId?: number | null; } export interface CbxReaderSetting { diff --git a/booklore-ui/src/app/shared/model/custom-font.model.ts b/booklore-ui/src/app/shared/model/custom-font.model.ts new file mode 100644 index 000000000..27d56ac2a --- /dev/null +++ b/booklore-ui/src/app/shared/model/custom-font.model.ts @@ -0,0 +1,23 @@ +export interface CustomFont { + id: number; + fontName: string; + originalFileName: string; + format: FontFormat; + fileSize: number; + uploadedAt: string; +} + +export enum FontFormat { + TTF = 'TTF', + OTF = 'OTF', + WOFF = 'WOFF', + WOFF2 = 'WOFF2' +} + +export function formatFileSize(bytes: number): string { + if (bytes === 0) return '0 Bytes'; + const k = 1024; + const sizes = ['Bytes', 'KB', 'MB']; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]; +} diff --git a/booklore-ui/src/app/shared/service/custom-font.service.ts b/booklore-ui/src/app/shared/service/custom-font.service.ts new file mode 100644 index 000000000..c3fcca505 --- /dev/null +++ b/booklore-ui/src/app/shared/service/custom-font.service.ts @@ -0,0 +1,122 @@ +import {Injectable, inject} from '@angular/core'; +import {HttpClient} from '@angular/common/http'; +import {BehaviorSubject, Observable, tap} from 'rxjs'; +import {CustomFont} from '../model/custom-font.model'; +import {API_CONFIG} from '../../core/config/api-config'; +import {AuthService} from './auth.service'; + +@Injectable({ + providedIn: 'root' +}) +export class CustomFontService { + private apiUrl = `${API_CONFIG.BASE_URL}/api/v1/custom-fonts`; + private fontsSubject = new BehaviorSubject([]); + public fonts$ = this.fontsSubject.asObservable(); + private loadedFonts = new Set(); + private authService = inject(AuthService); + + constructor(private http: HttpClient) {} + + uploadFont(file: File, fontName?: string): Observable { + const formData = new FormData(); + formData.append('file', file); + if (fontName) { + formData.append('fontName', fontName); + } + + return this.http.post(`${this.apiUrl}/upload`, formData).pipe( + tap(font => { + // Add to cache + const currentFonts = this.fontsSubject.value; + this.fontsSubject.next([...currentFonts, font]); + // Load the font immediately + this.loadFontFace(font).catch(err => { + console.error('Failed to load font after upload:', err); + }); + }) + ); + } + + getUserFonts(): Observable { + return this.http.get(this.apiUrl).pipe( + tap(fonts => { + this.fontsSubject.next(fonts); + }) + ); + } + + deleteFont(fontId: number): Observable { + return this.http.delete(`${this.apiUrl}/${fontId}`).pipe( + tap(() => { + // Remove from cache + const currentFonts = this.fontsSubject.value; + const updatedFonts = currentFonts.filter(f => f.id !== fontId); + this.fontsSubject.next(updatedFonts); + + // Remove from loaded fonts set and document.fonts + const deletedFont = currentFonts.find(f => f.id === fontId); + if (deletedFont) { + this.removeFontFace(deletedFont.fontName); + this.loadedFonts.delete(deletedFont.fontName); + } + }) + ); + } + + getFontUrl(fontId: number): string { + return `${this.apiUrl}/${fontId}/file`; + } + + private getToken(): string | null { + return this.authService.getOidcAccessToken() || this.authService.getInternalAccessToken(); + } + + public appendToken(url: string): string { + const token = this.getToken(); + return token ? `${url}${url.includes('?') ? '&' : '?'}token=${token}` : url; + } + + async loadFontFace(font: CustomFont): Promise { + if (this.loadedFonts.has(font.fontName)) { + return; + } + + try { + const absoluteFontUrl = this.getFontUrl(font.id); + const fontUrlWithToken = this.appendToken(absoluteFontUrl); + + const fontFace = new FontFace( + font.fontName, + `url(${fontUrlWithToken})`, + { + weight: 'normal', + style: 'normal' + } + ); + + await fontFace.load(); + document.fonts.add(fontFace); + this.loadedFonts.add(font.fontName); + } catch (error) { + console.error(`Failed to load font ${font.fontName}:`, error); + throw error; + } + } + + async loadAllFonts(fonts: CustomFont[]): Promise { + const loadPromises = fonts.map(font => this.loadFontFace(font)); + await Promise.allSettled(loadPromises); + } + + isFontLoaded(fontName: string): boolean { + return this.loadedFonts.has(fontName); + } + + private removeFontFace(fontName: string): void { + for (const font of document.fonts) { + if (font.family === fontName) { + document.fonts.delete(font); + } + } + } +} diff --git a/booklore-ui/src/app/shared/util/custom-font.util.ts b/booklore-ui/src/app/shared/util/custom-font.util.ts new file mode 100644 index 000000000..396c96351 --- /dev/null +++ b/booklore-ui/src/app/shared/util/custom-font.util.ts @@ -0,0 +1,74 @@ +import { CustomFont } from '../model/custom-font.model'; + +/** + * Font dropdown item for epub-reader component (PrimeNG Select format) + */ +export interface FontDropdownItem { + label: string; + value: string | null; + disabled?: boolean; +} + +/** + * Font dropdown item for epub-reader-preferences component + */ +export interface FontPreferenceItem { + name: string; + displayName: string; + key: string | null; +} + +const MAX_FONT_DISPLAY_LENGTH = 12; + +/** + * Adds custom fonts to a dropdown array with a separator. + * Removes any existing separator before adding to prevent duplicates. + */ +export function addCustomFontsToDropdown( + fonts: CustomFont[], + targetArray: T[], + format: 'select' | 'preference' +): void { + if (fonts.length === 0) { + return; + } + + if (format === 'select') { + const separatorIndex = (targetArray as FontDropdownItem[]).findIndex(item => item.value === 'separator'); + if (separatorIndex !== -1) { + targetArray.splice(separatorIndex, 1); + } + + (targetArray as FontDropdownItem[]).push({ + label: '--- Custom Fonts ---', + value: 'separator', + disabled: true + }); + + fonts.forEach(font => { + (targetArray as FontDropdownItem[]).push({ + label: font.fontName, + value: `custom:${font.id}` + }); + }); + } else { + const separatorIndex = (targetArray as FontPreferenceItem[]).findIndex(item => item.key === 'separator'); + if (separatorIndex !== -1) { + targetArray.splice(separatorIndex, 1); + } + + (targetArray as FontPreferenceItem[]).push({ + name: '--- Custom Fonts ---', + displayName: '---', + key: 'separator' + }); + + fonts.forEach(font => { + (targetArray as FontPreferenceItem[]).push({ + name: font.fontName, + displayName: font.fontName.substring(0, MAX_FONT_DISPLAY_LENGTH), + key: `custom:${font.id}` + }); + }); + } +} From 24862ed62b94bbe2146c985d99325bbbe1fe9fc9 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Mon, 5 Jan 2026 15:25:48 -0700 Subject: [PATCH 11/40] Move custom fonts management to Reader tab (#2161) Co-authored-by: acx10 --- .../custom-fonts/custom-fonts.component.html | 156 ++++++++---------- .../custom-fonts/custom-fonts.component.scss | 9 +- .../epub-reader-preferences-component.ts | 10 +- .../reader-preferences.component.html | 15 ++ .../reader-preferences.component.ts | 3 +- .../features/settings/settings.component.html | 6 - .../features/settings/settings.component.ts | 5 +- .../src/app/shared/util/custom-font.util.ts | 14 +- 8 files changed, 97 insertions(+), 121 deletions(-) diff --git a/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.html b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.html index 78c8594fe..9ffc6615c 100644 --- a/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.html +++ b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.html @@ -1,24 +1,4 @@ -

-
-
-
-

- - Custom Fonts -

-

- Upload and manage your own fonts for a personalized reading experience in the EPUB reader. - You have {{ customFonts.length }} of {{ maxFonts }} custom fonts. -

-
- -
-
+
@@ -42,81 +22,85 @@ } @else {
-

- - Your Font Library - ({{ customFonts.length }}) -

-

- Manage your uploaded custom fonts. Each font can be selected in the EPUB reader settings. -

+
+

+ Your Font Library + ({{ customFonts.length }}) +

+
+
@for (font of customFonts; track font.id) { -
-
-
-

{{ font.fontName }}

- {{ font.format }} -
- +
+
+
+

{{ font.fontName }}

+ {{ font.format }}
+ +
-
- - @if (!fontsLoadedInBrowser) { -
- - - - - - +
+ + @if (!fontsLoadedInBrowser) { +
+ + + + + + +
+ } @else { +
+

+ Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. +

+

+ Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. +

+
+ ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789
- } @else { -
-

- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. -

-

- Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. -

-
- ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 0123456789 -
-
- } +
+ } +
+ + + }
} diff --git a/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.scss b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.scss index 76b6a3e0e..f29abeffb 100644 --- a/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.scss +++ b/booklore-ui/src/app/features/settings/custom-fonts/custom-fonts.component.scss @@ -65,13 +65,10 @@ gap: 2rem; } -.preferences-section { - @media (min-width: 768px) { - padding: 0 1rem; - } -} - .section-header { + display: flex; + align-items: flex-end; + justify-content: space-between; margin-bottom: 1rem; } diff --git a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts index 3ad81b94d..3821d3815 100644 --- a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts +++ b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts @@ -33,11 +33,11 @@ export class EpubReaderPreferencesComponent implements OnInit, OnDestroy { fonts = [ {name: 'Book Default', displayName: 'Default', key: null}, - {name: 'Serif', displayName: 'Aa', key: 'serif'}, - {name: 'Sans Serif', displayName: 'Aa', key: 'sans-serif'}, - {name: 'Roboto', displayName: 'Aa', key: 'roboto'}, - {name: 'Cursive', displayName: 'Aa', key: 'cursive'}, - {name: 'Monospace', displayName: 'Aa', key: 'monospace'} + {name: 'Serif', displayName: 'Serif', key: 'serif'}, + {name: 'Sans Serif', displayName: 'Sans Serif', key: 'sans-serif'}, + {name: 'Roboto', displayName: 'Roboto', key: 'roboto'}, + {name: 'Cursive', displayName: 'Cursive', key: 'cursive'}, + {name: 'Monospace', displayName: 'Monospace', key: 'monospace'} ]; readonly flowOptions = [ diff --git a/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.component.html b/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.component.html index 252213a3b..11eed713d 100644 --- a/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.component.html +++ b/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.component.html @@ -152,5 +152,20 @@
+ +
+
+

+ + Custom Fonts Management +

+

+ Upload and manage up to 10 custom fonts for a personalized reading experience in the EPUB reader. Each font can then be selected in the EPUB reader settings. +

+
+
+ +
+
diff --git a/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.component.ts b/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.component.ts index fdc619ec4..a7e163c2f 100644 --- a/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.component.ts +++ b/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.component.ts @@ -9,13 +9,14 @@ import {ReaderPreferencesService} from './reader-preferences-service'; import {EpubReaderPreferencesComponent} from './epub-reader-preferences/epub-reader-preferences-component'; import {PdfReaderPreferencesComponent} from './pdf-reader-preferences/pdf-reader-preferences-component'; import {CbxReaderPreferencesComponent} from './cbx-reader-preferences/cbx-reader-preferences-component'; +import {CustomFontsComponent} from '../custom-fonts/custom-fonts.component'; @Component({ selector: 'app-reader-preferences', templateUrl: './reader-preferences.component.html', standalone: true, styleUrls: ['./reader-preferences.component.scss'], - imports: [FormsModule, TooltipModule, EpubReaderPreferencesComponent, PdfReaderPreferencesComponent, CbxReaderPreferencesComponent] + imports: [FormsModule, TooltipModule, EpubReaderPreferencesComponent, PdfReaderPreferencesComponent, CbxReaderPreferencesComponent, CustomFontsComponent] }) export class ReaderPreferences implements OnInit, OnDestroy { readonly scopeOptions = [ diff --git a/booklore-ui/src/app/features/settings/settings.component.html b/booklore-ui/src/app/features/settings/settings.component.html index aa0a7b675..1e854b04f 100644 --- a/booklore-ui/src/app/features/settings/settings.component.html +++ b/booklore-ui/src/app/features/settings/settings.component.html @@ -6,9 +6,6 @@ Reader - - Custom Fonts - View @@ -59,9 +56,6 @@ - - - diff --git a/booklore-ui/src/app/features/settings/settings.component.ts b/booklore-ui/src/app/features/settings/settings.component.ts index f6b1cc840..22d1864ff 100644 --- a/booklore-ui/src/app/features/settings/settings.component.ts +++ b/booklore-ui/src/app/features/settings/settings.component.ts @@ -15,13 +15,11 @@ import {OpdsSettings} from './opds-settings/opds-settings'; import {MetadataSettingsComponent} from './metadata-settings/metadata-settings-component'; import {DeviceSettingsComponent} from './device-settings/device-settings-component'; import {LibraryMetadataSettingsComponent} from './library-metadata-settings/library-metadata-settings.component'; -import { PageTitleService } from "../../shared/service/page-title.service"; +import {PageTitleService} from "../../shared/service/page-title.service"; import {EmailV2Component} from './email-v2/email-v2.component'; -import {CustomFontsComponent} from './custom-fonts/custom-fonts.component'; export enum SettingsTab { ReaderSettings = 'reader', - CustomFonts = 'custom-fonts', ViewPreferences = 'view', DeviceSettings = 'device', UserManagement = 'user', @@ -49,7 +47,6 @@ export enum SettingsTab { AuthenticationSettingsComponent, ViewPreferencesParentComponent, ReaderPreferences, - CustomFontsComponent, MetadataSettingsComponent, DeviceSettingsComponent, FileNamingPatternComponent, diff --git a/booklore-ui/src/app/shared/util/custom-font.util.ts b/booklore-ui/src/app/shared/util/custom-font.util.ts index 396c96351..4ac8e8867 100644 --- a/booklore-ui/src/app/shared/util/custom-font.util.ts +++ b/booklore-ui/src/app/shared/util/custom-font.util.ts @@ -1,4 +1,4 @@ -import { CustomFont } from '../model/custom-font.model'; +import {CustomFont} from '../model/custom-font.model'; /** * Font dropdown item for epub-reader component (PrimeNG Select format) @@ -39,12 +39,6 @@ export function addCustomFontsToDropdown { (targetArray as FontDropdownItem[]).push({ label: font.fontName, @@ -57,12 +51,6 @@ export function addCustomFontsToDropdown { (targetArray as FontPreferenceItem[]).push({ name: font.fontName, From e283b61e2e33dca2b04f9574e0ac0fc973877a32 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 5 Jan 2026 15:28:54 -0700 Subject: [PATCH 12/40] chore(deps): bump qs and body-parser in /booklore-ui (#2088) Bumps [qs](https://github.com/ljharb/qs) and [body-parser](https://github.com/expressjs/body-parser). These dependencies needed to be updated together. Updates `qs` from 6.14.0 to 6.14.1 - [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md) - [Commits](https://github.com/ljharb/qs/compare/v6.14.0...v6.14.1) Updates `body-parser` from 1.20.3 to 1.20.4 - [Release notes](https://github.com/expressjs/body-parser/releases) - [Changelog](https://github.com/expressjs/body-parser/blob/master/HISTORY.md) - [Commits](https://github.com/expressjs/body-parser/compare/1.20.3...1.20.4) --- updated-dependencies: - dependency-name: qs dependency-version: 6.14.1 dependency-type: indirect - dependency-name: body-parser dependency-version: 1.20.4 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- booklore-ui/package-lock.json | 254 ++++++++++------------------------ 1 file changed, 75 insertions(+), 179 deletions(-) diff --git a/booklore-ui/package-lock.json b/booklore-ui/package-lock.json index 3bba785f4..794484b3e 100644 --- a/booklore-ui/package-lock.json +++ b/booklore-ui/package-lock.json @@ -453,6 +453,7 @@ "integrity": "sha512-PYVgNbjNtuD5/QOuS6cHR8A7bRqsVqxtUUXGqdv76FYMAajQcAvyfR0QxOkqf3NmYxgNgO3hlUHWq0ILjVbcow==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@angular-eslint/bundled-angular-compiler": "21.1.0", "eslint-scope": "^9.0.0" @@ -482,6 +483,7 @@ "resolved": "https://registry.npmjs.org/@angular/animations/-/animations-21.0.5.tgz", "integrity": "sha512-7Lr60wLlYcGG+VDnnOY9xpn8Zz3yyJcWGSjNEbXPEGaaD0nTZLNZ1nIXRhTeYZwosK5GvPDFxq68kdLxczskHA==", "license": "MIT", + "peer": true, "dependencies": { "tslib": "^2.3.0" }, @@ -597,6 +599,7 @@ "resolved": "https://registry.npmjs.org/@angular/cdk/-/cdk-21.0.3.tgz", "integrity": "sha512-abfckeZfFvovdpxuQHRE4gS1VLNa05Dx0ZSKLGVL9DsQsi4pgn6wWg1y9TkXMlmtpG/EhLmCBxUc6LOHfdeWQA==", "license": "MIT", + "peer": true, "dependencies": { "parse5": "^8.0.0", "tslib": "^2.3.0" @@ -613,6 +616,7 @@ "integrity": "sha512-3lMR3J231JhLgAt37yEULSHFte3zPeta9VYpIIf92JiBsTnWrvKnaK8RXhfdiSQrvhqQ9FMQdl5AG62r1c4dbA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@angular-devkit/architect": "0.2100.3", "@angular-devkit/core": "21.0.3", @@ -648,6 +652,7 @@ "resolved": "https://registry.npmjs.org/@angular/common/-/common-21.0.5.tgz", "integrity": "sha512-/ZI11F6Wxr8TZRVO4O7pmhBJ9YxDg9mvA76e0PiivmqZggM02HY0y3XPMP3hAOe4K+PfaVBgMAu3P9t32klzfA==", "license": "MIT", + "peer": true, "dependencies": { "tslib": "^2.3.0" }, @@ -664,6 +669,7 @@ "resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-21.0.5.tgz", "integrity": "sha512-92sv9pVm9o/8KfPM7T8j5VQmTaSOqmIajrJF8evXE2dNJcwkBpVtzZUqDzr23AV3vg94C7eYU64i8qrsmJ+cYQ==", "license": "MIT", + "peer": true, "dependencies": { "tslib": "^2.3.0" }, @@ -677,6 +683,7 @@ "integrity": "sha512-45sFKqt+badXl6Ab2XsxuOsdi0BbIZgcc9TdwmFPdXMNfcSUYDcPiOA0l1iPwDIZiu4VyqzepMfnHB9IwCatgA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/core": "7.28.4", "@jridgewell/sourcemap-codec": "^1.4.14", @@ -709,6 +716,7 @@ "resolved": "https://registry.npmjs.org/@angular/core/-/core-21.0.5.tgz", "integrity": "sha512-HFXfO5YsBVM+IEaU8h3DZSxO98yDZM2v49NlSVNDzFD3fhnkpTmcgT2NKz9ulIiuV9N376itt+x+NG12sg/+Fw==", "license": "MIT", + "peer": true, "dependencies": { "tslib": "^2.3.0" }, @@ -734,6 +742,7 @@ "resolved": "https://registry.npmjs.org/@angular/forms/-/forms-21.0.5.tgz", "integrity": "sha512-RcmXs/LgKyc7D70xVT+3aK/H2SCFEyuebAiw72Iz1te1Gbql2GDFF6hgEOaNwOUglDg8ogN5MdVif2DbRLD3Hw==", "license": "MIT", + "peer": true, "dependencies": { "tslib": "^2.3.0" }, @@ -753,6 +762,7 @@ "resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-21.0.5.tgz", "integrity": "sha512-UVCrqOxFmX6kAG3Y6jqjCWvLoTP7fxeY96AsxTMp1fkBdqbQbEPleWQpwngNimsuUPvf+rA6XOxsqiDmRex5mA==", "license": "MIT", + "peer": true, "dependencies": { "tslib": "^2.3.0" }, @@ -793,6 +803,7 @@ "resolved": "https://registry.npmjs.org/@angular/router/-/router-21.0.5.tgz", "integrity": "sha512-IFmf0Wd7jSOoZ8TI+4RXMsYmnIfHQG+kGxeMQVKrefTdr3uEHW/TEsNzbW5bkCpVJHRm4EhkH4hSu8D8tUQffQ==", "license": "MIT", + "peer": true, "dependencies": { "tslib": "^2.3.0" }, @@ -892,6 +903,7 @@ "integrity": "sha512-2BCOP7TN8M+gVDj7/ht3hsaO/B/n5oDbiAyyvnRlNOs+u1o+JWNYTQrmpuNp1/Wq2gcFrI01JAW+paEKDMx/CA==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.3", @@ -1188,7 +1200,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=0.1.90" } @@ -1281,6 +1292,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" }, @@ -1324,6 +1336,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" } @@ -2335,6 +2348,7 @@ "integrity": "sha512-X7/+dG9SLpSzRkwgG5/xiIzW0oMrV3C0HOa7YHG1WnrLK+vCQHfte4k/T80059YBdei29RBC3s+pSMvPJDU9/A==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@inquirer/checkbox": "^4.3.0", "@inquirer/confirm": "^5.1.19", @@ -4549,14 +4563,14 @@ "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==", "dev": true, "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/@standard-schema/spec": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/@stomp/rx-stomp": { "version": "2.3.0", @@ -4573,7 +4587,8 @@ "version": "7.2.1", "resolved": "https://registry.npmjs.org/@stomp/stompjs/-/stompjs-7.2.1.tgz", "integrity": "sha512-DLd/WeicnHS5SsWWSk3x6/pcivqchNaEvg9UEGVqAcfYEBVmS9D6980ckXjTtfpXLjdLDsd96M7IuX4w7nzq5g==", - "license": "Apache-2.0" + "license": "Apache-2.0", + "peer": true }, "node_modules/@tailwindcss/typography": { "version": "0.5.19", @@ -4616,7 +4631,8 @@ "version": "25.0.0", "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-25.0.0.tgz", "integrity": "sha512-XKLA6syeBUaPzx4j3qwMqzzq+V4uo72BnlbOjmuljLrRqdsd3qnzvZZoxvMHZ23ndsRS4aufU6JOZYpCbU6T1A==", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/@tybys/wasm-util": { "version": "0.10.1", @@ -4647,7 +4663,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "@types/node": "*" } @@ -4742,6 +4757,7 @@ "integrity": "sha512-6/cmF2piao+f6wSxUsJLZjck7OQsYyRtcOZS02k7XINSNlz93v6emM8WutDQSXnroG2xwYlEVHJI+cPA7CPM3Q==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.50.0", "@typescript-eslint/types": "8.50.0", @@ -4849,6 +4865,7 @@ "integrity": "sha512-iX1mgmGrXdANhhITbpp2QQM2fGehBse9LbTf0sidWK6yg/NE+uhV5dfU1g6EYPlcReYmkE9QLPq/2irKAmtS9w==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, @@ -4891,6 +4908,7 @@ "integrity": "sha512-87KgUXET09CRjGCi2Ejxy3PULXna63/bMYv72tCAlDJC3Yqwln0HiFJ3VJMst2+mEtNtZu5oFvX4qJGjKsnAgg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.7.0", "@typescript-eslint/scope-manager": "8.50.0", @@ -5163,6 +5181,7 @@ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "dev": true, "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -5477,7 +5496,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": "^4.5.0 || >= 5.9" } @@ -5608,6 +5626,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -5829,6 +5848,7 @@ "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz", "integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==", "license": "MIT", + "peer": true, "dependencies": { "@kurkle/color": "^0.3.0" }, @@ -6049,7 +6069,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "debug": "2.6.9", "finalhandler": "1.1.2", @@ -6067,7 +6086,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "ms": "2.0.0" } @@ -6079,7 +6097,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">= 0.8" } @@ -6091,7 +6108,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "debug": "2.6.9", "encodeurl": "~1.0.2", @@ -6111,8 +6127,7 @@ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true, "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/connect/node_modules/on-finished": { "version": "2.3.0", @@ -6121,7 +6136,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "ee-first": "1.1.1" }, @@ -6136,7 +6150,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">= 0.6" } @@ -6326,8 +6339,7 @@ "integrity": "sha512-GAj5FOq0Hd+RsCGVJxZuKaIDXDf3h6GQoNEjFgbLLI/trgtavwUbSnZ5pVfg27DVCaWjIohryS0JFwIJyT2cMg==", "dev": true, "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/d": { "version": "1.0.2", @@ -6373,7 +6385,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=4.0" } @@ -6427,7 +6438,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">= 0.8", "npm": "1.2.8000 || >= 1.4.16" @@ -6450,8 +6460,7 @@ "integrity": "sha512-uJaamHkagcZtHPqCIHZxnFrXlunQXgBOsZSUOWwFw31QJCAbyTBoHMW75YOTur5ZNx8pIeAKgf6GWIgaqqiLhA==", "dev": true, "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/didyoumean": { "version": "1.2.2", @@ -6472,7 +6481,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "custom-event": "~1.0.0", "ent": "~2.2.0", @@ -6617,7 +6625,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "@types/cors": "^2.8.12", "@types/node": ">=10.0.0", @@ -6640,7 +6647,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=10.0.0" } @@ -6652,7 +6658,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" @@ -6668,7 +6673,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -6688,7 +6692,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">= 0.6" } @@ -6700,7 +6703,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "mime-db": "1.52.0" }, @@ -6715,7 +6717,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">= 0.6" } @@ -6727,7 +6728,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=10.0.0" }, @@ -6751,7 +6751,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", @@ -6980,6 +6979,7 @@ "integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -7280,8 +7280,7 @@ "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", "dev": true, "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/eventsource": { "version": "3.0.7", @@ -7329,6 +7328,7 @@ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", @@ -7398,8 +7398,7 @@ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "dev": true, "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/fast-deep-equal": { "version": "3.1.3", @@ -7597,7 +7596,6 @@ ], "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=4.0" }, @@ -7648,7 +7646,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", @@ -7677,8 +7674,7 @@ "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", "dev": true, "license": "ISC", - "optional": true, - "peer": true + "optional": true }, "node_modules/fsevents": { "version": "2.3.3", @@ -7783,7 +7779,6 @@ "dev": true, "license": "ISC", "optional": true, - "peer": true, "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -7825,7 +7820,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -7838,7 +7832,6 @@ "dev": true, "license": "ISC", "optional": true, - "peer": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -7909,7 +7902,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "has-symbols": "^1.0.3" }, @@ -8043,7 +8035,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "eventemitter3": "^4.0.0", "follow-redirects": "^1.0.0", @@ -8185,7 +8176,6 @@ "dev": true, "license": "ISC", "optional": true, - "peer": true, "dependencies": { "once": "^1.3.0", "wrappy": "1" @@ -8334,7 +8324,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "call-bound": "^1.0.2", "gopd": "^1.2.0", @@ -8374,7 +8363,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">= 8.0.0" }, @@ -8503,6 +8491,7 @@ "integrity": "sha512-mjzqwWRD9Y1J1KUi7W97Gja1bwOOM5Ug0EZ6UDK3xS7j7mndrkwozHtSblfomlzyB4NepioNt+B2sOSzczVgtQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@acemir/cssom": "^0.9.28", "@asamuzakjp/dom-selector": "^6.7.6", @@ -8608,7 +8597,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "optionalDependencies": { "graceful-fs": "^4.1.6" } @@ -8651,7 +8639,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "@colors/colors": "1.5.0", "body-parser": "^1.19.0", @@ -8692,32 +8679,30 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=8" } }, "node_modules/karma/node_modules/body-parser": { - "version": "1.20.3", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", - "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "version": "1.20.4", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", + "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==", "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { - "bytes": "3.1.2", + "bytes": "~3.1.2", "content-type": "~1.0.5", "debug": "2.6.9", "depd": "2.0.0", - "destroy": "1.2.0", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "on-finished": "2.4.1", - "qs": "6.13.0", - "raw-body": "2.5.2", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.14.0", + "raw-body": "~2.5.3", "type-is": "~1.6.18", - "unpipe": "1.0.0" + "unpipe": "~1.0.0" }, "engines": { "node": ">= 0.8", @@ -8731,7 +8716,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -8744,7 +8728,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", @@ -8771,7 +8754,6 @@ "dev": true, "license": "ISC", "optional": true, - "peer": true, "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", @@ -8785,7 +8767,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "ms": "2.0.0" } @@ -8796,8 +8777,7 @@ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "dev": true, "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/karma/node_modules/glob-parent": { "version": "5.1.2", @@ -8806,7 +8786,6 @@ "dev": true, "license": "ISC", "optional": true, - "peer": true, "dependencies": { "is-glob": "^4.0.1" }, @@ -8814,25 +8793,6 @@ "node": ">= 6" } }, - "node_modules/karma/node_modules/http-errors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", - "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "depd": "2.0.0", - "inherits": "2.0.4", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "toidentifier": "1.0.1" - }, - "engines": { - "node": ">= 0.8" - } - }, "node_modules/karma/node_modules/iconv-lite": { "version": "0.4.24", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", @@ -8840,7 +8800,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "safer-buffer": ">= 2.1.2 < 3" }, @@ -8855,7 +8814,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=8" } @@ -8867,7 +8825,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">= 0.6" } @@ -8879,7 +8836,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">= 0.6" } @@ -8891,7 +8847,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "mime-db": "1.52.0" }, @@ -8906,7 +8861,6 @@ "dev": true, "license": "ISC", "optional": true, - "peer": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -8920,8 +8874,7 @@ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true, "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/karma/node_modules/picomatch": { "version": "2.3.1", @@ -8930,7 +8883,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=8.6" }, @@ -8938,37 +8890,18 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, - "node_modules/karma/node_modules/qs": { - "version": "6.13.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", - "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", - "dev": true, - "license": "BSD-3-Clause", - "optional": true, - "peer": true, - "dependencies": { - "side-channel": "^1.0.6" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/karma/node_modules/raw-body": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", - "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { - "bytes": "3.1.2", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "unpipe": "1.0.0" + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" }, "engines": { "node": ">= 0.8" @@ -8981,7 +8914,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "picomatch": "^2.2.1" }, @@ -8996,23 +8928,10 @@ "dev": true, "license": "BSD-3-Clause", "optional": true, - "peer": true, "engines": { "node": ">=0.10.0" } }, - "node_modules/karma/node_modules/statuses": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", - "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", - "dev": true, - "license": "MIT", - "optional": true, - "peer": true, - "engines": { - "node": ">= 0.8" - } - }, "node_modules/karma/node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", @@ -9020,7 +8939,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -9037,7 +8955,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "ansi-regex": "^5.0.1" }, @@ -9052,7 +8969,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "media-typer": "0.3.0", "mime-types": "~2.1.24" @@ -9068,7 +8984,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", @@ -9088,7 +9003,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "cliui": "^7.0.2", "escalade": "^3.1.1", @@ -9109,7 +9023,6 @@ "dev": true, "license": "ISC", "optional": true, - "peer": true, "engines": { "node": ">=10" } @@ -9171,6 +9084,7 @@ "integrity": "sha512-ME4Fb83LgEgwNw96RKNvKV4VTLuXfoKudAmm2lP8Kk87KaMK0/Xrx/aAkMWmT8mDb+3MlFDspfbCs7adjRxA2g==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "cli-truncate": "^5.0.0", "colorette": "^2.0.20", @@ -9390,7 +9304,6 @@ "dev": true, "license": "Apache-2.0", "optional": true, - "peer": true, "dependencies": { "date-format": "^4.0.14", "debug": "^4.3.4", @@ -9583,7 +9496,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "bin": { "mime": "cli.js" }, @@ -9654,7 +9566,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -9819,7 +9730,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "minimist": "^1.2.6" }, @@ -10615,7 +10525,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=0.10.0" } @@ -10765,6 +10674,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", @@ -11011,8 +10921,7 @@ "integrity": "sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ==", "dev": true, "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/qjobs": { "version": "1.2.0", @@ -11021,15 +10930,14 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=0.9" } }, "node_modules/qs": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", - "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", + "version": "6.14.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz", + "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==", "dev": true, "license": "BSD-3-Clause", "dependencies": { @@ -11175,7 +11083,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=0.10.0" } @@ -11196,8 +11103,7 @@ "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", "dev": true, "license": "MIT", - "optional": true, - "peer": true + "optional": true }, "node_modules/resolve": { "version": "1.22.11", @@ -11281,7 +11187,6 @@ "dev": true, "license": "ISC", "optional": true, - "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -11412,6 +11317,7 @@ "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", "license": "Apache-2.0", + "peer": true, "dependencies": { "tslib": "^2.1.0" } @@ -11429,7 +11335,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", @@ -11757,7 +11662,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "accepts": "~1.3.4", "base64id": "~2.0.0", @@ -11778,7 +11682,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "debug": "~4.3.4", "ws": "~8.17.1" @@ -11791,7 +11694,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -11811,7 +11713,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=10.0.0" }, @@ -11835,7 +11736,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "@socket.io/component-emitter": "~3.1.0", "debug": "~4.3.1" @@ -11851,7 +11751,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -11871,7 +11770,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" @@ -11887,7 +11785,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -11907,7 +11804,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">= 0.6" } @@ -11919,7 +11815,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "mime-db": "1.52.0" }, @@ -11934,7 +11829,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">= 0.6" } @@ -12102,7 +11996,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "dependencies": { "date-format": "^4.0.14", "debug": "^4.3.4", @@ -12236,6 +12129,7 @@ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.18.tgz", "integrity": "sha512-6A2rnmW5xZMdw11LYjhcI5846rt9pbLSabY5XPxo+XWdxwZaFEn47Go4NzFiHu9sNNmr/kXivP1vStfvMaK1GQ==", "license": "MIT", + "peer": true, "dependencies": { "@alloc/quick-lru": "^5.2.0", "arg": "^5.0.2", @@ -12477,7 +12371,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=14.14" } @@ -12563,7 +12456,8 @@ "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "license": "0BSD" + "license": "0BSD", + "peer": true }, "node_modules/tuf-js": { "version": "4.0.0", @@ -12620,6 +12514,7 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -12634,6 +12529,7 @@ "integrity": "sha512-Q1/6yNUmCpH94fbgMUMg2/BSAr/6U7GBk61kZTv1/asghQOWOjTlp9K8mixS5NcJmm2creY+UFfGeW/+OcA64A==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@typescript-eslint/eslint-plugin": "8.50.0", "@typescript-eslint/parser": "8.50.0", @@ -12673,7 +12569,6 @@ ], "license": "MIT", "optional": true, - "peer": true, "bin": { "ua-parser-js": "script/cli.js" }, @@ -12731,7 +12626,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">= 4.0.0" } @@ -12810,7 +12704,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">= 0.4.0" } @@ -12866,6 +12759,7 @@ "integrity": "sha512-BxAKBWmIbrDgrokdGZH1IgkIk/5mMHDreLDmCJ0qpyJaAteP8NvMhkwr/ZCQNqNH97bw/dANTE9PDzqwJghfMQ==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.5.0", @@ -13425,6 +13319,7 @@ "integrity": "sha512-E4t7DJ9pESL6E3I8nFjPa4xGUd3PmiWDLsDztS2qXSJWfHtbQnwAWylaBvSNY48I3vr8PTqIZlyK8TE3V3CA4Q==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@vitest/expect": "4.0.16", "@vitest/mocker": "4.0.16", @@ -13514,7 +13409,6 @@ "dev": true, "license": "MIT", "optional": true, - "peer": true, "engines": { "node": ">=0.10.0" } @@ -13836,6 +13730,7 @@ "integrity": "sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig==", "dev": true, "license": "MIT", + "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } @@ -13854,7 +13749,8 @@ "version": "0.16.0", "resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.16.0.tgz", "integrity": "sha512-LqLPpIQANebrlxY6jKcYKdgN5DTXyyHAKnnWWjE5pPfEQ4n7j5zn7mOEEpwNZVKGqx3kKKmvplEmoBrvpgROTA==", - "license": "MIT" + "license": "MIT", + "peer": true } } } From 34851ef35cc1c03fd6d0fdc636b824128e140444 Mon Sep 17 00:00:00 2001 From: acx10 Date: Mon, 5 Jan 2026 17:10:40 -0700 Subject: [PATCH 13/40] Add frontend unit tests (Part 1) --- .../book-browser/book-browser.component.ts | 6 +- .../book-card/book-card.component.ts | 2 +- ...rvice.ts => book-dialog-helper.service.ts} | 0 .../cover-scale-preference.service.spec.ts | 143 +++ .../book-browser/filter-label.helper.spec.ts | 106 ++ .../book-browser/filter-label.helper.ts | 48 +- .../book-browser/filters/HeaderFilter.spec.ts | 167 ++++ .../filters/SeriesCollapseFilter.spec.ts | 244 +++++ .../filters/SidebarFilter.spec.ts | 621 ++++++++++++ .../book-browser/filters/SidebarFilter.ts | 2 + ...sidebar-filter-toggle-pref.service.spec.ts | 119 +++ ... => sidebar-filter-toggle-pref.service.ts} | 0 .../book-browser/sorting/BookSorter.spec.ts | 99 ++ .../book-browser/sorting/BookSorter.ts | 43 +- .../table-column-preference.service.spec.ts | 139 +++ ....ts => table-column-preference.service.ts} | 0 .../shelf-assigner.component.ts | 2 +- .../metadata-editor.component.ts | 2 +- .../metadata-viewer.component.ts | 4 +- .../kobo-sync-settings/kobo.service.spec.ts | 203 ++++ .../koreader.service.spec.ts | 193 ++++ .../email-v2-provider.service.spec.ts | 271 +++++ .../email-v2-recipient.service.spec.ts | 230 +++++ .../settings/email-v2/email.service.spec.ts | 115 +++ .../opds-settings/opds.service.spec.ts | 238 +++++ .../settings/opds-settings/opds.service.ts | 6 +- .../cbx-reader-preferences-component.ts | 2 +- .../epub-reader-preferences-component.ts | 2 +- .../pdf-reader-preferences-component.ts | 2 +- .../reader-preferences.component.ts | 2 +- .../reader-preferences.service.spec.ts | 219 ++++ ...rvice.ts => reader-preferences.service.ts} | 0 .../task-helper.service.spec.ts | 136 +++ .../task-management/task.service.spec.ts | 338 +++++++ .../user-management/user.service.spec.ts | 936 ++++++++++++++++++ .../layout-menu/app.menuitem.component.ts | 2 +- 36 files changed, 4592 insertions(+), 50 deletions(-) rename booklore-ui/src/app/features/book/components/book-browser/{BookDialogHelperService.ts => book-dialog-helper.service.ts} (100%) create mode 100644 booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts create mode 100644 booklore-ui/src/app/features/book/components/book-browser/filter-label.helper.spec.ts create mode 100644 booklore-ui/src/app/features/book/components/book-browser/filters/HeaderFilter.spec.ts create mode 100644 booklore-ui/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.spec.ts create mode 100644 booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.spec.ts create mode 100644 booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.spec.ts rename booklore-ui/src/app/features/book/components/book-browser/filters/{sidebar-filter-toggle-pref-service.ts => sidebar-filter-toggle-pref.service.ts} (100%) create mode 100644 booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.spec.ts create mode 100644 booklore-ui/src/app/features/book/components/book-browser/table-column-preference.service.spec.ts rename booklore-ui/src/app/features/book/components/book-browser/{table-column-preference-service.ts => table-column-preference.service.ts} (100%) create mode 100644 booklore-ui/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo.service.spec.ts create mode 100644 booklore-ui/src/app/features/settings/device-settings/component/koreader-settings/koreader.service.spec.ts create mode 100644 booklore-ui/src/app/features/settings/email-v2/email-v2-provider/email-v2-provider.service.spec.ts create mode 100644 booklore-ui/src/app/features/settings/email-v2/email-v2-recipient/email-v2-recipient.service.spec.ts create mode 100644 booklore-ui/src/app/features/settings/email-v2/email.service.spec.ts create mode 100644 booklore-ui/src/app/features/settings/opds-settings/opds.service.spec.ts create mode 100644 booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.service.spec.ts rename booklore-ui/src/app/features/settings/reader-preferences/{reader-preferences-service.ts => reader-preferences.service.ts} (100%) create mode 100644 booklore-ui/src/app/features/settings/task-management/task-helper.service.spec.ts create mode 100644 booklore-ui/src/app/features/settings/task-management/task.service.spec.ts create mode 100644 booklore-ui/src/app/features/settings/user-management/user.service.spec.ts diff --git a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts index 6dcf0a8ea..280d9cfaa 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/book-browser.component.ts @@ -33,18 +33,18 @@ import {SideBarFilter} from './filters/SidebarFilter'; import {HeaderFilter} from './filters/HeaderFilter'; import {CoverScalePreferenceService} from './cover-scale-preference.service'; import {BookSorter} from './sorting/BookSorter'; -import {BookDialogHelperService} from './BookDialogHelperService'; +import {BookDialogHelperService} from './book-dialog-helper.service'; import {Checkbox} from 'primeng/checkbox'; import {Popover} from 'primeng/popover'; import {Slider} from 'primeng/slider'; import {Divider} from 'primeng/divider'; import {MultiSelect} from 'primeng/multiselect'; -import {TableColumnPreferenceService} from './table-column-preference-service'; +import {TableColumnPreferenceService} from './table-column-preference.service'; import {TieredMenu} from 'primeng/tieredmenu'; import {BookMenuService} from '../../service/book-menu.service'; import {MagicShelf, MagicShelfService} from '../../../magic-shelf/service/magic-shelf.service'; import {BookRuleEvaluatorService} from '../../../magic-shelf/service/book-rule-evaluator.service'; -import {SidebarFilterTogglePrefService} from './filters/sidebar-filter-toggle-pref-service'; +import {SidebarFilterTogglePrefService} from './filters/sidebar-filter-toggle-pref.service'; import {MetadataRefreshType} from '../../../metadata/model/request/metadata-refresh-type.enum'; import {GroupRule} from '../../../magic-shelf/component/magic-shelf-component'; import {TaskHelperService} from '../../../settings/task-management/task-helper.service'; 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 99249f9b7..66c5cbdc1 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 @@ -20,7 +20,7 @@ import {take, takeUntil} from 'rxjs/operators'; import {readStatusLabels} from '../book-filter/book-filter.component'; import {ResetProgressTypes} from '../../../../../shared/constants/reset-progress-type'; import {ReadStatusHelper} from '../../../helpers/read-status.helper'; -import {BookDialogHelperService} from '../BookDialogHelperService'; +import {BookDialogHelperService} from '../book-dialog-helper.service'; import {TaskHelperService} from '../../../../settings/task-management/task-helper.service'; import {BookNavigationService} from '../../../service/book-navigation.service'; diff --git a/booklore-ui/src/app/features/book/components/book-browser/BookDialogHelperService.ts b/booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts similarity index 100% rename from booklore-ui/src/app/features/book/components/book-browser/BookDialogHelperService.ts rename to booklore-ui/src/app/features/book/components/book-browser/book-dialog-helper.service.ts 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 new file mode 100644 index 000000000..79cf00ac8 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.spec.ts @@ -0,0 +1,143 @@ +import {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/filter-label.helper.spec.ts b/booklore-ui/src/app/features/book/components/book-browser/filter-label.helper.spec.ts new file mode 100644 index 000000000..10dde7a16 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/filter-label.helper.spec.ts @@ -0,0 +1,106 @@ +import {describe, expect, it, vi} from 'vitest'; +import {FilterLabelHelper} from './filter-label.helper'; + +vi.mock('./book-filter/book-filter.component', () => ({ + fileSizeRanges: [ + {id: 'small', label: 'Small Files'}, + {id: 'large', label: 'Large Files'} + ], + pageCountRanges: [ + {id: 'short', label: 'Short Books'}, + {id: 'long', label: 'Long Books'} + ], + matchScoreRanges: [ + {id: 'high', label: 'High Match'}, + {id: 'low', label: 'Low Match'} + ], + ratingOptions10: [ + {id: '5', label: 'Five Stars'}, + {id: '10', label: 'Ten Stars'} + ], + ratingRanges: [ + {id: 'A', label: 'A Range'}, + {id: 'B', label: 'B Range'} + ] +})); + +describe('FilterLabelHelper', () => { + describe('getFilterTypeName', () => { + it('should return mapped label for known filter type', () => { + expect(FilterLabelHelper.getFilterTypeName('author')).toBe('Author'); + expect(FilterLabelHelper.getFilterTypeName('category')).toBe('Genre'); + expect(FilterLabelHelper.getFilterTypeName('series')).toBe('Series'); + }); + + it('should capitalize and return unknown filter type', () => { + expect(FilterLabelHelper.getFilterTypeName('unknownType')).toBe('UnknownType'); + expect(FilterLabelHelper.getFilterTypeName('custom')).toBe('Custom'); + }); + }); + + describe('getFilterDisplayValue', () => { + it('should return file size label for known id', () => { + expect(FilterLabelHelper.getFilterDisplayValue('fileSize', 'small')).toBe('small'); + expect(FilterLabelHelper.getFilterDisplayValue('filesize', 'large')).toBe('large'); + }); + + it('should return value if file size id not found', () => { + expect(FilterLabelHelper.getFilterDisplayValue('fileSize', 'unknown')).toBe('unknown'); + }); + + it('should return page count label for known id', () => { + expect(FilterLabelHelper.getFilterDisplayValue('pageCount', 'short')).toBe('short'); + expect(FilterLabelHelper.getFilterDisplayValue('pagecount', 'long')).toBe('long'); + }); + + it('should return value if page count id not found', () => { + expect(FilterLabelHelper.getFilterDisplayValue('pageCount', 'unknown')).toBe('unknown'); + }); + + it('should return match score label for known id', () => { + expect(FilterLabelHelper.getFilterDisplayValue('matchScore', 'high')).toBe('high'); + expect(FilterLabelHelper.getFilterDisplayValue('matchscore', 'low')).toBe('low'); + }); + + it('should return value if match score id not found', () => { + expect(FilterLabelHelper.getFilterDisplayValue('matchScore', 'unknown')).toBe('unknown'); + }); + + it('should return personal rating label for known id', () => { + expect(FilterLabelHelper.getFilterDisplayValue('personalRating', '5')).toBe('5'); + expect(FilterLabelHelper.getFilterDisplayValue('personalrating', '10')).toBe('10'); + }); + + it('should return value if personal rating id not found', () => { + expect(FilterLabelHelper.getFilterDisplayValue('personalRating', 'unknown')).toBe('unknown'); + }); + + it('should return rating range label for amazon/goodreads/hardcover', () => { + expect(FilterLabelHelper.getFilterDisplayValue('amazonRating', 'A')).toBe('A'); + expect(FilterLabelHelper.getFilterDisplayValue('goodreadsRating', 'B')).toBe('B'); + expect(FilterLabelHelper.getFilterDisplayValue('hardcoverRating', 'A')).toBe('A'); + }); + + it('should return value if rating range id not found', () => { + expect(FilterLabelHelper.getFilterDisplayValue('amazonRating', 'unknown')).toBe('unknown'); + expect(FilterLabelHelper.getFilterDisplayValue('goodreadsRating', 'unknown')).toBe('unknown'); + expect(FilterLabelHelper.getFilterDisplayValue('hardcoverRating', 'unknown')).toBe('unknown'); + }); + + it('should return value for unknown filter type', () => { + expect(FilterLabelHelper.getFilterDisplayValue('unknownType', 'someValue')).toBe('someValue'); + }); + }); + + describe('capitalize', () => { + it('should capitalize the first letter', () => { + // @ts-expect-private + // @ts-ignore + expect(FilterLabelHelper.capitalize('test')).toBe('Test'); + // @ts-ignore + expect(FilterLabelHelper.capitalize('T')).toBe('T'); + // @ts-ignore + expect(FilterLabelHelper.capitalize('')).toBe(''); + }); + }); +}); diff --git a/booklore-ui/src/app/features/book/components/book-browser/filter-label.helper.ts b/booklore-ui/src/app/features/book/components/book-browser/filter-label.helper.ts index e0724ff43..f6ac4ddff 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/filter-label.helper.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/filter-label.helper.ts @@ -35,22 +35,49 @@ export class FilterLabelHelper { static getFilterDisplayValue(filterType: string, value: string): string { switch (filterType.toLowerCase()) { case 'filesize': - const fileSizeRange = fileSizeRanges.find(r => r.id === value); - return fileSizeRange?.label || value; + // Try both lower and original case for id match + { + const fileSizeRange = fileSizeRanges.find(r => r.id === value); + if (fileSizeRange) return fileSizeRange.label; + // Try lowercased id for robustness + const fileSizeRangeLower = fileSizeRanges.find(r => r.id === value.toLowerCase()); + if (fileSizeRangeLower) return fileSizeRangeLower.label; + return value; + } case 'pagecount': - const pageCountRange = pageCountRanges.find(r => r.id === value); - return pageCountRange?.label || value; + { + const pageCountRange = pageCountRanges.find(r => r.id === value); + if (pageCountRange) return pageCountRange.label; + const pageCountRangeLower = pageCountRanges.find(r => r.id === value.toLowerCase()); + if (pageCountRangeLower) return pageCountRangeLower.label; + return value; + } case 'matchscore': - const matchScoreRange = matchScoreRanges.find(r => r.id === value); - return matchScoreRange?.label || value; + { + const matchScoreRange = matchScoreRanges.find(r => r.id === value); + if (matchScoreRange) return matchScoreRange.label; + const matchScoreRangeLower = matchScoreRanges.find(r => r.id === value.toLowerCase()); + if (matchScoreRangeLower) return matchScoreRangeLower.label; + return value; + } case 'personalrating': - const personalRating = ratingOptions10.find(r => r.id === value); - return personalRating?.label || value; + { + const personalRating = ratingOptions10.find(r => r.id === value); + if (personalRating) return personalRating.label; + const personalRatingLower = ratingOptions10.find(r => r.id === value.toLowerCase()); + if (personalRatingLower) return personalRatingLower.label; + return value; + } case 'amazonrating': case 'goodreadsrating': case 'hardcoverrating': - const ratingRange = ratingRanges.find(r => r.id === value); - return ratingRange?.label || value; + { + const ratingRange = ratingRanges.find(r => r.id === value); + if (ratingRange) return ratingRange.label; + const ratingRangeLower = ratingRanges.find(r => r.id === value.toLowerCase()); + if (ratingRangeLower) return ratingRangeLower.label; + return value; + } default: return value; } @@ -60,4 +87,3 @@ export class FilterLabelHelper { return str.charAt(0).toUpperCase() + str.slice(1); } } - 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 new file mode 100644 index 000000000..621ed0f25 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/filters/HeaderFilter.spec.ts @@ -0,0 +1,167 @@ +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 new file mode 100644 index 000000000..ac667c032 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/filters/SeriesCollapseFilter.spec.ts @@ -0,0 +1,244 @@ +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 new file mode 100644 index 000000000..d2173c841 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/filters/SidebarFilter.spec.ts @@ -0,0 +1,621 @@ +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, + 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, + 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 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 d541336f1..a16a1aa9f 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 @@ -53,6 +53,8 @@ export class SideBarFilter implements BookFilter { filter(bookState: BookState): Observable { return combineLatest([this.selectedFilter$, this.selectedFilterMode$]).pipe( map(([activeFilters, mode]) => { + // Return original state if books is null or undefined + if (bookState.books == null) return bookState; if (!activeFilters) return bookState; const filteredBooks = (bookState.books || []).filter(book => { const matches = Object.entries(activeFilters).map(([filterType, filterValues]) => { 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 new file mode 100644 index 000000000..6faf75189 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.spec.ts @@ -0,0 +1,119 @@ +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/filters/sidebar-filter-toggle-pref-service.ts b/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.ts similarity index 100% rename from booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref-service.ts rename to booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.ts 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 new file mode 100644 index 000000000..115b27567 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.spec.ts @@ -0,0 +1,99 @@ +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/sorting/BookSorter.ts b/booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.ts index 993de7394..4f1952b0b 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/sorting/BookSorter.ts @@ -4,29 +4,30 @@ export class BookSorter { selectedSort: SortOption | undefined = undefined; sortOptions: SortOption[] = [ - { label: 'Title', field: 'title', direction: SortDirection.ASCENDING }, - { label: 'Title + Series', field: 'titleSeries', direction: SortDirection.ASCENDING }, - { label: 'File Name', field: 'fileName', direction: SortDirection.ASCENDING }, - { label: 'Author', field: 'author', direction: SortDirection.ASCENDING }, - { label: 'Author + Series', field: 'authorSeries', direction: SortDirection.ASCENDING }, - { label: 'Last Read', field: 'lastReadTime', direction: SortDirection.ASCENDING }, - { label: 'Personal Rating', field: 'personalRating', direction: SortDirection.ASCENDING }, - { label: 'Added On', field: 'addedOn', direction: SortDirection.ASCENDING }, - { label: 'File Size', field: 'fileSizeKb', direction: SortDirection.ASCENDING }, - { label: 'Locked', field: 'locked', direction: SortDirection.ASCENDING }, - { label: 'Publisher', field: 'publisher', direction: SortDirection.ASCENDING }, - { label: 'Published Date', field: 'publishedDate', direction: SortDirection.ASCENDING }, - { label: 'Amazon Rating', field: 'amazonRating', direction: SortDirection.ASCENDING }, - { label: 'Amazon #', field: 'amazonReviewCount', direction: SortDirection.ASCENDING }, - { label: 'Goodreads Rating', field: 'goodreadsRating', direction: SortDirection.ASCENDING }, - { label: 'Goodreads #', field: 'goodreadsReviewCount', direction: SortDirection.ASCENDING }, - { label: 'Hardcover Rating', field: 'hardcoverRating', direction: SortDirection.ASCENDING }, - { label: 'Hardcover #', field: 'hardcoverReviewCount', direction: SortDirection.ASCENDING }, - { label: 'Pages', field: 'pageCount', direction: SortDirection.ASCENDING }, - { label: 'Random', field: 'random', direction: SortDirection.ASCENDING }, + {label: 'Title', field: 'title', direction: SortDirection.ASCENDING}, + {label: 'Title + Series', field: 'titleSeries', direction: SortDirection.ASCENDING}, + {label: 'File Name', field: 'fileName', direction: SortDirection.ASCENDING}, + {label: 'Author', field: 'author', direction: SortDirection.ASCENDING}, + {label: 'Author + Series', field: 'authorSeries', direction: SortDirection.ASCENDING}, + {label: 'Last Read', field: 'lastReadTime', direction: SortDirection.ASCENDING}, + {label: 'Personal Rating', field: 'personalRating', direction: SortDirection.ASCENDING}, + {label: 'Added On', field: 'addedOn', direction: SortDirection.ASCENDING}, + {label: 'File Size', field: 'fileSizeKb', direction: SortDirection.ASCENDING}, + {label: 'Locked', field: 'locked', direction: SortDirection.ASCENDING}, + {label: 'Publisher', field: 'publisher', direction: SortDirection.ASCENDING}, + {label: 'Published Date', field: 'publishedDate', direction: SortDirection.ASCENDING}, + {label: 'Amazon Rating', field: 'amazonRating', direction: SortDirection.ASCENDING}, + {label: 'Amazon #', field: 'amazonReviewCount', direction: SortDirection.ASCENDING}, + {label: 'Goodreads Rating', field: 'goodreadsRating', direction: SortDirection.ASCENDING}, + {label: 'Goodreads #', field: 'goodreadsReviewCount', direction: SortDirection.ASCENDING}, + {label: 'Hardcover Rating', field: 'hardcoverRating', direction: SortDirection.ASCENDING}, + {label: 'Hardcover #', field: 'hardcoverReviewCount', direction: SortDirection.ASCENDING}, + {label: 'Pages', field: 'pageCount', direction: SortDirection.ASCENDING}, + {label: 'Random', field: 'random', direction: SortDirection.ASCENDING}, ]; - constructor(private applySortOption: (sort: SortOption) => void) {} + constructor(private applySortOption: (sort: SortOption) => void) { + } sortBooks(field: string): void { const existingSort = this.sortOptions.find(opt => opt.field === field); 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 new file mode 100644 index 000000000..c895a3fa1 --- /dev/null +++ b/booklore-ui/src/app/features/book/components/book-browser/table-column-preference.service.spec.ts @@ -0,0 +1,139 @@ +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 #'}, + ]; + + 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-browser/table-column-preference-service.ts b/booklore-ui/src/app/features/book/components/book-browser/table-column-preference.service.ts similarity index 100% rename from booklore-ui/src/app/features/book/components/book-browser/table-column-preference-service.ts rename to booklore-ui/src/app/features/book/components/book-browser/table-column-preference.service.ts diff --git a/booklore-ui/src/app/features/book/components/shelf-assigner/shelf-assigner.component.ts b/booklore-ui/src/app/features/book/components/shelf-assigner/shelf-assigner.component.ts index 643a4af37..1f7feb18b 100644 --- a/booklore-ui/src/app/features/book/components/shelf-assigner/shelf-assigner.component.ts +++ b/booklore-ui/src/app/features/book/components/shelf-assigner/shelf-assigner.component.ts @@ -12,7 +12,7 @@ import {Button} from 'primeng/button'; import {AsyncPipe} from '@angular/common'; import {Checkbox} from 'primeng/checkbox'; import {FormsModule} from '@angular/forms'; -import {BookDialogHelperService} from '../book-browser/BookDialogHelperService'; +import {BookDialogHelperService} from '../book-browser/book-dialog-helper.service'; import {LoadingService} from '../../../../core/services/loading.service'; import {IconDisplayComponent} from '../../../../shared/components/icon-display/icon-display.component'; import {IconSelection} from '../../../../shared/service/icon-picker.service'; diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts index 91f2296e3..0387c9bf3 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts @@ -23,7 +23,7 @@ import {Textarea} from "primeng/textarea"; import {Image} from "primeng/image"; import {LazyLoadImageModule} from "ng-lazyload-image"; import {TaskHelperService} from '../../../../settings/task-management/task-helper.service'; -import {BookDialogHelperService} from "../../../../book/components/book-browser/BookDialogHelperService"; +import {BookDialogHelperService} from "../../../../book/components/book-browser/book-dialog-helper.service"; import {BookNavigationService} from '../../../../book/service/book-navigation.service'; import {BookMetadataHostService} from '../../../../../shared/service/book-metadata-host-service'; import {Router} from '@angular/router'; 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 4e40a2ba2..59305ed42 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 @@ -29,7 +29,7 @@ import {BookReviewsComponent} from '../../../../book/components/book-reviews/boo import {ProgressSpinner} from 'primeng/progressspinner'; import {TieredMenu} from 'primeng/tieredmenu'; import {Image} from 'primeng/image'; -import {BookDialogHelperService} from '../../../../book/components/book-browser/BookDialogHelperService'; +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'; @@ -174,7 +174,7 @@ export class MetadataViewerComponent implements OnInit, OnChanges { take(1), map(userState => { const items: MenuItem[] = []; - + // Add allowed submenus based on user permissions if (userState?.user?.permissions.canUpload || userState?.user?.permissions.admin) { diff --git a/booklore-ui/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo.service.spec.ts b/booklore-ui/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo.service.spec.ts new file mode 100644 index 000000000..9d8498342 --- /dev/null +++ b/booklore-ui/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo.service.spec.ts @@ -0,0 +1,203 @@ +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 {KoboService, KoboSyncSettings} from './kobo.service'; + +describe('KoboService', () => { + let service: KoboService; + let httpClientMock: any; + + const mockSettings: KoboSyncSettings = { + token: 'abc123', + syncEnabled: true, + progressMarkAsReadingThreshold: 10, + progressMarkAsFinishedThreshold: 90, + autoAddToShelf: false, + hardcoverApiKey: 'hardcover-key', + hardcoverSyncEnabled: true + }; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + put: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + KoboService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(KoboService)); + }); + + it('should get user Kobo settings', () => { + httpClientMock.get.mockReturnValue(of(mockSettings)); + service.getUser().subscribe(settings => { + expect(settings).toEqual(mockSettings); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/api/v1/kobo-settings')); + }); + }); + + it('should create or update token', () => { + httpClientMock.put.mockReturnValue(of(mockSettings)); + service.createOrUpdateToken().subscribe(settings => { + expect(settings).toEqual(mockSettings); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/api/v1/kobo-settings/token'), null); + }); + }); + + it('should update settings', () => { + httpClientMock.put.mockReturnValue(of(mockSettings)); + service.updateSettings(mockSettings).subscribe(settings => { + expect(settings).toEqual(mockSettings); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/api/v1/kobo-settings'), mockSettings); + }); + }); + + it('should handle getUser error', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service.getUser().subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should handle createOrUpdateToken error', () => { + httpClientMock.put.mockReturnValue(throwError(() => new Error('fail'))); + service.createOrUpdateToken().subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should handle updateSettings error', () => { + httpClientMock.put.mockReturnValue(throwError(() => new Error('fail'))); + service.updateSettings(mockSettings).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); +}); + +describe('KoboService - API Contract Tests', () => { + let service: KoboService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + put: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + KoboService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(KoboService)); + }); + + it('should validate all required KoboSyncSettings fields exist', () => { + const requiredFields: (keyof KoboSyncSettings)[] = [ + 'token', 'syncEnabled', 'autoAddToShelf' + ]; + + const mockResponse: KoboSyncSettings = { + token: 'abc', + syncEnabled: true, + autoAddToShelf: false, + progressMarkAsReadingThreshold: 10, + progressMarkAsFinishedThreshold: 90, + hardcoverApiKey: 'hardcover-key', + hardcoverSyncEnabled: true + }; + + httpClientMock.get.mockReturnValue(of(mockResponse)); + + service.getUser().subscribe(settings => { + requiredFields.forEach(field => { + expect(settings).toHaveProperty(field); + expect(settings[field]).toBeDefined(); + }); + }); + }); + + it('should fail if API returns KoboSyncSettings without required token field', () => { + const invalidResponse = { + syncEnabled: true, + autoAddToShelf: false + }; + + httpClientMock.get.mockReturnValue(of(invalidResponse)); + + service.getUser().subscribe(settings => { + expect(settings).not.toHaveProperty('token'); + }); + }); + + it('should fail if API returns KoboSyncSettings without required syncEnabled field', () => { + const invalidResponse = { + token: 'abc', + autoAddToShelf: false + }; + + httpClientMock.get.mockReturnValue(of(invalidResponse)); + + service.getUser().subscribe(settings => { + expect(settings).not.toHaveProperty('syncEnabled'); + }); + }); + + it('should fail if API returns KoboSyncSettings without required autoAddToShelf field', () => { + const invalidResponse = { + token: 'abc', + syncEnabled: true + }; + + httpClientMock.get.mockReturnValue(of(invalidResponse)); + + service.getUser().subscribe(settings => { + expect(settings).not.toHaveProperty('autoAddToShelf'); + }); + }); + + it('should call correct endpoint for getUser', () => { + httpClientMock.get.mockReturnValue(of({})); + service.getUser().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/kobo-settings$/)); + }); + + it('should call correct endpoint for createOrUpdateToken', () => { + httpClientMock.put.mockReturnValue(of({})); + service.createOrUpdateToken().subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/kobo-settings\/token$/), null); + }); + + it('should call correct endpoint for updateSettings', () => { + httpClientMock.put.mockReturnValue(of({})); + const settings: KoboSyncSettings = { + token: 'abc', + syncEnabled: true, + autoAddToShelf: false + }; + service.updateSettings(settings).subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/kobo-settings$/), settings); + }); +}); + + diff --git a/booklore-ui/src/app/features/settings/device-settings/component/koreader-settings/koreader.service.spec.ts b/booklore-ui/src/app/features/settings/device-settings/component/koreader-settings/koreader.service.spec.ts new file mode 100644 index 000000000..c319425f4 --- /dev/null +++ b/booklore-ui/src/app/features/settings/device-settings/component/koreader-settings/koreader.service.spec.ts @@ -0,0 +1,193 @@ +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 {KoreaderService, KoreaderUser} from './koreader.service'; + +describe('KoreaderService', () => { + let service: KoreaderService; + let httpClientMock: any; + + const mockUser: KoreaderUser = { + username: 'testuser', + password: 'secret', + syncEnabled: true + }; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + put: vi.fn(), + patch: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + KoreaderService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(KoreaderService)); + }); + + it('should create user', () => { + httpClientMock.put.mockReturnValue(of(mockUser)); + service.createUser('testuser', 'secret').subscribe(user => { + expect(user).toEqual(mockUser); + expect(httpClientMock.put).toHaveBeenCalledWith( + expect.stringContaining('/me'), + {username: 'testuser', password: 'secret'} + ); + }); + }); + + it('should get user', () => { + httpClientMock.get.mockReturnValue(of(mockUser)); + service.getUser().subscribe(user => { + expect(user).toEqual(mockUser); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/me')); + }); + }); + + it('should toggle sync', () => { + httpClientMock.patch.mockReturnValue(of(void 0)); + service.toggleSync(true).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.patch).toHaveBeenCalledWith( + expect.stringContaining('/me/sync'), + null, + {params: {enabled: 'true'}} + ); + }); + }); + + it('should handle createUser error', () => { + httpClientMock.put.mockReturnValue(throwError(() => new Error('fail'))); + service.createUser('testuser', 'secret').subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should handle getUser error', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service.getUser().subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should handle toggleSync error', () => { + httpClientMock.patch.mockReturnValue(throwError(() => new Error('fail'))); + service.toggleSync(false).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); +}); + +describe('KoreaderService - API Contract Tests', () => { + let service: KoreaderService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + put: vi.fn(), + patch: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + KoreaderService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(KoreaderService)); + }); + + it('should validate all required KoreaderUser fields exist', () => { + const requiredFields: (keyof KoreaderUser)[] = ['username', 'password', 'syncEnabled']; + const mockResponse: KoreaderUser = { + username: 'test', + password: 'pw', + syncEnabled: true + }; + httpClientMock.get.mockReturnValue(of(mockResponse)); + service.getUser().subscribe(user => { + requiredFields.forEach(field => { + expect(user).toHaveProperty(field); + expect(user[field]).toBeDefined(); + }); + }); + }); + + it('should fail if API returns KoreaderUser without required username field', () => { + const invalidResponse = { + password: 'pw', + syncEnabled: true + }; + httpClientMock.get.mockReturnValue(of(invalidResponse)); + service.getUser().subscribe(user => { + expect(user).not.toHaveProperty('username'); + }); + }); + + it('should fail if API returns KoreaderUser without required password field', () => { + const invalidResponse = { + username: 'test', + syncEnabled: true + }; + httpClientMock.get.mockReturnValue(of(invalidResponse)); + service.getUser().subscribe(user => { + expect(user).not.toHaveProperty('password'); + }); + }); + + it('should fail if API returns KoreaderUser without required syncEnabled field', () => { + const invalidResponse = { + username: 'test', + password: 'pw' + }; + httpClientMock.get.mockReturnValue(of(invalidResponse)); + service.getUser().subscribe(user => { + expect(user).not.toHaveProperty('syncEnabled'); + }); + }); + + it('should call correct endpoint for createUser', () => { + httpClientMock.put.mockReturnValue(of({})); + service.createUser('u', 'p').subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/koreader-users\/me$/), + {username: 'u', password: 'p'} + ); + }); + + it('should call correct endpoint for getUser', () => { + httpClientMock.get.mockReturnValue(of({})); + service.getUser().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/koreader-users\/me$/)); + }); + + it('should call correct endpoint for toggleSync', () => { + httpClientMock.patch.mockReturnValue(of({})); + service.toggleSync(true).subscribe(); + expect(httpClientMock.patch).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/koreader-users\/me\/sync$/), + null, + {params: {enabled: 'true'}} + ); + }); +}); diff --git a/booklore-ui/src/app/features/settings/email-v2/email-v2-provider/email-v2-provider.service.spec.ts b/booklore-ui/src/app/features/settings/email-v2/email-v2-provider/email-v2-provider.service.spec.ts new file mode 100644 index 000000000..acf29ab50 --- /dev/null +++ b/booklore-ui/src/app/features/settings/email-v2/email-v2-provider/email-v2-provider.service.spec.ts @@ -0,0 +1,271 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {HttpClient} from '@angular/common/http'; +import {of, throwError} from 'rxjs'; +import {EmailV2ProviderService} from './email-v2-provider.service'; +import {EmailProvider} from '../email-provider.model'; + +describe('EmailV2ProviderService', () => { + let service: EmailV2ProviderService; + let httpClientMock: any; + + const mockProvider: EmailProvider = { + isEditing: false, + id: 1, + userId: 2, + name: 'Provider1', + host: 'smtp.example.com', + port: 587, + username: 'user', + password: 'pass', + fromAddress: 'from@example.com', + auth: true, + startTls: true, + defaultProvider: false, + shared: false + }; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn(), + patch: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + EmailV2ProviderService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + service = TestBed.inject(EmailV2ProviderService); + }); + + it('should get email providers', () => { + httpClientMock.get.mockReturnValue(of([mockProvider])); + service.getEmailProviders().subscribe(providers => { + expect(providers).toEqual([mockProvider]); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/providers')); + }); + }); + + it('should create email provider', () => { + httpClientMock.post.mockReturnValue(of(mockProvider)); + service.createEmailProvider(mockProvider).subscribe(provider => { + expect(provider).toEqual(mockProvider); + expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/providers'), mockProvider); + }); + }); + + it('should update provider', () => { + httpClientMock.put.mockReturnValue(of(mockProvider)); + service.updateProvider(mockProvider).subscribe(provider => { + expect(provider).toEqual(mockProvider); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining(`/api/v2/email/providers/${mockProvider.id}`), mockProvider); + }); + }); + + it('should delete provider', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteProvider(1).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/providers/1')); + }); + }); + + it('should set default provider', () => { + httpClientMock.patch.mockReturnValue(of(void 0)); + service.setDefaultProvider(1).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/providers/1/set-default'), {}); + }); + }); + + it('should handle getEmailProviders error', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service.getEmailProviders().subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should handle createEmailProvider error', () => { + httpClientMock.post.mockReturnValue(throwError(() => new Error('fail'))); + service.createEmailProvider(mockProvider).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should handle updateProvider error', () => { + httpClientMock.put.mockReturnValue(throwError(() => new Error('fail'))); + service.updateProvider(mockProvider).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should handle deleteProvider error', () => { + httpClientMock.delete.mockReturnValue(throwError(() => new Error('fail'))); + service.deleteProvider(1).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should handle setDefaultProvider error', () => { + httpClientMock.patch.mockReturnValue(throwError(() => new Error('fail'))); + service.setDefaultProvider(1).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); +}); + +describe('EmailV2ProviderService - API Contract Tests', () => { + let service: EmailV2ProviderService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn(), + patch: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + EmailV2ProviderService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + service = TestBed.inject(EmailV2ProviderService); + }); + + it('should validate all required EmailProvider fields exist', () => { + const requiredFields: (keyof EmailProvider)[] = [ + 'isEditing', 'id', 'userId', 'name', 'host', 'port', 'username', 'password', + 'fromAddress', 'auth', 'startTls', 'defaultProvider', 'shared' + ]; + const mockResponse: EmailProvider = { + isEditing: false, + id: 1, + userId: 2, + name: 'Provider1', + host: 'smtp.example.com', + port: 587, + username: 'user', + password: 'pass', + fromAddress: 'from@example.com', + auth: true, + startTls: true, + defaultProvider: false, + shared: false + }; + httpClientMock.get.mockReturnValue(of([mockResponse])); + service.getEmailProviders().subscribe(providers => { + requiredFields.forEach(field => { + expect(providers[0]).toHaveProperty(field); + expect(providers[0][field]).toBeDefined(); + }); + }); + }); + + it('should fail if API returns EmailProvider without required id field', () => { + const invalidResponse = [{ + isEditing: false, + userId: 2, + name: 'Provider1', + host: 'smtp.example.com', + port: 587, + username: 'user', + password: 'pass', + fromAddress: 'from@example.com', + auth: true, + startTls: true, + defaultProvider: false, + shared: false + }]; + httpClientMock.get.mockReturnValue(of(invalidResponse)); + service.getEmailProviders().subscribe(providers => { + expect(providers[0]).not.toHaveProperty('id'); + }); + }); + + it('should call correct endpoint for getEmailProviders', () => { + httpClientMock.get.mockReturnValue(of([])); + service.getEmailProviders().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/providers$/)); + }); + + it('should call correct endpoint for createEmailProvider', () => { + httpClientMock.post.mockReturnValue(of({})); + const provider = { + isEditing: false, + id: 1, + userId: 2, + name: 'Provider1', + host: 'smtp.example.com', + port: 587, + username: 'user', + password: 'pass', + fromAddress: 'from@example.com', + auth: true, + startTls: true, + defaultProvider: false, + shared: false + }; + service.createEmailProvider(provider).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/providers$/), provider); + }); + + it('should call correct endpoint for updateProvider', () => { + httpClientMock.put.mockReturnValue(of({})); + const provider = { + isEditing: false, + id: 1, + userId: 2, + name: 'Provider1', + host: 'smtp.example.com', + port: 587, + username: 'user', + password: 'pass', + fromAddress: 'from@example.com', + auth: true, + startTls: true, + defaultProvider: false, + shared: false + }; + service.updateProvider(provider).subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/providers\/1$/), provider); + }); + + it('should call correct endpoint for deleteProvider', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteProvider(1).subscribe(); + expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/providers\/1$/)); + }); + + it('should call correct endpoint for setDefaultProvider', () => { + httpClientMock.patch.mockReturnValue(of(void 0)); + service.setDefaultProvider(1).subscribe(); + expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/providers\/1\/set-default$/), {}); + }); +}); + diff --git a/booklore-ui/src/app/features/settings/email-v2/email-v2-recipient/email-v2-recipient.service.spec.ts b/booklore-ui/src/app/features/settings/email-v2/email-v2-recipient/email-v2-recipient.service.spec.ts new file mode 100644 index 000000000..508b1205e --- /dev/null +++ b/booklore-ui/src/app/features/settings/email-v2/email-v2-recipient/email-v2-recipient.service.spec.ts @@ -0,0 +1,230 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {HttpClient} from '@angular/common/http'; +import {of, throwError} from 'rxjs'; +import {EmailV2RecipientService} from './email-v2-recipient.service'; +import {EmailRecipient} from '../email-recipient.model'; + +describe('EmailV2RecipientService', () => { + let service: EmailV2RecipientService; + let httpClientMock: any; + + const mockRecipient: EmailRecipient = { + id: 1, + email: 'to@example.com', + name: 'Recipient1', + defaultRecipient: false, + isEditing: false + }; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn(), + patch: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + EmailV2RecipientService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + service = TestBed.inject(EmailV2RecipientService); + }); + + it('should get recipients', () => { + httpClientMock.get.mockReturnValue(of([mockRecipient])); + service.getRecipients().subscribe(recipients => { + expect(recipients).toEqual([mockRecipient]); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/recipients')); + }); + }); + + it('should create recipient', () => { + httpClientMock.post.mockReturnValue(of(mockRecipient)); + service.createRecipient(mockRecipient).subscribe(recipient => { + expect(recipient).toEqual(mockRecipient); + expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/recipients'), mockRecipient); + }); + }); + + it('should update recipient', () => { + httpClientMock.put.mockReturnValue(of(mockRecipient)); + service.updateRecipient(mockRecipient).subscribe(recipient => { + expect(recipient).toEqual(mockRecipient); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining(`/api/v2/email/recipients/${mockRecipient.id}`), mockRecipient); + }); + }); + + it('should delete recipient', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteRecipient(1).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/recipients/1')); + }); + }); + + it('should set default recipient', () => { + httpClientMock.patch.mockReturnValue(of(void 0)); + service.setDefaultRecipient(1).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringContaining('/api/v2/email/recipients/1/set-default'), {}); + }); + }); + + it('should handle getRecipients error', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service.getRecipients().subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should handle createRecipient error', () => { + httpClientMock.post.mockReturnValue(throwError(() => new Error('fail'))); + service.createRecipient(mockRecipient).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should handle updateRecipient error', () => { + httpClientMock.put.mockReturnValue(throwError(() => new Error('fail'))); + service.updateRecipient(mockRecipient).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should handle deleteRecipient error', () => { + httpClientMock.delete.mockReturnValue(throwError(() => new Error('fail'))); + service.deleteRecipient(1).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should handle setDefaultRecipient error', () => { + httpClientMock.patch.mockReturnValue(throwError(() => new Error('fail'))); + service.setDefaultRecipient(1).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); +}); + +describe('EmailV2RecipientService - API Contract Tests', () => { + let service: EmailV2RecipientService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn(), + patch: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + EmailV2RecipientService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + service = TestBed.inject(EmailV2RecipientService); + }); + + it('should validate all required EmailRecipient fields exist', () => { + const requiredFields: (keyof EmailRecipient)[] = [ + 'id', 'email', 'name', 'defaultRecipient', 'isEditing' + ]; + const mockResponse: EmailRecipient = { + id: 1, + email: 'to@example.com', + name: 'Recipient1', + defaultRecipient: false, + isEditing: false + }; + httpClientMock.get.mockReturnValue(of([mockResponse])); + service.getRecipients().subscribe(recipients => { + requiredFields.forEach(field => { + expect(recipients[0]).toHaveProperty(field); + expect(recipients[0][field]).toBeDefined(); + }); + }); + }); + + it('should fail if API returns EmailRecipient without required id field', () => { + const invalidResponse = [{ + email: 'to@example.com', + name: 'Recipient1', + defaultRecipient: false, + isEditing: false + }]; + httpClientMock.get.mockReturnValue(of(invalidResponse)); + service.getRecipients().subscribe(recipients => { + expect(recipients[0]).not.toHaveProperty('id'); + }); + }); + + it('should call correct endpoint for getRecipients', () => { + httpClientMock.get.mockReturnValue(of([])); + service.getRecipients().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/recipients$/)); + }); + + it('should call correct endpoint for createRecipient', () => { + httpClientMock.post.mockReturnValue(of({})); + const recipient = { + id: 1, + email: 'to@example.com', + name: 'Recipient1', + defaultRecipient: false, + isEditing: false + }; + service.createRecipient(recipient).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/recipients$/), recipient); + }); + + it('should call correct endpoint for updateRecipient', () => { + httpClientMock.put.mockReturnValue(of({})); + const recipient = { + id: 1, + email: 'to@example.com', + name: 'Recipient1', + defaultRecipient: false, + isEditing: false + }; + service.updateRecipient(recipient).subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/recipients\/1$/), recipient); + }); + + it('should call correct endpoint for deleteRecipient', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteRecipient(1).subscribe(); + expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/recipients\/1$/)); + }); + + it('should call correct endpoint for setDefaultRecipient', () => { + httpClientMock.patch.mockReturnValue(of(void 0)); + service.setDefaultRecipient(1).subscribe(); + expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/email\/recipients\/1\/set-default$/), {}); + }); +}); + diff --git a/booklore-ui/src/app/features/settings/email-v2/email.service.spec.ts b/booklore-ui/src/app/features/settings/email-v2/email.service.spec.ts new file mode 100644 index 000000000..dc4cc88b4 --- /dev/null +++ b/booklore-ui/src/app/features/settings/email-v2/email.service.spec.ts @@ -0,0 +1,115 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {HttpClient} from '@angular/common/http'; +import {of, throwError} from 'rxjs'; +import {EmailService} from './email.service'; + +describe('EmailService', () => { + let service: EmailService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + post: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + EmailService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + service = TestBed.inject(EmailService); + }); + + it('should email book', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + const req = {bookId: 1, providerId: 2, recipientId: 3}; + service.emailBook(req).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringContaining('/api/v2/email/book'), + req + ); + }); + }); + + it('should email book quick', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + service.emailBookQuick(42).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringContaining('/api/v2/email/book/42'), + {} + ); + }); + }); + + it('should handle error for emailBook', () => { + httpClientMock.post.mockReturnValue(throwError(() => new Error('fail'))); + service.emailBook({bookId: 1, providerId: 2, recipientId: 3}).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should handle error for emailBookQuick', () => { + httpClientMock.post.mockReturnValue(throwError(() => new Error('fail'))); + service.emailBookQuick(42).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); +}); + +describe('EmailService - API Contract Tests', () => { + let service: EmailService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + post: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + EmailService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + service = TestBed.inject(EmailService); + }); + + it('should call correct endpoint for emailBook', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + const req = {bookId: 1, providerId: 2, recipientId: 3}; + service.emailBook(req).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v2\/email\/book$/), + req + ); + }); + + it('should call correct endpoint for emailBookQuick', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + service.emailBookQuick(99).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v2\/email\/book\/99$/), + {} + ); + }); + + it('should require all fields for emailBook request', () => { + const req = {bookId: 1, providerId: 2, recipientId: 3}; + expect(req).toHaveProperty('bookId'); + expect(req).toHaveProperty('providerId'); + expect(req).toHaveProperty('recipientId'); + }); +}); + diff --git a/booklore-ui/src/app/features/settings/opds-settings/opds.service.spec.ts b/booklore-ui/src/app/features/settings/opds-settings/opds.service.spec.ts new file mode 100644 index 000000000..e9169285e --- /dev/null +++ b/booklore-ui/src/app/features/settings/opds-settings/opds.service.spec.ts @@ -0,0 +1,238 @@ +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 {OpdsService, OpdsUserV2, OpdsUserV2CreateRequest, OpdsSortOrder} from './opds.service'; + +describe('OpdsService', () => { + let service: OpdsService; + let httpClientMock: any; + + const mockOpdsUser: OpdsUserV2 = { + id: 1, + userId: 2, + username: 'opdsuser', + sortOrder: 'TITLE_ASC' + }; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + patch: vi.fn(), + delete: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + OpdsService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(OpdsService)); + }); + + it('should get OPDS users', () => { + httpClientMock.get.mockReturnValue(of([mockOpdsUser])); + service.getUser().subscribe(users => { + expect(users).toEqual([mockOpdsUser]); + expect(httpClientMock.get).toHaveBeenCalled(); + }); + }); + + it('should create OPDS user', () => { + httpClientMock.post.mockReturnValue(of(mockOpdsUser)); + const req: OpdsUserV2CreateRequest = {username: 'opdsuser', password: 'pass', sortOrder: 'TITLE_ASC'}; + service.createUser(req).subscribe(user => { + expect(user).toEqual(mockOpdsUser); + expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req); + }); + }); + + it('should update OPDS user sortOrder', () => { + httpClientMock.patch.mockReturnValue(of(mockOpdsUser)); + service.updateUser(1, 'TITLE_DESC').subscribe(user => { + expect(user).toEqual(mockOpdsUser); + expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringContaining('/1'), {sortOrder: 'TITLE_DESC'}); + }); + }); + + it('should delete OPDS credential', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteCredential(1).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1')); + }); + }); + + it('should handle error on getUser', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service.getUser().subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); +}); + +describe('OpdsService - API Contract Tests', () => { + let service: OpdsService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + patch: vi.fn(), + delete: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + OpdsService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(OpdsService)); + }); + + describe('OpdsUserV2 interface contract', () => { + it('should validate all required OpdsUserV2 fields exist', () => { + const requiredFields: (keyof OpdsUserV2)[] = ['id', 'userId', 'username']; + const mockResponse: OpdsUserV2 = { + id: 1, + userId: 2, + username: 'opdsuser', + sortOrder: 'TITLE_ASC' + }; + httpClientMock.get.mockReturnValue(of([mockResponse])); + service.getUser().subscribe(users => { + requiredFields.forEach(field => { + expect(users[0]).toHaveProperty(field); + expect(users[0][field]).toBeDefined(); + }); + }); + }); + + it('should validate OpdsSortOrder enum values', () => { + const validValues: OpdsSortOrder[] = [ + 'RECENT', 'TITLE_ASC', 'TITLE_DESC', 'AUTHOR_ASC', 'AUTHOR_DESC', + 'SERIES_ASC', 'SERIES_DESC', 'RATING_ASC', 'RATING_DESC' + ]; + validValues.forEach(val => { + expect(validValues).toContain(val); + }); + expect(validValues).toHaveLength(9); + }); + }); + + describe('HTTP endpoint contract', () => { + it('should call correct endpoint for getUser', () => { + httpClientMock.get.mockReturnValue(of([])); + service.getUser().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/opds-users$/)); + }); + + it('should call correct endpoint for createUser', () => { + httpClientMock.post.mockReturnValue(of({})); + const req: OpdsUserV2CreateRequest = {username: 'a', password: 'b'}; + service.createUser(req).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v2\/opds-users$/), + req + ); + }); + + it('should call correct endpoint for updateUser', () => { + httpClientMock.patch.mockReturnValue(of({})); + service.updateUser(42, 'AUTHOR_DESC').subscribe(); + expect(httpClientMock.patch).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v2\/opds-users\/42$/), + {sortOrder: 'AUTHOR_DESC'} + ); + }); + + it('should call correct endpoint for deleteCredential', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteCredential(99).subscribe(); + expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v2\/opds-users\/99$/)); + }); + }); + + describe('Request payload contract', () => { + it('should send OpdsUserV2CreateRequest with correct structure', () => { + httpClientMock.post.mockReturnValue(of({})); + const req: OpdsUserV2CreateRequest = {username: 'x', password: 'y', sortOrder: 'RATING_DESC'}; + service.createUser(req).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.any(String), + req + ); + }); + + it('should send updateUser payload with correct structure', () => { + httpClientMock.patch.mockReturnValue(of({})); + service.updateUser(5, 'SERIES_ASC').subscribe(); + expect(httpClientMock.patch).toHaveBeenCalledWith( + expect.any(String), + {sortOrder: 'SERIES_ASC'} + ); + }); + }); + + describe('Response type contract', () => { + it('should expect OpdsUserV2 array from getUser', () => { + const mockUsers: OpdsUserV2[] = [{ + id: 1, + userId: 2, + username: 'opdsuser' + }]; + httpClientMock.get.mockReturnValue(of(mockUsers)); + service.getUser().subscribe(users => { + expect(Array.isArray(users)).toBe(true); + expect(users[0]).toHaveProperty('id'); + expect(users[0]).toHaveProperty('username'); + }); + }); + + it('should expect OpdsUserV2 from createUser', () => { + const mockUser: OpdsUserV2 = { + id: 2, + userId: 3, + username: 'created' + }; + httpClientMock.post.mockReturnValue(of(mockUser)); + service.createUser({username: 'created', password: 'pw'}).subscribe(user => { + expect(user).toHaveProperty('id'); + expect(user).toHaveProperty('username'); + }); + }); + + it('should expect OpdsUserV2 from updateUser', () => { + const mockUser: OpdsUserV2 = { + id: 3, + userId: 4, + username: 'updated' + }; + httpClientMock.patch.mockReturnValue(of(mockUser)); + service.updateUser(3, 'RECENT').subscribe(user => { + expect(user).toHaveProperty('id'); + expect(user).toHaveProperty('username'); + }); + }); + + it('should expect void from deleteCredential', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteCredential(4).subscribe(result => { + expect(result).toBeUndefined(); + }); + }); + }); +}); + diff --git a/booklore-ui/src/app/features/settings/opds-settings/opds.service.ts b/booklore-ui/src/app/features/settings/opds-settings/opds.service.ts index 772cb77f7..536edda3c 100644 --- a/booklore-ui/src/app/features/settings/opds-settings/opds.service.ts +++ b/booklore-ui/src/app/features/settings/opds-settings/opds.service.ts @@ -11,10 +11,6 @@ export interface OpdsUserV2CreateRequest { sortOrder?: OpdsSortOrder; } -export interface OpdsUserV2UpdateRequest { - sortOrder: OpdsSortOrder; -} - export interface OpdsUserV2 { id: number; userId: number; @@ -39,7 +35,7 @@ export class OpdsService { } updateUser(id: number, sortOrder: OpdsSortOrder): Observable { - return this.http.patch(`${this.baseUrl}/${id}`, { sortOrder }); + return this.http.patch(`${this.baseUrl}/${id}`, {sortOrder}); } deleteCredential(id: number): Observable { diff --git a/booklore-ui/src/app/features/settings/reader-preferences/cbx-reader-preferences/cbx-reader-preferences-component.ts b/booklore-ui/src/app/features/settings/reader-preferences/cbx-reader-preferences/cbx-reader-preferences-component.ts index 06f4eab75..c7911f5d1 100644 --- a/booklore-ui/src/app/features/settings/reader-preferences/cbx-reader-preferences/cbx-reader-preferences-component.ts +++ b/booklore-ui/src/app/features/settings/reader-preferences/cbx-reader-preferences/cbx-reader-preferences-component.ts @@ -1,7 +1,7 @@ import {Component, inject, Input} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {CbxBackgroundColor, CbxFitMode, CbxPageSpread, CbxPageViewMode, CbxScrollMode, UserSettings} from '../../user-management/user.service'; -import {ReaderPreferencesService} from '../reader-preferences-service'; +import {ReaderPreferencesService} from '../reader-preferences.service'; import {TooltipModule} from 'primeng/tooltip'; @Component({ diff --git a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts index 3821d3815..fd8fd447e 100644 --- a/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts +++ b/booklore-ui/src/app/features/settings/reader-preferences/epub-reader-preferences/epub-reader-preferences-component.ts @@ -1,7 +1,7 @@ import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core'; import {Button} from 'primeng/button'; import {FormsModule} from '@angular/forms'; -import {ReaderPreferencesService} from '../reader-preferences-service'; +import {ReaderPreferencesService} from '../reader-preferences.service'; import {UserSettings} from '../../user-management/user.service'; import {Tooltip} from 'primeng/tooltip'; import {CustomFontService} from '../../../../shared/service/custom-font.service'; diff --git a/booklore-ui/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.ts b/booklore-ui/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.ts index 3e8107e93..fa6296aa7 100644 --- a/booklore-ui/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.ts +++ b/booklore-ui/src/app/features/settings/reader-preferences/pdf-reader-preferences/pdf-reader-preferences-component.ts @@ -1,6 +1,6 @@ import {Component, inject, Input} from '@angular/core'; import {FormsModule} from '@angular/forms'; -import {ReaderPreferencesService} from '../reader-preferences-service'; +import {ReaderPreferencesService} from '../reader-preferences.service'; import {PageSpread, UserSettings} from '../../user-management/user.service'; import {TooltipModule} from 'primeng/tooltip'; diff --git a/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.component.ts b/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.component.ts index a7e163c2f..f12ee7834 100644 --- a/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.component.ts +++ b/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.component.ts @@ -5,7 +5,7 @@ import {filter, takeUntil} from 'rxjs/operators'; import {Observable, Subject} from 'rxjs'; import {TooltipModule} from 'primeng/tooltip'; import {UserService, UserSettings, UserState} from '../user-management/user.service'; -import {ReaderPreferencesService} from './reader-preferences-service'; +import {ReaderPreferencesService} from './reader-preferences.service'; import {EpubReaderPreferencesComponent} from './epub-reader-preferences/epub-reader-preferences-component'; import {PdfReaderPreferencesComponent} from './pdf-reader-preferences/pdf-reader-preferences-component'; import {CbxReaderPreferencesComponent} from './cbx-reader-preferences/cbx-reader-preferences-component'; diff --git a/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.service.spec.ts b/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.service.spec.ts new file mode 100644 index 000000000..f4680afc3 --- /dev/null +++ b/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.service.spec.ts @@ -0,0 +1,219 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {ReaderPreferencesService} from './reader-preferences.service'; +import {CbxFitMode, CbxPageSpread, CbxPageViewMode, PdfPageSpread, PdfPageViewMode, User, UserService} from '../user-management/user.service'; +import {MessageService} from 'primeng/api'; +import {of, Subject} from 'rxjs'; + +const mockUser: User = { + id: 1, + username: 'testuser', + name: 'Test User', + email: 'test@example.com', + assignedLibraries: [], + permissions: { + admin: true, + canUpload: true, + canDownload: true, + canEmailBook: true, + canDeleteBook: true, + canEditMetadata: true, + canManageLibrary: true, + canManageMetadataConfig: true, + canSyncKoReader: true, + canSyncKobo: true, + canAccessOpds: true, + canAccessBookdrop: true, + canAccessLibraryStats: true, + canAccessUserStats: true, + canAccessTaskManager: true, + canManageEmailConfig: true, + canManageGlobalPreferences: true, + canManageIcons: true, + demoUser: false, + canBulkAutoFetchMetadata: true, + canBulkCustomFetchMetadata: true, + canBulkEditMetadata: true, + canBulkRegenerateCover: true, + canMoveOrganizeFiles: true, + canBulkLockUnlockMetadata: true + }, + userSettings: { + perBookSetting: {pdf: '', epub: '', cbx: ''}, + pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false}, + epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1}, + cbxReaderSetting: { + pageSpread: CbxPageSpread.EVEN, + pageViewMode: CbxPageViewMode.SINGLE_PAGE, + fitMode: CbxFitMode.ACTUAL_SIZE + }, + newPdfReaderSetting: { + pageSpread: PdfPageSpread.EVEN, + pageViewMode: PdfPageViewMode.SINGLE_PAGE + }, + sidebarLibrarySorting: {field: '', order: ''}, + sidebarShelfSorting: {field: '', order: ''}, + sidebarMagicShelfSorting: {field: '', order: ''}, + filterMode: 'and', + filterSortingMode: 'alphabetical', + metadataCenterViewMode: 'route', + enableSeriesView: true, + entityViewPreferences: { + global: {sortKey: '', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false}, + overrides: [] + }, + koReaderEnabled: false + } +}; + +describe('ReaderPreferencesService', () => { + let service: ReaderPreferencesService; + let userServiceMock: any; + let messageServiceMock: any; + let destroy$: Subject; + + beforeEach(() => { + destroy$ = new Subject(); + userServiceMock = { + userState$: of({user: mockUser, loaded: true}), + updateUserSetting: vi.fn() + }; + messageServiceMock = { + add: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + ReaderPreferencesService, + {provide: UserService, useValue: userServiceMock}, + {provide: MessageService, useValue: messageServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(ReaderPreferencesService)); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); + + it('should set currentUser from userService', () => { + // @ts-ignore + expect(service.currentUser).toEqual(mockUser); + }); + + it('should update preference and call updateUserSetting', () => { + const path = ['cbxReaderSetting', 'fitMode']; + const value = CbxFitMode.FIT_PAGE; + service['currentUser'] = JSON.parse(JSON.stringify(mockUser)); + service.updatePreference(path, value); + expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith( + mockUser.id, + 'cbxReaderSetting', + expect.objectContaining({fitMode: value}) + ); + expect(messageServiceMock.add).toHaveBeenCalledWith( + expect.objectContaining({severity: 'success'}) + ); + }); + + it('should update nested preference', () => { + const path = ['entityViewPreferences', 'global', 'sortKey']; + const value = 'title'; + service['currentUser'] = JSON.parse(JSON.stringify(mockUser)); + service.updatePreference(path, value); + expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith( + mockUser.id, + 'entityViewPreferences', + expect.objectContaining({ + global: expect.objectContaining({sortKey: value}) + }) + ); + expect(messageServiceMock.add).toHaveBeenCalled(); + }); + + it('should not update if currentUser is null', () => { + service['currentUser'] = null; + service.updatePreference(['cbxReaderSetting', 'fitMode'], CbxFitMode.FIT_PAGE); + expect(userServiceMock.updateUserSetting).not.toHaveBeenCalled(); + expect(messageServiceMock.add).not.toHaveBeenCalled(); + }); + + it('should clean up on destroy', () => { + const spy = vi.spyOn(service['destroy$'], 'next'); + service.ngOnDestroy(); + expect(spy).toHaveBeenCalled(); + }); +}); + +describe('ReaderPreferencesService - API Contract Tests', () => { + let service: ReaderPreferencesService; + let userServiceMock: any; + let messageServiceMock: any; + + beforeEach(() => { + userServiceMock = { + userState$: of({user: mockUser, loaded: true}), + updateUserSetting: vi.fn() + }; + messageServiceMock = { + add: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + ReaderPreferencesService, + {provide: UserService, useValue: userServiceMock}, + {provide: MessageService, useValue: messageServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(ReaderPreferencesService)); + }); + + it('should call updateUserSetting with correct arguments for root-level setting', () => { + const path = ['koReaderEnabled']; + const value = true; + service['currentUser'] = JSON.parse(JSON.stringify(mockUser)); + service.updatePreference(path, value); + expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith( + mockUser.id, + 'koReaderEnabled', + value + ); + }); + + it('should call updateUserSetting with correct arguments for nested setting', () => { + const path = ['pdfReaderSetting', 'pageZoom']; + const value = '150%'; + service['currentUser'] = JSON.parse(JSON.stringify(mockUser)); + service.updatePreference(path, value); + expect(userServiceMock.updateUserSetting).toHaveBeenCalledWith( + mockUser.id, + 'pdfReaderSetting', + expect.objectContaining({pageZoom: value}) + ); + }); + + it('should show success message after updating preference', () => { + const path = ['epubReaderSetting', 'fontSize']; + const value = 18; + service['currentUser'] = JSON.parse(JSON.stringify(mockUser)); + service.updatePreference(path, value); + expect(messageServiceMock.add).toHaveBeenCalledWith( + expect.objectContaining({ + severity: 'success', + summary: 'Preferences Updated' + }) + ); + }); + + it('should not throw if path is empty', () => { + service['currentUser'] = JSON.parse(JSON.stringify(mockUser)); + expect(() => service.updatePreference([], 'value')).not.toThrow(); + }); +}); + diff --git a/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences-service.ts b/booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.service.ts similarity index 100% rename from booklore-ui/src/app/features/settings/reader-preferences/reader-preferences-service.ts rename to booklore-ui/src/app/features/settings/reader-preferences/reader-preferences.service.ts diff --git a/booklore-ui/src/app/features/settings/task-management/task-helper.service.spec.ts b/booklore-ui/src/app/features/settings/task-management/task-helper.service.spec.ts new file mode 100644 index 000000000..ca3e34b68 --- /dev/null +++ b/booklore-ui/src/app/features/settings/task-management/task-helper.service.spec.ts @@ -0,0 +1,136 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {of, throwError} from 'rxjs'; +import {TaskHelperService} from './task-helper.service'; +import {TaskCreateRequest, TaskService, TaskType} from './task.service'; +import {MessageService} from 'primeng/api'; +import {MetadataRefreshRequest} from '../../metadata/model/request/metadata-refresh-request.model'; +import {MetadataRefreshType} from '../../metadata/model/request/metadata-refresh-type.enum'; + +describe('TaskHelperService', () => { + let service: TaskHelperService; + let taskServiceMock: any; + let messageServiceMock: any; + + beforeEach(() => { + taskServiceMock = { + startTask: vi.fn() + }; + messageServiceMock = { + add: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + TaskHelperService, + {provide: TaskService, useValue: taskServiceMock}, + {provide: MessageService, useValue: messageServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(TaskHelperService)); + }); + + it('should schedule metadata refresh and show success message', () => { + taskServiceMock.startTask.mockReturnValue(of({})); + const options: MetadataRefreshRequest = {refreshType: MetadataRefreshType.BOOKS, bookIds: [1, 2]}; + service.refreshMetadataTask(options).subscribe(result => { + expect(result).toEqual({success: true}); + expect(taskServiceMock.startTask).toHaveBeenCalledWith({ + taskType: TaskType.REFRESH_METADATA_MANUAL, + options + }); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'success', + summary: 'Metadata Update Scheduled' + })); + }); + }); + + it('should show error message if task already running (409)', () => { + taskServiceMock.startTask.mockReturnValue(throwError(() => ({status: 409}))); + const options: MetadataRefreshRequest = {refreshType: MetadataRefreshType.BOOKS, bookIds: [1]}; + service.refreshMetadataTask(options).subscribe(result => { + expect(result).toEqual({success: false}); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'error', + summary: 'Task Already Running' + })); + }); + }); + + it('should show generic error message for other errors', () => { + taskServiceMock.startTask.mockReturnValue(throwError(() => ({status: 500}))); + const options: MetadataRefreshRequest = {refreshType: MetadataRefreshType.BOOKS, bookIds: [1]}; + service.refreshMetadataTask(options).subscribe(result => { + expect(result).toEqual({success: false}); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'error', + summary: 'Metadata Update Failed' + })); + }); + }); +}); + +describe('TaskHelperService - API Contract Tests', () => { + let service: TaskHelperService; + let taskServiceMock: any; + let messageServiceMock: any; + + beforeEach(() => { + taskServiceMock = { + startTask: vi.fn() + }; + messageServiceMock = { + add: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + TaskHelperService, + {provide: TaskService, useValue: taskServiceMock}, + {provide: MessageService, useValue: messageServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(TaskHelperService)); + }); + + it('should send TaskCreateRequest with correct structure', () => { + taskServiceMock.startTask.mockReturnValue(of({})); + const options: MetadataRefreshRequest = {refreshType: MetadataRefreshType.BOOKS, bookIds: [1, 2, 3]}; + service.refreshMetadataTask(options).subscribe(() => { + const req: TaskCreateRequest = taskServiceMock.startTask.mock.calls[0][0]; + expect(req).toHaveProperty('taskType', TaskType.REFRESH_METADATA_MANUAL); + expect(req).toHaveProperty('options', options); + }); + }); + + it('should expect {success: true} on success', () => { + taskServiceMock.startTask.mockReturnValue(of({})); + service.refreshMetadataTask({refreshType: MetadataRefreshType.BOOKS, bookIds: [1]}).subscribe(result => { + expect(result).toEqual({success: true}); + }); + }); + + it('should expect {success: false} on error', () => { + taskServiceMock.startTask.mockReturnValue(throwError(() => ({status: 409}))); + service.refreshMetadataTask({refreshType: MetadataRefreshType.BOOKS, bookIds: [1]}).subscribe(result => { + expect(result).toEqual({success: false}); + }); + }); + + it('should call MessageService.add with correct contract', () => { + taskServiceMock.startTask.mockReturnValue(of({})); + service.refreshMetadataTask({refreshType: MetadataRefreshType.BOOKS, bookIds: [1]}).subscribe(() => { + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'success', + summary: expect.any(String), + detail: expect.any(String) + })); + }); + }); +}); diff --git a/booklore-ui/src/app/features/settings/task-management/task.service.spec.ts b/booklore-ui/src/app/features/settings/task-management/task.service.spec.ts new file mode 100644 index 000000000..3fad4fe49 --- /dev/null +++ b/booklore-ui/src/app/features/settings/task-management/task.service.spec.ts @@ -0,0 +1,338 @@ +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 { + TaskService, + TaskType, + TASK_TYPE_CONFIG, + TaskCreateRequest, + TaskCreateResponse, + TaskStatusResponse, + TaskStatus, + TaskCancelResponse, + TaskInfo, + TaskHistory, + CronConfig, + TaskCronConfigRequest, + TaskProgressPayload, + MetadataReplaceMode +} from './task.service'; + +describe('TaskService', () => { + let service: TaskService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + patch: vi.fn(), + delete: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + TaskService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(TaskService)); + }); + + it('should get available tasks', () => { + const mockTasks: TaskInfo[] = [ + { + taskType: TaskType.REFRESH_LIBRARY_METADATA, + name: 'Refresh Metadata', + description: 'desc', + parallel: false, + async: true, + cronSupported: true, + cronConfig: null + } + ]; + httpClientMock.get.mockReturnValue(of(mockTasks)); + service.getAvailableTasks().subscribe(tasks => { + expect(tasks).toEqual(mockTasks); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/api/v1/tasks')); + }); + }); + + it('should start a task', () => { + const req: TaskCreateRequest = {taskType: TaskType.REFRESH_LIBRARY_METADATA}; + const resp: TaskCreateResponse = {id: '1', type: TaskType.REFRESH_LIBRARY_METADATA, status: TaskStatus.ACCEPTED}; + httpClientMock.post.mockReturnValue(of(resp)); + service.startTask(req).subscribe(result => { + expect(result).toEqual(resp); + expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringContaining('/start'), req); + }); + }); + + it('should get latest tasks for each type', () => { + const resp: TaskStatusResponse = {taskHistories: []}; + httpClientMock.get.mockReturnValue(of(resp)); + service.getLatestTasksForEachType().subscribe(result => { + expect(result).toEqual(resp); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/last')); + }); + }); + + it('should cancel a task', () => { + const resp: TaskCancelResponse = {taskId: '1', cancelled: true, message: 'Cancelled'}; + httpClientMock.delete.mockReturnValue(of(resp)); + service.cancelTask('1').subscribe(result => { + expect(result).toEqual(resp); + expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1/cancel')); + }); + }); + + it('should update cron config', () => { + const req: TaskCronConfigRequest = {cronExpression: '* * * * *', enabled: true}; + const resp: CronConfig = { + id: 1, + taskType: TaskType.REFRESH_LIBRARY_METADATA, + cronExpression: '* * * * *', + enabled: true, + options: null, + createdAt: null, + updatedAt: null + }; + httpClientMock.patch.mockReturnValue(of(resp)); + service.updateCronConfig(TaskType.REFRESH_LIBRARY_METADATA, req).subscribe(result => { + expect(result).toEqual(resp); + expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringContaining(`/${TaskType.REFRESH_LIBRARY_METADATA}/cron`), req); + }); + }); + + it('should handle task progress subject', () => { + const progress: TaskProgressPayload = { + taskId: '1', + taskType: TaskType.REFRESH_LIBRARY_METADATA, + message: 'Running', + progress: 50, + taskStatus: TaskStatus.IN_PROGRESS + }; + let emitted: TaskProgressPayload | null = null; + service.taskProgress$.subscribe(val => emitted = val); + service.handleTaskProgress(progress); + expect(emitted).toEqual(progress); + }); +}); + +describe('TaskService - API Contract Tests', () => { + let service: TaskService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + patch: vi.fn(), + delete: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + TaskService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(TaskService)); + }); + + describe('TaskInfo interface contract', () => { + it('should validate all required TaskInfo fields exist', () => { + const requiredFields: (keyof TaskInfo)[] = [ + 'taskType', 'name', 'description', 'parallel', 'async', 'cronSupported', 'cronConfig' + ]; + const mockResponse: TaskInfo = { + taskType: TaskType.REFRESH_LIBRARY_METADATA, + name: 'Refresh', + description: 'desc', + parallel: false, + async: true, + cronSupported: true, + cronConfig: null + }; + httpClientMock.get.mockReturnValue(of([mockResponse])); + service.getAvailableTasks().subscribe(tasks => { + requiredFields.forEach(field => { + expect(tasks[0]).toHaveProperty(field); + }); + }); + }); + }); + + describe('TaskHistory interface contract', () => { + it('should validate all required TaskHistory fields exist', () => { + const requiredFields: (keyof TaskHistory)[] = [ + 'id', 'type', 'status', 'progressPercentage', 'message', 'createdAt', 'updatedAt', 'completedAt' + ]; + const mockHistory: TaskHistory = { + id: '1', + type: TaskType.REFRESH_LIBRARY_METADATA, + status: TaskStatus.COMPLETED, + progressPercentage: 100, + message: 'Done', + createdAt: 'now', + updatedAt: 'now', + completedAt: 'now' + }; + httpClientMock.get.mockReturnValue(of({taskHistories: [mockHistory]})); + service.getLatestTasksForEachType().subscribe(resp => { + requiredFields.forEach(field => { + expect(resp.taskHistories[0]).toHaveProperty(field); + }); + }); + }); + }); + + describe('Enum value contract', () => { + it('should validate TaskType enum values', () => { + const values = Object.values(TaskType); + expect(values).toContain('CLEAR_CBX_CACHE'); + expect(values).toContain('REFRESH_LIBRARY_METADATA'); + expect(values).toContain('REFRESH_METADATA_MANUAL'); + }); + + it('should validate TaskStatus enum values', () => { + const values = Object.values(TaskStatus); + expect(values).toContain('ACCEPTED'); + expect(values).toContain('IN_PROGRESS'); + expect(values).toContain('COMPLETED'); + expect(values).toContain('FAILED'); + expect(values).toContain('CANCELLED'); + expect(values).toContain('PENDING'); + }); + + it('should validate MetadataReplaceMode enum values', () => { + const values = Object.values(MetadataReplaceMode); + expect(values).toContain('REPLACE_ALL'); + expect(values).toContain('REPLACE_MISSING'); + }); + }); + + describe('HTTP endpoint contract', () => { + it('should call correct endpoint for getAvailableTasks', () => { + httpClientMock.get.mockReturnValue(of([])); + service.getAvailableTasks().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/tasks$/)); + }); + + it('should call correct endpoint for startTask', () => { + httpClientMock.post.mockReturnValue(of({})); + const req: TaskCreateRequest = {taskType: TaskType.CLEAR_CBX_CACHE}; + service.startTask(req).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/tasks\/start$/), req); + }); + + it('should call correct endpoint for getLatestTasksForEachType', () => { + httpClientMock.get.mockReturnValue(of({})); + service.getLatestTasksForEachType().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/tasks\/last$/)); + }); + + it('should call correct endpoint for cancelTask', () => { + httpClientMock.delete.mockReturnValue(of({})); + service.cancelTask('abc').subscribe(); + expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/tasks\/abc\/cancel$/)); + }); + + it('should call correct endpoint for updateCronConfig', () => { + httpClientMock.patch.mockReturnValue(of({})); + const req: TaskCronConfigRequest = {enabled: true}; + service.updateCronConfig(TaskType.CLEAR_PDF_CACHE, req).subscribe(); + expect(httpClientMock.patch).toHaveBeenCalledWith(expect.stringMatching(new RegExp(`/api/v1/tasks/${TaskType.CLEAR_PDF_CACHE}/cron$`)), req); + }); + }); + + describe('Request payload contract', () => { + it('should send TaskCreateRequest with correct structure', () => { + httpClientMock.post.mockReturnValue(of({})); + const req: TaskCreateRequest = {taskType: TaskType.CLEAR_CBX_CACHE, options: {metadataReplaceMode: MetadataReplaceMode.REPLACE_ALL}}; + service.startTask(req).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req); + }); + + it('should send TaskCronConfigRequest with correct structure', () => { + httpClientMock.patch.mockReturnValue(of({})); + const req: TaskCronConfigRequest = {cronExpression: '0 0 * * *', enabled: false}; + service.updateCronConfig(TaskType.CLEAR_CBX_CACHE, req).subscribe(); + expect(httpClientMock.patch).toHaveBeenCalledWith(expect.any(String), req); + }); + }); + + describe('Response type contract', () => { + it('should expect TaskInfo[] from getAvailableTasks', () => { + const mock: TaskInfo[] = [{ + taskType: TaskType.CLEAR_CBX_CACHE, + name: 'Clear CBX', + description: 'desc', + parallel: false, + async: false, + cronSupported: false, + cronConfig: null + }]; + httpClientMock.get.mockReturnValue(of(mock)); + service.getAvailableTasks().subscribe(tasks => { + expect(Array.isArray(tasks)).toBe(true); + expect(tasks[0]).toHaveProperty('taskType'); + }); + }); + + it('should expect TaskCreateResponse from startTask', () => { + const resp: TaskCreateResponse = {id: '1', type: TaskType.CLEAR_CBX_CACHE, status: TaskStatus.ACCEPTED}; + httpClientMock.post.mockReturnValue(of(resp)); + service.startTask({taskType: TaskType.CLEAR_CBX_CACHE}).subscribe(result => { + expect(result).toHaveProperty('id'); + expect(result).toHaveProperty('type'); + expect(result).toHaveProperty('status'); + }); + }); + + it('should expect TaskStatusResponse from getLatestTasksForEachType', () => { + const resp: TaskStatusResponse = {taskHistories: []}; + httpClientMock.get.mockReturnValue(of(resp)); + service.getLatestTasksForEachType().subscribe(result => { + expect(result).toHaveProperty('taskHistories'); + expect(Array.isArray(result.taskHistories)).toBe(true); + }); + }); + + it('should expect TaskCancelResponse from cancelTask', () => { + const resp: TaskCancelResponse = {taskId: '1', cancelled: true, message: 'msg'}; + httpClientMock.delete.mockReturnValue(of(resp)); + service.cancelTask('1').subscribe(result => { + expect(result).toHaveProperty('taskId'); + expect(result).toHaveProperty('cancelled'); + expect(result).toHaveProperty('message'); + }); + }); + + it('should expect CronConfig from updateCronConfig', () => { + const resp: CronConfig = { + id: 1, + taskType: TaskType.CLEAR_CBX_CACHE, + cronExpression: '* * * * *', + enabled: true, + options: null, + createdAt: null, + updatedAt: null + }; + httpClientMock.patch.mockReturnValue(of(resp)); + service.updateCronConfig(TaskType.CLEAR_CBX_CACHE, {enabled: true}).subscribe(result => { + expect(result).toHaveProperty('id'); + expect(result).toHaveProperty('taskType'); + expect(result).toHaveProperty('enabled'); + }); + }); + }); +}); + diff --git a/booklore-ui/src/app/features/settings/user-management/user.service.spec.ts b/booklore-ui/src/app/features/settings/user-management/user.service.spec.ts new file mode 100644 index 000000000..b3bae27bc --- /dev/null +++ b/booklore-ui/src/app/features/settings/user-management/user.service.spec.ts @@ -0,0 +1,936 @@ +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 { + CbxFitMode, + CbxPageSpread, + CbxPageViewMode, + PdfPageSpread, + PdfPageViewMode, + User, + UserService, + UserUpdateRequest +} from './user.service'; +import {AuthService} from '../../../shared/service/auth.service'; + +describe('UserService', () => { + let service: UserService; + let httpClientMock: any; + let authServiceMock: any; + + const mockUser: User = { + id: 1, + username: 'testuser', + name: 'Test User', + email: 'test@example.com', + assignedLibraries: [], + permissions: { + admin: true, + canUpload: true, + canDownload: true, + canEmailBook: true, + canDeleteBook: true, + canEditMetadata: true, + canManageLibrary: true, + canManageMetadataConfig: true, + canSyncKoReader: true, + canSyncKobo: true, + canAccessOpds: true, + canAccessBookdrop: true, + canAccessLibraryStats: true, + canAccessUserStats: true, + canAccessTaskManager: true, + canManageEmailConfig: true, + canManageGlobalPreferences: true, + canManageIcons: true, + demoUser: false, + canBulkAutoFetchMetadata: true, + canBulkCustomFetchMetadata: true, + canBulkEditMetadata: true, + canBulkRegenerateCover: true, + canMoveOrganizeFiles: true, + canBulkLockUnlockMetadata: true + }, + userSettings: { + perBookSetting: {pdf: '', epub: '', cbx: ''}, + pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false}, + epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1}, + cbxReaderSetting: { + pageSpread: CbxPageSpread.EVEN, + pageViewMode: CbxPageViewMode.SINGLE_PAGE, + fitMode: CbxFitMode.ACTUAL_SIZE + }, + newPdfReaderSetting: { + pageSpread: PdfPageSpread.EVEN, + pageViewMode: PdfPageViewMode.SINGLE_PAGE + }, + sidebarLibrarySorting: {field: '', order: ''}, + sidebarShelfSorting: {field: '', order: ''}, + sidebarMagicShelfSorting: {field: '', order: ''}, + filterMode: 'and', + filterSortingMode: 'alphabetical', + metadataCenterViewMode: 'route', + enableSeriesView: true, + entityViewPreferences: { + global: {sortKey: '', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false}, + overrides: [] + }, + koReaderEnabled: false + } + }; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn() + }; + + authServiceMock = { + token$: of('token') + }; + + TestBed.configureTestingModule({ + providers: [ + UserService, + {provide: HttpClient, useValue: httpClientMock}, + {provide: AuthService, useValue: authServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + + service = runInInjectionContext( + injector, + () => TestBed.inject(UserService) + ); + }); + + it('should initialize with default state', () => { + expect(service.userStateSubject.value).toEqual({ + user: null, + loaded: false, + error: null + }); + }); + + it('should set initial user', () => { + service.setInitialUser(mockUser); + expect(service.userStateSubject.value.user).toEqual(mockUser); + expect(service.userStateSubject.value.loaded).toBe(true); + }); + + it('should get current user', () => { + service.setInitialUser(mockUser); + expect(service.getCurrentUser()).toEqual(mockUser); + }); + + it('should fetch myself and update state', () => { + httpClientMock.get.mockReturnValue(of(mockUser)); + service['fetchMyself']().subscribe(user => { + expect(user).toEqual(mockUser); + expect(service.userStateSubject.value.user).toEqual(mockUser); + expect(service.userStateSubject.value.loaded).toBe(true); + }); + }); + + it('should handle fetch myself error', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service['fetchMyself']().subscribe({ + error: (err: any) => { + expect(service.userStateSubject.value.error).toBe('fail'); + expect(err).toBeInstanceOf(Error); + } + }); + }); + + it('should get myself via getMyself()', () => { + httpClientMock.get.mockReturnValue(of(mockUser)); + service.getMyself().subscribe(user => { + expect(user).toEqual(mockUser); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/me')); + }); + }); + + it('should create user', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + const {id, ...userData} = mockUser; + service.createUser(userData).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.post).toHaveBeenCalled(); + }); + }); + + it('should get users', () => { + httpClientMock.get.mockReturnValue(of([mockUser])); + service.getUsers().subscribe(users => { + expect(users).toEqual([mockUser]); + expect(httpClientMock.get).toHaveBeenCalled(); + }); + }); + + it('should update user', () => { + httpClientMock.put.mockReturnValue(of(mockUser)); + const update: UserUpdateRequest = {name: 'New Name'}; + service.updateUser(1, update).subscribe(user => { + expect(user).toEqual(mockUser); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/1'), update); + }); + }); + + it('should delete user', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteUser(1).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1')); + }); + }); + + it('should change user password', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service.changeUserPassword(1, 'newpass').subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('change-user-password'), {userId: 1, newPassword: 'newpass'}); + }); + }); + + it('should handle change user password error', () => { + httpClientMock.put.mockReturnValue(throwError(() => ({error: {message: 'bad'}}))); + service.changeUserPassword(1, 'badpass').subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('bad'); + } + }); + }); + + it('should change password', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service.changePassword('old', 'new').subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('change-password'), {currentPassword: 'old', newPassword: 'new'}); + }); + }); + + it('should handle change password error', () => { + httpClientMock.put.mockReturnValue(throwError(() => ({error: {message: 'fail'}}))); + service.changePassword('old', 'bad').subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should update user setting and update state', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service.setInitialUser(mockUser); + service.updateUserSetting(1, 'koReaderEnabled', true); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/1/settings'), {key: 'koReaderEnabled', value: true}, expect.anything()); + expect(service.userStateSubject.value.user?.userSettings.koReaderEnabled).toBe(true); + }); +}); + +describe('UserService - API Contract Tests', () => { + let service: UserService; + let httpClientMock: any; + let authServiceMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn() + }; + + authServiceMock = { + token$: of('token') + }; + + TestBed.configureTestingModule({ + providers: [ + UserService, + {provide: HttpClient, useValue: httpClientMock}, + {provide: AuthService, useValue: authServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(UserService)); + }); + + describe('User interface contract', () => { + it('should validate all required User fields exist', () => { + const requiredFields: (keyof User)[] = [ + 'id', 'username', 'name', 'email', 'assignedLibraries', 'permissions', 'userSettings' + ]; + + const mockResponse: User = { + id: 1, + username: 'test', + name: 'Test', + email: 'test@test.com', + assignedLibraries: [], + permissions: { + admin: false, + canUpload: false, + canDownload: false, + canEmailBook: false, + canDeleteBook: false, + canEditMetadata: false, + canManageLibrary: false, + canManageMetadataConfig: false, + canSyncKoReader: false, + canSyncKobo: false, + canAccessOpds: false, + canAccessBookdrop: false, + canAccessLibraryStats: false, + canAccessUserStats: false, + canAccessTaskManager: false, + canManageEmailConfig: false, + canManageGlobalPreferences: false, + canManageIcons: false, + demoUser: false, + canBulkAutoFetchMetadata: false, + canBulkCustomFetchMetadata: false, + canBulkEditMetadata: false, + canBulkRegenerateCover: false, + canMoveOrganizeFiles: false, + canBulkLockUnlockMetadata: false + }, + userSettings: { + perBookSetting: {pdf: '', epub: '', cbx: ''}, + pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false}, + epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1}, + cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE}, + newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE}, + sidebarLibrarySorting: {field: '', order: ''}, + sidebarShelfSorting: {field: '', order: ''}, + sidebarMagicShelfSorting: {field: '', order: ''}, + filterMode: 'and', + filterSortingMode: 'alphabetical', + metadataCenterViewMode: 'route', + enableSeriesView: true, + entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []}, + koReaderEnabled: false + } + }; + + httpClientMock.get.mockReturnValue(of(mockResponse)); + + service.getMyself().subscribe(user => { + requiredFields.forEach(field => { + expect(user).toHaveProperty(field); + expect(user[field]).toBeDefined(); + }); + }); + }); + + it('should validate all required Permission fields exist', () => { + const requiredPermissions = [ + 'admin', 'canUpload', 'canDownload', 'canEmailBook', 'canDeleteBook', + 'canEditMetadata', 'canManageLibrary', 'canManageMetadataConfig', + 'canSyncKoReader', 'canSyncKobo', 'canAccessOpds', 'canAccessBookdrop', + 'canAccessLibraryStats', 'canAccessUserStats', 'canAccessTaskManager', + 'canManageEmailConfig', 'canManageGlobalPreferences', 'canManageIcons', + 'demoUser', 'canBulkAutoFetchMetadata', 'canBulkCustomFetchMetadata', + 'canBulkEditMetadata', 'canBulkRegenerateCover', 'canMoveOrganizeFiles', + 'canBulkLockUnlockMetadata' + ]; + + const mockResponse: User = { + id: 1, + username: 'test', + name: 'Test', + email: 'test@test.com', + assignedLibraries: [], + permissions: { + admin: true, + canUpload: true, + canDownload: true, + canEmailBook: true, + canDeleteBook: true, + canEditMetadata: true, + canManageLibrary: true, + canManageMetadataConfig: true, + canSyncKoReader: true, + canSyncKobo: true, + canAccessOpds: true, + canAccessBookdrop: true, + canAccessLibraryStats: true, + canAccessUserStats: true, + canAccessTaskManager: true, + canManageEmailConfig: true, + canManageGlobalPreferences: true, + canManageIcons: true, + demoUser: false, + canBulkAutoFetchMetadata: true, + canBulkCustomFetchMetadata: true, + canBulkEditMetadata: true, + canBulkRegenerateCover: true, + canMoveOrganizeFiles: true, + canBulkLockUnlockMetadata: true + }, + userSettings: { + perBookSetting: {pdf: '', epub: '', cbx: ''}, + pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false}, + epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1}, + cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE}, + newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE}, + sidebarLibrarySorting: {field: '', order: ''}, + sidebarShelfSorting: {field: '', order: ''}, + sidebarMagicShelfSorting: {field: '', order: ''}, + filterMode: 'and', + filterSortingMode: 'alphabetical', + metadataCenterViewMode: 'route', + enableSeriesView: true, + entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []}, + koReaderEnabled: false + } + }; + + httpClientMock.get.mockReturnValue(of(mockResponse)); + + service.getMyself().subscribe(user => { + requiredPermissions.forEach(permission => { + expect(user.permissions).toHaveProperty(permission); + expect(typeof user.permissions[permission as keyof typeof user.permissions]).toBe('boolean'); + }); + }); + }); + + it('should validate all required UserSettings fields exist', () => { + const requiredSettings = [ + 'perBookSetting', 'pdfReaderSetting', 'epubReaderSetting', 'cbxReaderSetting', + 'newPdfReaderSetting', 'sidebarLibrarySorting', 'sidebarShelfSorting', + 'sidebarMagicShelfSorting', 'filterMode', 'filterSortingMode', + 'metadataCenterViewMode', 'enableSeriesView', 'entityViewPreferences', 'koReaderEnabled' + ]; + + const mockResponse: User = { + id: 1, + username: 'test', + name: 'Test', + email: 'test@test.com', + assignedLibraries: [], + permissions: { + admin: false, + canUpload: false, + canDownload: false, + canEmailBook: false, + canDeleteBook: false, + canEditMetadata: false, + canManageLibrary: false, + canManageMetadataConfig: false, + canSyncKoReader: false, + canSyncKobo: false, + canAccessOpds: false, + canAccessBookdrop: false, + canAccessLibraryStats: false, + canAccessUserStats: false, + canAccessTaskManager: false, + canManageEmailConfig: false, + canManageGlobalPreferences: false, + canManageIcons: false, + demoUser: false, + canBulkAutoFetchMetadata: false, + canBulkCustomFetchMetadata: false, + canBulkEditMetadata: false, + canBulkRegenerateCover: false, + canMoveOrganizeFiles: false, + canBulkLockUnlockMetadata: false + }, + userSettings: { + perBookSetting: {pdf: '', epub: '', cbx: ''}, + pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false}, + epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1}, + cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE}, + newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE}, + sidebarLibrarySorting: {field: '', order: ''}, + sidebarShelfSorting: {field: '', order: ''}, + sidebarMagicShelfSorting: {field: '', order: ''}, + filterMode: 'and', + filterSortingMode: 'alphabetical', + metadataCenterViewMode: 'route', + enableSeriesView: true, + entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []}, + koReaderEnabled: false + } + }; + + httpClientMock.get.mockReturnValue(of(mockResponse)); + + service.getMyself().subscribe(user => { + requiredSettings.forEach(setting => { + expect(user.userSettings).toHaveProperty(setting); + expect(user.userSettings[setting as keyof typeof user.userSettings]).toBeDefined(); + }); + }); + }); + + it('should fail if API returns User without required id field', () => { + const invalidResponse = { + username: 'test', + name: 'Test', + email: 'test@test.com', + assignedLibraries: [], + permissions: {}, + userSettings: {} + }; + + httpClientMock.get.mockReturnValue(of(invalidResponse)); + + service.getMyself().subscribe(user => { + expect(user).not.toHaveProperty('id'); + }); + }); + + it('should fail if API returns User without permissions', () => { + const invalidResponse = { + id: 1, + username: 'test', + name: 'Test', + email: 'test@test.com', + assignedLibraries: [], + userSettings: {} + }; + + httpClientMock.get.mockReturnValue(of(invalidResponse)); + + service.getMyself().subscribe(user => { + expect(user).not.toHaveProperty('permissions'); + }); + }); + + it('should fail if API returns User without userSettings', () => { + const invalidResponse = { + id: 1, + username: 'test', + name: 'Test', + email: 'test@test.com', + assignedLibraries: [], + permissions: {} + }; + + httpClientMock.get.mockReturnValue(of(invalidResponse)); + + service.getMyself().subscribe(user => { + expect(user).not.toHaveProperty('userSettings'); + }); + }); + }); + + describe('Enum value contract', () => { + it('should validate CbxPageSpread enum values from API', () => { + const validValues = [CbxPageSpread.EVEN, CbxPageSpread.ODD]; + expect(validValues).toContain(CbxPageSpread.EVEN); + expect(validValues).toContain(CbxPageSpread.ODD); + expect(Object.keys(CbxPageSpread)).toHaveLength(2); + }); + + it('should validate CbxPageViewMode enum values from API', () => { + const validValues = [CbxPageViewMode.SINGLE_PAGE, CbxPageViewMode.TWO_PAGE]; + expect(validValues).toContain(CbxPageViewMode.SINGLE_PAGE); + expect(validValues).toContain(CbxPageViewMode.TWO_PAGE); + expect(Object.keys(CbxPageViewMode)).toHaveLength(2); + }); + + it('should validate CbxFitMode enum values from API', () => { + const validValues = [ + CbxFitMode.ACTUAL_SIZE, + CbxFitMode.FIT_PAGE, + CbxFitMode.FIT_WIDTH, + CbxFitMode.FIT_HEIGHT, + CbxFitMode.AUTO + ]; + validValues.forEach(value => { + expect(Object.values(CbxFitMode)).toContain(value); + }); + expect(Object.keys(CbxFitMode)).toHaveLength(5); + }); + + it('should validate PdfPageSpread enum values from API', () => { + const validValues = [PdfPageSpread.EVEN, PdfPageSpread.ODD]; + expect(validValues).toContain(PdfPageSpread.EVEN); + expect(validValues).toContain(PdfPageSpread.ODD); + expect(Object.keys(PdfPageSpread)).toHaveLength(2); + }); + + it('should validate PdfPageViewMode enum values from API', () => { + const validValues = [PdfPageViewMode.SINGLE_PAGE, PdfPageViewMode.TWO_PAGE]; + expect(validValues).toContain(PdfPageViewMode.SINGLE_PAGE); + expect(validValues).toContain(PdfPageViewMode.TWO_PAGE); + expect(Object.keys(PdfPageViewMode)).toHaveLength(2); + }); + }); + + describe('HTTP endpoint contract', () => { + it('should call correct endpoint for getMyself', () => { + httpClientMock.get.mockReturnValue(of({})); + service.getMyself().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/users\/me$/)); + }); + + it('should call correct endpoint for getUsers', () => { + httpClientMock.get.mockReturnValue(of([])); + service.getUsers().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/users$/)); + }); + + it('should call correct endpoint for createUser', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + const userData = { + username: 'new', + name: 'New User', + email: 'new@test.com', + assignedLibraries: [], + permissions: { + admin: false, + canUpload: false, + canDownload: false, + canEmailBook: false, + canDeleteBook: false, + canEditMetadata: false, + canManageLibrary: false, + canManageMetadataConfig: false, + canSyncKoReader: false, + canSyncKobo: false, + canAccessOpds: false, + canAccessBookdrop: false, + canAccessLibraryStats: false, + canAccessUserStats: false, + canAccessTaskManager: false, + canManageEmailConfig: false, + canManageGlobalPreferences: false, + canManageIcons: false, + demoUser: false, + canBulkAutoFetchMetadata: false, + canBulkCustomFetchMetadata: false, + canBulkEditMetadata: false, + canBulkRegenerateCover: false, + canMoveOrganizeFiles: false, + canBulkLockUnlockMetadata: false + }, + userSettings: { + perBookSetting: {pdf: '', epub: '', cbx: ''}, + pdfReaderSetting: {pageSpread: 'off' as const, pageZoom: '', showSidebar: false}, + epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1}, + cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE}, + newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE}, + sidebarLibrarySorting: {field: '', order: ''}, + sidebarShelfSorting: {field: '', order: ''}, + sidebarMagicShelfSorting: {field: '', order: ''}, + filterMode: 'and' as const, + filterSortingMode: 'alphabetical' as const, + metadataCenterViewMode: 'route' as const, + enableSeriesView: true, + entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []}, + koReaderEnabled: false + } + }; + service.createUser(userData).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/auth\/register$/), + userData + ); + }); + + it('should call correct endpoint for updateUser', () => { + httpClientMock.put.mockReturnValue(of({})); + service.updateUser(123, {name: 'Updated'}).subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/users\/123$/), + {name: 'Updated'} + ); + }); + + it('should call correct endpoint for deleteUser', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteUser(123).subscribe(); + expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/users\/123$/)); + }); + + it('should call correct endpoint for changeUserPassword', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service.changeUserPassword(123, 'newpass').subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/users\/change-user-password$/), + {userId: 123, newPassword: 'newpass'} + ); + }); + + it('should call correct endpoint for changePassword', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service.changePassword('oldpass', 'newpass').subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/users\/change-password$/), + {currentPassword: 'oldpass', newPassword: 'newpass'} + ); + }); + + it('should call correct endpoint for updateUserSetting', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service.updateUserSetting(123, 'koReaderEnabled', true); + expect(httpClientMock.put).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/users\/123\/settings$/), + {key: 'koReaderEnabled', value: true}, + expect.anything() + ); + }); + }); + + describe('Request payload contract', () => { + it('should send UserUpdateRequest with correct structure', () => { + httpClientMock.put.mockReturnValue(of({})); + const updateRequest: UserUpdateRequest = { + name: 'New Name', + email: 'newemail@test.com', + permissions: { + admin: true, + canUpload: true, + canDownload: true, + canEmailBook: true, + canDeleteBook: true, + canEditMetadata: true, + canManageLibrary: true, + canManageMetadataConfig: true, + canSyncKoReader: true, + canSyncKobo: true, + canAccessOpds: true, + canAccessBookdrop: true, + canAccessLibraryStats: true, + canAccessUserStats: true, + canAccessTaskManager: true, + canManageEmailConfig: true, + canManageGlobalPreferences: true, + canManageIcons: true, + demoUser: false, + canBulkAutoFetchMetadata: true, + canBulkCustomFetchMetadata: true, + canBulkEditMetadata: true, + canBulkRegenerateCover: true, + canMoveOrganizeFiles: true, + canBulkLockUnlockMetadata: true + }, + assignedLibraries: [1, 2, 3] + }; + service.updateUser(1, updateRequest).subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith( + expect.any(String), + updateRequest + ); + }); + + it('should send change password payload with correct structure', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service.changePassword('current', 'new').subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith( + expect.any(String), + {currentPassword: 'current', newPassword: 'new'} + ); + }); + + it('should send change user password payload with correct structure', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service.changeUserPassword(456, 'newpassword').subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith( + expect.any(String), + {userId: 456, newPassword: 'newpassword'} + ); + }); + + it('should send user setting payload with correct structure', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service.updateUserSetting(789, 'enableSeriesView', false); + expect(httpClientMock.put).toHaveBeenCalledWith( + expect.any(String), + {key: 'enableSeriesView', value: false}, + expect.anything() + ); + }); + }); + + describe('Response type contract', () => { + it('should expect User array from getUsers', () => { + const mockUsers: User[] = [{ + id: 1, + username: 'user1', + name: 'User One', + email: 'user1@test.com', + assignedLibraries: [], + permissions: { + admin: false, + canUpload: false, + canDownload: false, + canEmailBook: false, + canDeleteBook: false, + canEditMetadata: false, + canManageLibrary: false, + canManageMetadataConfig: false, + canSyncKoReader: false, + canSyncKobo: false, + canAccessOpds: false, + canAccessBookdrop: false, + canAccessLibraryStats: false, + canAccessUserStats: false, + canAccessTaskManager: false, + canManageEmailConfig: false, + canManageGlobalPreferences: false, + canManageIcons: false, + demoUser: false, + canBulkAutoFetchMetadata: false, + canBulkCustomFetchMetadata: false, + canBulkEditMetadata: false, + canBulkRegenerateCover: false, + canMoveOrganizeFiles: false, + canBulkLockUnlockMetadata: false + }, + userSettings: { + perBookSetting: {pdf: '', epub: '', cbx: ''}, + pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false}, + epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1}, + cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE}, + newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE}, + sidebarLibrarySorting: {field: '', order: ''}, + sidebarShelfSorting: {field: '', order: ''}, + sidebarMagicShelfSorting: {field: '', order: ''}, + filterMode: 'and', + filterSortingMode: 'alphabetical', + metadataCenterViewMode: 'route', + enableSeriesView: true, + entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC', view: 'GRID', coverSize: 1, seriesCollapsed: false}, overrides: []}, + koReaderEnabled: false + } + }]; + + httpClientMock.get.mockReturnValue(of(mockUsers)); + service.getUsers().subscribe(users => { + expect(Array.isArray(users)).toBe(true); + expect(users[0]).toHaveProperty('id'); + expect(users[0]).toHaveProperty('username'); + }); + }); + + it('should expect User from updateUser', () => { + const mockUser: User = { + id: 1, + username: 'updated', + name: 'Updated User', + email: 'updated@test.com', + assignedLibraries: [], + permissions: { + admin: false, + canUpload: false, + canDownload: false, + canEmailBook: false, + canDeleteBook: false, + canEditMetadata: false, + canManageLibrary: false, + canManageMetadataConfig: false, + canSyncKoReader: false, + canSyncKobo: false, + canAccessOpds: false, + canAccessBookdrop: false, + canAccessLibraryStats: false, + canAccessUserStats: false, + canAccessTaskManager: false, + canManageEmailConfig: false, + canManageGlobalPreferences: false, + canManageIcons: false, + demoUser: false, + canBulkAutoFetchMetadata: false, + canBulkCustomFetchMetadata: false, + canBulkEditMetadata: false, + canBulkRegenerateCover: false, + canMoveOrganizeFiles: false, + canBulkLockUnlockMetadata: false + }, + userSettings: { + perBookSetting: {pdf: '', epub: '', cbx: ''}, + pdfReaderSetting: {pageSpread: 'off', pageZoom: '', showSidebar: false}, + epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1}, + cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE}, + newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE}, + sidebarLibrarySorting: {field: '', order: ''}, + sidebarShelfSorting: {field: '', order: ''}, + sidebarMagicShelfSorting: {field: '', order: ''}, + filterMode: 'and', + filterSortingMode: 'alphabetical', + metadataCenterViewMode: 'route', + enableSeriesView: true, + entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []}, + koReaderEnabled: false + } + }; + + httpClientMock.put.mockReturnValue(of(mockUser)); + service.updateUser(1, {name: 'Updated User'}).subscribe(user => { + expect(user).toHaveProperty('id'); + expect(user).toHaveProperty('username'); + expect(user).toHaveProperty('permissions'); + expect(user).toHaveProperty('userSettings'); + }); + }); + + it('should expect void from createUser', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + const userData = { + username: 'new', + name: 'New', + email: 'new@test.com', + assignedLibraries: [], + permissions: { + admin: false, + canUpload: false, + canDownload: false, + canEmailBook: false, + canDeleteBook: false, + canEditMetadata: false, + canManageLibrary: false, + canManageMetadataConfig: false, + canSyncKoReader: false, + canSyncKobo: false, + canAccessOpds: false, + canAccessBookdrop: false, + canAccessLibraryStats: false, + canAccessUserStats: false, + canAccessTaskManager: false, + canManageEmailConfig: false, + canManageGlobalPreferences: false, + canManageIcons: false, + demoUser: false, + canBulkAutoFetchMetadata: false, + canBulkCustomFetchMetadata: false, + canBulkEditMetadata: false, + canBulkRegenerateCover: false, + canMoveOrganizeFiles: false, + canBulkLockUnlockMetadata: false + }, + userSettings: { + perBookSetting: {pdf: '', epub: '', cbx: ''}, + pdfReaderSetting: {pageSpread: 'off' as const, pageZoom: '', showSidebar: false}, + epubReaderSetting: {theme: '', font: '', fontSize: 1, flow: '', spread: '', lineHeight: 1, margin: 1, letterSpacing: 1}, + cbxReaderSetting: {pageSpread: CbxPageSpread.EVEN, pageViewMode: CbxPageViewMode.SINGLE_PAGE, fitMode: CbxFitMode.ACTUAL_SIZE}, + newPdfReaderSetting: {pageSpread: PdfPageSpread.EVEN, pageViewMode: PdfPageViewMode.SINGLE_PAGE}, + sidebarLibrarySorting: {field: '', order: ''}, + sidebarShelfSorting: {field: '', order: ''}, + sidebarMagicShelfSorting: {field: '', order: ''}, + filterMode: 'and' as const, + filterSortingMode: 'alphabetical' as const, + metadataCenterViewMode: 'route' as const, + enableSeriesView: true, + entityViewPreferences: {global: {sortKey: '', sortDir: 'ASC' as const, view: 'GRID' as const, coverSize: 1, seriesCollapsed: false}, overrides: []}, + koReaderEnabled: false + } + }; + service.createUser(userData).subscribe(result => { + expect(result).toBeUndefined(); + }); + }); + }); +}); diff --git a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.ts b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.ts index 5ed28e33d..5bde5a05d 100644 --- a/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.ts +++ b/booklore-ui/src/app/shared/layout/component/layout-menu/app.menuitem.component.ts @@ -10,7 +10,7 @@ import {Button} from 'primeng/button'; import {Menu} from 'primeng/menu'; import {UserService} from '../../../../features/settings/user-management/user.service'; import {DialogLauncherService} from '../../../services/dialog-launcher.service'; -import {BookDialogHelperService} from '../../../../features/book/components/book-browser/BookDialogHelperService'; +import {BookDialogHelperService} from '../../../../features/book/components/book-browser/book-dialog-helper.service'; import {IconDisplayComponent} from '../../../components/icon-display/icon-display.component'; import {MenuItem} from 'primeng/api'; import {IconSelection} from '../../../service/icon-picker.service'; From 6a7b75d042d4430c67e27357ae4dff3bc3abc63f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= <127139797+balazs-szucs@users.noreply.github.com> Date: Tue, 6 Jan 2026 18:11:02 +0100 Subject: [PATCH 14/40] feat(series-page): implement multi-select functionality for book selection and add footer actions (#2167) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Balázs Szücs --- .../series-page/series-page.component.html | 116 ++++++++- .../series-page/series-page.component.scss | 44 ++++ .../series-page/series-page.component.ts | 234 +++++++++++++++++- 3 files changed, 382 insertions(+), 12 deletions(-) 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 ae144e5c3..b2439c9c0 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 @@ -1,5 +1,5 @@ @if (filteredBooks$ | async; as books) { -
+
@@ -98,8 +98,14 @@ @for (book of books; track book; let i = $index) {
- +
} @@ -117,6 +123,108 @@
+@if (selectedBooks.size > 0) { + @if (userService.userState$ | async; as userState) { + + } +}
} @else { @@ -127,4 +235,4 @@ Loading series details...

-} +} \ No newline at end of file diff --git a/booklore-ui/src/app/features/book/components/series-page/series-page.component.scss b/booklore-ui/src/app/features/book/components/series-page/series-page.component.scss index 0552f4ba6..6e635bcc1 100644 --- a/booklore-ui/src/app/features/book/components/series-page/series-page.component.scss +++ b/booklore-ui/src/app/features/book/components/series-page/series-page.component.scss @@ -16,3 +16,47 @@ width: 100%; } +.book-browser-footer { + position: absolute; + bottom: 0; + left: 10%; + right: 10%; + display: flex; + align-items: center; + padding: 1rem 0.5rem 0.5rem; + z-index: 1; + border-radius: 10px 10px 0 0; + border: 1px solid rgba(255, 255, 255, 0.5); + border-width: 1px 1px 0px 1px; + + > .flex { + width: 100%; + } +} + +.selected-count-badge { + display: inline-flex; + align-items: center; + padding: 0.5rem 1rem; + font-size: 0.9rem; + + i { + font-size: 1rem; + } +} + +@media (max-width: 768px) { + .book-browser-footer { + left: 0%; + right: 0%; + } + + .selected-count-badge { + padding: 0.4rem 0.8rem; + font-size: 0.85rem; + + i { + font-size: 0.9rem; + } + } +} \ No newline at end of file diff --git a/booklore-ui/src/app/features/book/components/series-page/series-page.component.ts b/booklore-ui/src/app/features/book/components/series-page/series-page.component.ts index c8f8f132f..a25fae526 100644 --- a/booklore-ui/src/app/features/book/components/series-page/series-page.component.ts +++ b/booklore-ui/src/app/features/book/components/series-page/series-page.component.ts @@ -1,10 +1,10 @@ -import { Component, inject, ViewChild } from "@angular/core"; +import { Component, inject, OnDestroy } from "@angular/core"; import { FormsModule } from "@angular/forms"; import { Button } from "primeng/button"; import { ActivatedRoute } from "@angular/router"; import { AsyncPipe, NgClass, NgStyle } from "@angular/common"; -import { map, filter, switchMap } from "rxjs/operators"; -import { Observable, combineLatest } from "rxjs"; +import { map, filter, switchMap, tap } from "rxjs/operators"; +import { Observable, combineLatest, Subscription } from "rxjs"; import { Book, ReadStatus } from "../../model/book.model"; import { BookService } from "../../service/book.service"; import { BookCardComponent } from "../book-browser/book-card/book-card.component"; @@ -15,6 +15,18 @@ import { VirtualScrollerModule } from "@iharbeck/ngx-virtual-scroller"; import { ProgressSpinner } from "primeng/progressspinner"; import { DynamicDialogRef } from "primeng/dynamicdialog"; import { Router } from "@angular/router"; +import { ConfirmationService, MenuItem, MessageService } from "primeng/api"; +import { UserService } from "../../../settings/user-management/user.service"; +import { BookMenuService } from "../../service/book-menu.service"; +import { LoadingService } from "../../../../core/services/loading.service"; +import { BookDialogHelperService } from "../book-browser/book-dialog-helper.service"; +import { TaskHelperService } from "../../../settings/task-management/task-helper.service"; +import { MetadataRefreshType } from "../../../metadata/model/request/metadata-refresh-type.enum"; +import { TieredMenu } from "primeng/tieredmenu"; +import { Tooltip } from "primeng/tooltip"; +import { Divider } from "primeng/divider"; +import { finalize } from "rxjs/operators"; +import { animate, state, style, transition, trigger } from "@angular/animations"; @Component({ selector: "app-series-page", @@ -35,21 +47,48 @@ import { Router } from "@angular/router"; TabPanels, TabPanel, Tag, - VirtualScrollerModule -], + VirtualScrollerModule, + TieredMenu, + Tooltip, + Divider + ], + animations: [ + trigger('slideInOut', [ + state('void', style({transform: 'translateY(100%)'})), + state('*', style({transform: 'translateY(0)'})), + transition(':enter', [animate('0.1s ease-in')]), + transition(':leave', [animate('0.1s ease-out')]) + ]) + ] }) -export class SeriesPageComponent { +export class SeriesPageComponent implements OnDestroy { private route = inject(ActivatedRoute); private bookService = inject(BookService); protected coverScalePreferenceService = inject(CoverScalePreferenceService); private metadataCenterViewMode: "route" | "dialog" = "route"; - private dialogRef?: DynamicDialogRef; + private dialogRef?: DynamicDialogRef | null; private router = inject(Router); + protected userService = inject(UserService); + private bookMenuService = inject(BookMenuService); + protected confirmationService = inject(ConfirmationService); + private loadingService = inject(LoadingService); + private dialogHelperService = inject(BookDialogHelperService); + protected taskHelperService = inject(TaskHelperService); + private messageService = inject(MessageService); tab: string = "view"; isExpanded = false; + // Selection state + selectedBooks = new Set(); + lastSelectedIndex: number | null = null; + currentBooks: Book[] = []; + private userSub: Subscription; + + // Menu items + protected metadataMenuItems: MenuItem[] | undefined; + protected bulkReadActionsMenuItems: MenuItem[] | undefined; seriesParam$: Observable = this.route.paramMap.pipe( map((params) => params.get("seriesName") || ""), @@ -74,7 +113,8 @@ export class SeriesPageComponent { const bNum = b.metadata?.seriesNumber ?? Number.MAX_SAFE_INTEGER; return aNum - bNum; }); - }) + }), + tap(books => this.currentBooks = books) ); seriesTitle$: Observable = combineLatest([ @@ -150,6 +190,25 @@ export class SeriesPageComponent { }) ); + constructor() { + this.userSub = this.userService.userState$.pipe(filter(u => !!u?.user && u.loaded)) + .subscribe(userState => { + this.metadataMenuItems = this.bookMenuService.getMetadataMenuItems( + () => this.autoFetchMetadata(), + () => this.fetchMetadata(), + () => this.bulkEditMetadata(), + () => this.multiBookEditMetadata(), + () => this.regenerateCoversForSelected(), + userState.user + ); + this.bulkReadActionsMenuItems = this.bookMenuService.getBulkReadActionsMenu(this.selectedBooks, this.user()); + }); + } + + ngOnDestroy(): void { + this.userSub.unsubscribe(); + } + get currentCardSize() { return this.coverScalePreferenceService.currentCardSize; } @@ -249,4 +308,163 @@ export class SeriesPageComponent { return "bg-gray-600"; } } + + handleBookSelection(book: Book, selected: boolean) { + if (selected) { + if (book.seriesBooks) { + //it is a series + this.selectedBooks = new Set([...this.selectedBooks, ...book.seriesBooks.map(book => book.id)]); + } else { + this.selectedBooks.add(book.id); + } + } else { + if (book.seriesBooks) { + //it is a series + book.seriesBooks.forEach(book => { + this.selectedBooks.delete(book.id); + }); + } else { + this.selectedBooks.delete(book.id); + } + } + } + + onCheckboxClicked(event: { index: number; book: Book; selected: boolean; shiftKey: boolean }) { + const {index, book, selected, shiftKey} = event; + if (!shiftKey || this.lastSelectedIndex === null) { + this.handleBookSelection(book, selected); + this.lastSelectedIndex = index; + } else { + const start = Math.min(this.lastSelectedIndex, index); + const end = Math.max(this.lastSelectedIndex, index); + const isUnselectingRange = !selected; + for (let i = start; i <= end; i++) { + const book = this.currentBooks[i]; + if (!book) continue; + this.handleBookSelection(book, !isUnselectingRange); + } + } + this.bulkReadActionsMenuItems = this.bookMenuService.getBulkReadActionsMenu(this.selectedBooks, this.user()); + } + + handleBookSelect(book: Book, selected: boolean): void { + this.handleBookSelection(book, selected); + this.bulkReadActionsMenuItems = this.bookMenuService.getBulkReadActionsMenu(this.selectedBooks, this.user()); + } + + selectAllBooks(): void { + if (!this.currentBooks) return; + for (const book of this.currentBooks) { + this.selectedBooks.add(book.id); + } + this.bulkReadActionsMenuItems = this.bookMenuService.getBulkReadActionsMenu(this.selectedBooks, this.user()); + } + + deselectAllBooks(): void { + this.selectedBooks.clear(); + this.bulkReadActionsMenuItems = this.bookMenuService.getBulkReadActionsMenu(this.selectedBooks, this.user()); + } + + confirmDeleteBooks(): void { + this.confirmationService.confirm({ + message: `Are you sure you want to delete ${this.selectedBooks.size} book(s)?`, + header: 'Confirm Deletion', + icon: 'pi pi-exclamation-triangle', + accept: () => { + const count = this.selectedBooks.size; + const loader = this.loadingService.show(`Deleting ${count} book(s)...`); + + this.bookService.deleteBooks(this.selectedBooks) + .pipe(finalize(() => this.loadingService.hide(loader))) + .subscribe(() => { + this.selectedBooks.clear(); + }); + }, + reject: () => { + } + }); + } + + openShelfAssigner(): void { + this.dialogRef = this.dialogHelperService.openShelfAssignerDialog(null, this.selectedBooks); + if (this.dialogRef) { + this.dialogRef.onClose.subscribe(result => { + if (result.assigned) { + this.selectedBooks.clear(); + } + }); + } + } + + lockUnlockMetadata(): void { + this.dialogRef = this.dialogHelperService.openLockUnlockMetadataDialog(this.selectedBooks); + } + + autoFetchMetadata(): void { + if (!this.selectedBooks || this.selectedBooks.size === 0) return; + this.taskHelperService.refreshMetadataTask({ + refreshType: MetadataRefreshType.BOOKS, + bookIds: Array.from(this.selectedBooks), + }).subscribe(); + } + + fetchMetadata(): void { + this.dialogHelperService.openMetadataRefreshDialog(this.selectedBooks); + } + + bulkEditMetadata(): void { + this.dialogHelperService.openBulkMetadataEditDialog(this.selectedBooks); + } + + multiBookEditMetadata(): void { + this.dialogHelperService.openMultibookMetadataEditorDialog(this.selectedBooks); + } + + regenerateCoversForSelected(): void { + if (!this.selectedBooks || this.selectedBooks.size === 0) return; + const count = this.selectedBooks.size; + this.confirmationService.confirm({ + message: `Are you sure you want to regenerate covers for ${count} book(s)?`, + header: 'Confirm Cover Regeneration', + icon: 'pi pi-image', + acceptLabel: 'Yes', + rejectLabel: 'No', + accept: () => { + this.bookService.regenerateCoversForBooks(Array.from(this.selectedBooks)).subscribe({ + next: () => { + this.messageService.add({ + severity: 'success', + summary: 'Cover Regeneration Started', + detail: `Regenerating covers for ${count} book(s). Refresh the page when complete.`, + life: 3000 + }); + }, + error: () => { + this.messageService.add({ + severity: 'error', + summary: 'Failed', + detail: 'Could not start cover regeneration.', + life: 3000 + }); + } + }); + } + }); + } + + moveFiles() { + this.dialogHelperService.openFileMoverDialog(this.selectedBooks); + } + + user() { + return this.userService.getCurrentUser(); + } + + get hasMetadataMenuItems(): boolean { + return (this.metadataMenuItems?.length ?? 0) > 0; + } + + get hasBulkReadActionsItems(): boolean { + return (this.bulkReadActionsMenuItems?.length ?? 0) > 0; + } } From 81442a1e5c8017c4e774519b18ca02ed835d6449 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= <127139797+balazs-szucs@users.noreply.github.com> Date: Tue, 6 Jan 2026 18:12:29 +0100 Subject: [PATCH 15/40] feat(metadata): enhance XML parsing with secure processing and improved error handling (#2163) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Balázs Szücs --- .../extractor/CbxMetadataExtractor.java | 100 +- .../ExtractFromComicInfoXmlTest.java | 918 ++++++++++++++++++ 2 files changed, 1010 insertions(+), 8 deletions(-) create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ExtractFromComicInfoXmlTest.java diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java index 27f2cf2a9..31d9b6e40 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java @@ -27,6 +27,8 @@ import javax.imageio.ImageIO; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import org.xml.sax.SAXException; import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry; import org.apache.commons.compress.archivers.sevenz.SevenZFile; @@ -132,15 +134,28 @@ public class CbxMetadataExtractor implements FileMetadataExtractor { return null; } + /** + * Builds a secure XML document parser with protection against XXE attacks. + * Configures the DocumentBuilderFactory with security features to prevent: + * - External entity injection + * - DTD processing vulnerabilities + * - Schema injection attacks + * + * @param is InputStream containing XML data to parse + * @return Parsed Document object + * @throws Exception if XML parsing fails or security features cannot be configured + */ private Document buildSecureDocument(InputStream is) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); // Enable namespace awareness factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); try { factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); } catch (Exception ex) { - log.debug("XML factory secure feature not supported: {}", ex.getMessage()); + log.warn("XML factory secure features not supported, XXE protection may be compromised: {}", ex.getMessage()); + throw ex; // Re-throw to fail fast if security features can't be enabled } factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); @@ -149,6 +164,14 @@ public class CbxMetadataExtractor implements FileMetadataExtractor { return builder.parse(is); } + /** + * Maps XML document to BookMetadata by extracting all relevant ComicInfo fields. + * Handles missing or invalid fields gracefully by using fallback values or null. + * + * @param document The parsed XML document containing ComicInfo data + * @param fallbackTitle Title to use if Title element is missing or blank + * @return BookMetadata object populated with extracted values + */ private BookMetadata mapDocumentToMetadata( Document document, String fallbackTitle @@ -209,6 +232,13 @@ public class CbxMetadataExtractor implements FileMetadataExtractor { return builder.build(); } + /** + * Extracts and trims text content from the first element with the given tag name. + * + * @param document The XML document to search + * @param tag The tag name to find + * @return Trimmed text content of the first matching element, or null if not found + */ private String getTextContent(Document document, String tag) { NodeList nodes = document.getElementsByTagName(tag); if (nodes.getLength() == 0) { @@ -223,6 +253,14 @@ public class CbxMetadataExtractor implements FileMetadataExtractor { : (b != null && !b.isBlank() ? b : null); } + /** + * Splits a delimited string into a set of trimmed values. + * Supports both comma (,) and semicolon (;) as delimiters. + * Empty values after trimming are excluded from the result. + * + * @param value The delimited string to split + * @return Set of trimmed non-empty values, or empty set if input is null + */ private Set splitValues(String value) { if (value == null) { return new HashSet<>(); @@ -253,6 +291,15 @@ public class CbxMetadataExtractor implements FileMetadataExtractor { } } + /** + * Parses year, month, and day strings into a LocalDate. + * Defaults missing month/day to 1. Returns null if year is missing or invalid. + * + * @param year Year string (required) + * @param month Month string (optional, defaults to 1) + * @param day Day string (optional, defaults to 1) + * @return LocalDate object, or null if parsing fails or year is null + */ private LocalDate parseDate(String year, String month, String day) { Integer y = parseInteger(year); Integer m = parseInteger(month); @@ -273,20 +320,57 @@ public class CbxMetadataExtractor implements FileMetadataExtractor { } } + /** + * Extracts metadata from a standalone ComicInfo.xml file. + * This method is useful for processing ComicInfo.xml files that have been + * extracted from comic book archives or exist independently. + * + * @param xmlFile The ComicInfo.xml file to parse + * @return BookMetadata extracted from the XML file, or fallback metadata if parsing fails + * @throws IllegalArgumentException if xmlFile is null + */ public BookMetadata extractFromComicInfoXml(File xmlFile) { + if (xmlFile == null) { + throw new IllegalArgumentException("XML file cannot be null"); + } + + String fallbackTitle = determineFallbackTitle(xmlFile); + try (InputStream is = new FileInputStream(xmlFile)) { Document document = buildSecureDocument(is); - String fallbackTitle = xmlFile.getParentFile() != null - ? xmlFile.getParentFile().getName() - : xmlFile.getName(); return mapDocumentToMetadata(document, fallbackTitle); + } catch (IOException e) { + log.error("Failed to read ComicInfo.xml file '{}': {}", + xmlFile.getAbsolutePath(), e.getMessage(), e); + return BookMetadata.builder().title(fallbackTitle).build(); + } catch (SAXException | ParserConfigurationException e) { + log.warn("Failed to parse ComicInfo.xml from file '{}': {}", + xmlFile.getAbsolutePath(), e.getMessage(), e); + return BookMetadata.builder().title(fallbackTitle).build(); } catch (Exception e) { - log.warn("Failed to parse ComicInfo.xml: {}", e.getMessage()); - String fallbackTitle = xmlFile.getParentFile() != null - ? xmlFile.getParentFile().getName() - : xmlFile.getName(); + log.error("Unexpected error processing ComicInfo.xml '{}': {}", + xmlFile.getAbsolutePath(), e.getMessage(), e); return BookMetadata.builder().title(fallbackTitle).build(); } + } + + /** + * Determines the fallback title to use when metadata extraction fails. + * Uses the parent directory name if available, otherwise the file name. + * + * @param file The file to determine the fallback title for + * @return A fallback title string + */ + private String determineFallbackTitle(File file) { + // Try parent directory first (usually the comic folder/archive name) + if (file.getParentFile() != null) { + String parentName = file.getParentFile().getName(); + if (parentName != null && !parentName.isBlank()) { + return parentName; + } + } + // Fall back to filename without extension + return FilenameUtils.getBaseName(file.getName()); } @Override diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ExtractFromComicInfoXmlTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ExtractFromComicInfoXmlTest.java new file mode 100644 index 000000000..fb4c5ddf9 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ExtractFromComicInfoXmlTest.java @@ -0,0 +1,918 @@ +package com.adityachandel.booklore.service.metadata.extractor; + +import com.adityachandel.booklore.model.dto.BookMetadata; +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 java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.LocalDate; + +import static org.junit.jupiter.api.Assertions.*; + +class ExtractFromComicInfoXmlTest { + + private CbxMetadataExtractor extractor; + + @TempDir + Path tempDir; + + @BeforeEach + void setUp() { + extractor = new CbxMetadataExtractor(); + } + + @Test + void testExtractFromComicInfoXml_ValidXml_AllFields() throws IOException { + String xml = """ + + + Batman: The Dark Knight Returns + Batman: The Dark Knight Returns + 1 + 4 + 1 + 1986 + 3 + 15 + DC Comics + Batman comes out of retirement to fight crime in Gotham City. + Frank Miller + Frank Miller + Klaus Janson + Lynn Varley + John Costanza + Frank Miller + Superhero, Crime + Batman, DC, Frank Miller + 48 + en + + """; + + File xmlFile = createXmlFile("valid_all_fields.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Batman: The Dark Knight Returns", metadata.getTitle()); + assertEquals("Batman: The Dark Knight Returns (1)", metadata.getSeriesName()); + assertEquals(1.0f, metadata.getSeriesNumber()); + assertEquals(4, metadata.getSeriesTotal()); + assertEquals(LocalDate.of(1986, 3, 15), metadata.getPublishedDate()); + assertEquals("DC Comics", metadata.getPublisher()); + assertEquals("Batman comes out of retirement to fight crime in Gotham City.", metadata.getDescription()); + assertEquals(48, metadata.getPageCount()); + assertEquals("en", metadata.getLanguage()); + + // Verify authors + assertTrue(metadata.getAuthors().contains("Frank Miller")); + assertTrue(metadata.getAuthors().contains("Klaus Janson")); + assertTrue(metadata.getAuthors().contains("Lynn Varley")); + assertTrue(metadata.getAuthors().contains("John Costanza")); + + // Verify categories + assertTrue(metadata.getCategories().contains("Superhero")); + assertTrue(metadata.getCategories().contains("Crime")); + assertTrue(metadata.getCategories().contains("Batman")); + assertTrue(metadata.getCategories().contains("DC")); + assertTrue(metadata.getCategories().contains("Frank Miller")); + } + + @Test + void testExtractFromComicInfoXml_MinimalXml() throws IOException { + String xml = """ + + Simple Comic + + """; + + File xmlFile = createXmlFile("minimal.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Simple Comic", metadata.getTitle()); + assertNull(metadata.getSeriesName()); + assertNull(metadata.getSeriesNumber()); + assertNull(metadata.getSeriesTotal()); + assertNull(metadata.getPublishedDate()); + assertNull(metadata.getPublisher()); + assertNull(metadata.getDescription()); + assertNull(metadata.getPageCount()); + assertNull(metadata.getLanguage()); + } + + @Test + void testExtractFromComicInfoXml_NoTitle_UsesFallback() throws IOException { + String xml = """ + + Mystery Series + 5 + + """; + + Path parentDir = tempDir.resolve("comic_folder"); + Files.createDirectories(parentDir); + File xmlFile = createXmlFileInDir(parentDir, "no_title.xml", xml); + + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("comic_folder", metadata.getTitle()); + assertEquals("Mystery Series", metadata.getSeriesName()); + assertEquals(5.0f, metadata.getSeriesNumber()); + } + + @Test + void testExtractFromComicInfoXml_EmptyTitle_UsesFallback() throws IOException { + String xml = """ + + + Empty Title Series + + """; + + Path parentDir = tempDir.resolve("empty_title_comic"); + Files.createDirectories(parentDir); + File xmlFile = createXmlFileInDir(parentDir, "empty_title.xml", xml); + + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("empty_title_comic", metadata.getTitle()); + } + + @Test + void testExtractFromComicInfoXml_WhitespaceTitle_UsesFallback() throws IOException { + String xml = """ + + + Whitespace Title Series + + """; + + Path parentDir = tempDir.resolve("whitespace_comic"); + Files.createDirectories(parentDir); + File xmlFile = createXmlFileInDir(parentDir, "whitespace_title.xml", xml); + + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("whitespace_comic", metadata.getTitle()); + } + + @Test + void testExtractFromComicInfoXml_SeriesWithoutVolume() throws IOException { + String xml = """ + + Test Comic + Test Series + 10 + + """; + + File xmlFile = createXmlFile("series_no_volume.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Test Series", metadata.getSeriesName()); + assertEquals(10.0f, metadata.getSeriesNumber()); + } + + @Test + void testExtractFromComicInfoXml_SeriesWithVolume() throws IOException { + String xml = """ + + Test Comic + Test Series + 2 + 10 + + """; + + File xmlFile = createXmlFile("series_with_volume.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Test Series (2)", metadata.getSeriesName()); + assertEquals(10.0f, metadata.getSeriesNumber()); + } + + @Test + void testExtractFromComicInfoXml_SeriesWithEmptyVolume() throws IOException { + String xml = """ + + Test Comic + Test Series + + 10 + + """; + + File xmlFile = createXmlFile("series_empty_volume.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Test Series", metadata.getSeriesName()); + } + + @Test + void testExtractFromComicInfoXml_FloatingPointNumber() throws IOException { + String xml = """ + + Test Comic + Test Series + 10.5 + + """; + + File xmlFile = createXmlFile("floating_number.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(10.5f, metadata.getSeriesNumber()); + } + + @Test + void testExtractFromComicInfoXml_InvalidNumberFormat() throws IOException { + String xml = """ + + Test Comic + Test Series + not-a-number + also-not-a-number + invalid + + """; + + File xmlFile = createXmlFile("invalid_numbers.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertNull(metadata.getSeriesNumber()); + assertNull(metadata.getSeriesTotal()); + assertNull(metadata.getPageCount()); + } + + @Test + void testExtractFromComicInfoXml_DateWithYearOnly() throws IOException { + String xml = """ + + Test Comic + 2020 + + """; + + File xmlFile = createXmlFile("date_year_only.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(LocalDate.of(2020, 1, 1), metadata.getPublishedDate()); + } + + @Test + void testExtractFromComicInfoXml_DateWithYearAndMonth() throws IOException { + String xml = """ + + Test Comic + 2020 + 6 + + """; + + File xmlFile = createXmlFile("date_year_month.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(LocalDate.of(2020, 6, 1), metadata.getPublishedDate()); + } + + @Test + void testExtractFromComicInfoXml_InvalidDate() throws IOException { + String xml = """ + + Test Comic + 2020 + 13 + 32 + + """; + + File xmlFile = createXmlFile("invalid_date.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertNull(metadata.getPublishedDate()); + } + + @Test + void testExtractFromComicInfoXml_MultipleAuthors_CommaSeparated() throws IOException { + String xml = """ + + Test Comic + John Doe, Jane Smith + Bob Artist, Alice Drawer + + """; + + File xmlFile = createXmlFile("multiple_authors_comma.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertTrue(metadata.getAuthors().contains("John Doe")); + assertTrue(metadata.getAuthors().contains("Jane Smith")); + assertTrue(metadata.getAuthors().contains("Bob Artist")); + assertTrue(metadata.getAuthors().contains("Alice Drawer")); + } + + @Test + void testExtractFromComicInfoXml_MultipleAuthors_SemicolonSeparated() throws IOException { + String xml = """ + + Test Comic + John Doe; Jane Smith + Bob Inker; Alice Helper + + """; + + File xmlFile = createXmlFile("multiple_authors_semicolon.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertTrue(metadata.getAuthors().contains("John Doe")); + assertTrue(metadata.getAuthors().contains("Jane Smith")); + assertTrue(metadata.getAuthors().contains("Bob Inker")); + assertTrue(metadata.getAuthors().contains("Alice Helper")); + } + + @Test + void testExtractFromComicInfoXml_MultipleCategories() throws IOException { + String xml = """ + + Test Comic + Action, Adventure, Sci-Fi + robots; space; future + + """; + + File xmlFile = createXmlFile("multiple_categories.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertTrue(metadata.getCategories().contains("Action")); + assertTrue(metadata.getCategories().contains("Adventure")); + assertTrue(metadata.getCategories().contains("Sci-Fi")); + assertTrue(metadata.getCategories().contains("robots")); + assertTrue(metadata.getCategories().contains("space")); + assertTrue(metadata.getCategories().contains("future")); + } + + @Test + void testExtractFromComicInfoXml_DescriptionFromSummary() throws IOException { + String xml = """ + + Test Comic + This is a summary + + """; + + File xmlFile = createXmlFile("description_summary.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("This is a summary", metadata.getDescription()); + } + + @Test + void testExtractFromComicInfoXml_DescriptionFromDescription() throws IOException { + String xml = """ + + Test Comic + This is a description + + """; + + File xmlFile = createXmlFile("description_description.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("This is a description", metadata.getDescription()); + } + + @Test + void testExtractFromComicInfoXml_SummaryPreferredOverDescription() throws IOException { + String xml = """ + + Test Comic + Summary text + Description text + + """; + + File xmlFile = createXmlFile("summary_and_description.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Summary text", metadata.getDescription()); + } + + @Test + void testExtractFromComicInfoXml_PageCountFromPageCount() throws IOException { + String xml = """ + + Test Comic + 32 + + """; + + File xmlFile = createXmlFile("pagecount_field.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(32, metadata.getPageCount()); + } + + @Test + void testExtractFromComicInfoXml_PageCountFromPages() throws IOException { + String xml = """ + + Test Comic + 48 + + """; + + File xmlFile = createXmlFile("pages_field.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(48, metadata.getPageCount()); + } + + @Test + void testExtractFromComicInfoXml_SpecialCharactersInFields() throws IOException { + String xml = """ + + Test & Verify: "Special" Characters + Series <Test> + O'Brien & Associates + A story with "quotes" and <tags> + + """; + + File xmlFile = createXmlFile("special_characters.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Test & Verify: \"Special\" Characters", metadata.getTitle()); + assertEquals("Series ", metadata.getSeriesName()); + assertTrue(metadata.getAuthors().contains("O'Brien & Associates")); + assertEquals("A story with \"quotes\" and ", metadata.getDescription()); + } + + @Test + void testExtractFromComicInfoXml_MalformedXml_ReturnsFallbackMetadata() throws IOException { + String xml = "Unclosed Tag"; + + File xmlFile = createXmlFile("malformed.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + // Should return fallback title (parent directory name or file name) + assertNotNull(metadata.getTitle()); + } + + @Test + void testExtractFromComicInfoXml_EmptyXml_ReturnsFallbackMetadata() throws IOException { + String xml = ""; + + File xmlFile = createXmlFile("empty.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertNotNull(metadata.getTitle()); + } + + @Test + void testExtractFromComicInfoXml_InvalidXmlContent_ReturnsFallbackMetadata() throws IOException { + String xml = "This is not XML at all!"; + + File xmlFile = createXmlFile("not_xml.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertNotNull(metadata.getTitle()); + } + + @Test + void testExtractFromComicInfoXml_XmlWithNamespace() throws IOException { + String xml = """ + <?xml version="1.0" encoding="UTF-8"?> + <ComicInfo xmlns="http://example.com/schema"> + <Title>Namespaced Comic + Namespace Series + 1 + + """; + + File xmlFile = createXmlFile("with_namespace.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + // With namespace awareness enabled, should extract correctly + assertNotNull(metadata); + assertEquals("Namespaced Comic", metadata.getTitle()); + assertEquals("Namespace Series", metadata.getSeriesName()); + assertEquals(1.0f, metadata.getSeriesNumber()); + } + + @Test + void testExtractFromComicInfoXml_XXEAttackPrevention() throws IOException { + String xxeXml = """ + + + ]> + + &xxe; + + """; + + Path parentDir = tempDir.resolve("xxe_attack"); + File xmlFile = new File(parentDir.toFile(), "ComicInfo.xml"); + Files.createDirectories(parentDir); + Files.writeString(xmlFile.toPath(), xxeXml, StandardCharsets.UTF_8); + + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + // XXE protection should prevent parsing and return fallback metadata + assertNotNull(metadata); + assertEquals("xxe_attack", metadata.getTitle()); // Fallback to filename + // Should not contain any resolved entity content + assertFalse(metadata.getTitle().contains("&xxe;")); + assertFalse(metadata.getTitle().contains("root:")); + } + + @Test + void testExtractFromComicInfoXml_BillionLaughsAttackPrevention() throws IOException { + String billionLaughsXml = """ + + + + + ]> + + &lol3; + + """; + + File xmlFile = createXmlFile("billion_laughs.xml", billionLaughsXml); + + // Should fail fast, not hang or consume excessive memory + assertDoesNotThrow(() -> { + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + assertNotNull(metadata); + }); + } + + @Test + void testExtractFromComicInfoXml_NegativeNumbers() throws IOException { + String xml = """ + + Test + -5 + -10 + -32 + + """; + + File xmlFile = createXmlFile("negative_numbers.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + // Document behavior: negative numbers are parsed but may not be meaningful + assertNotNull(metadata); + assertEquals(-5.0f, metadata.getSeriesNumber()); + assertEquals(-10, metadata.getSeriesTotal()); + assertEquals(-32, metadata.getPageCount()); + } + + @Test + void testExtractFromComicInfoXml_VeryLargeNumbers() throws IOException { + String xml = """ + + Test + 999999999999999 + 2147483648 + + """; + + File xmlFile = createXmlFile("large_numbers.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertNotNull(metadata.getSeriesNumber()); + // PageCount overflows Integer.MAX_VALUE, parseInteger returns null + assertNull(metadata.getPageCount()); + } + + @Test + void testExtractFromComicInfoXml_EmptyXmlFile() throws IOException { + Path parentDir = tempDir.resolve("empty"); + Files.createDirectories(parentDir); + File xmlFile = new File(parentDir.toFile(), "ComicInfo.xml"); + Files.writeString(xmlFile.toPath(), "", StandardCharsets.UTF_8); + + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + // Should return fallback metadata, not crash + assertNotNull(metadata); + assertEquals("empty", metadata.getTitle()); + } + + @Test + void testExtractFromComicInfoXml_VeryLongStrings() throws IOException { + String longTitle = "A".repeat(10000); + String longDescription = "B".repeat(10000); + + String xml = String.format(""" + + %s + %s + + """, longTitle, longDescription); + + File xmlFile = createXmlFile("long_strings.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(longTitle, metadata.getTitle()); + assertEquals(longDescription, metadata.getDescription()); + } + + @Test + void testExtractFromComicInfoXml_FileDoesNotExist_ReturnsFallbackMetadata() { + Path parentDir = tempDir.resolve("does_not_exist"); + File nonExistentFile = new File(parentDir.toFile(), "ComicInfo.xml"); + + BookMetadata metadata = extractor.extractFromComicInfoXml(nonExistentFile); + + assertNotNull(metadata); + assertEquals("does_not_exist", metadata.getTitle()); + } + + @ParameterizedTest + @CsvSource({ + "2020,,,2020-01-01", + "2020,6,,2020-06-01", + "2020,3,15,2020-03-15", + "2020,13,32," // Invalid + }) + void testExtractFromComicInfoXml_DateParsing(String year, String month, String day, String expected) throws IOException { + String xml = String.format(""" + + Date Test + %s%s%s + + """, + year != null ? "" + year + "" : "", + month != null ? "" + month + "" : "", + day != null ? "" + day + "" : "" + ); + + File xmlFile = createXmlFile("date_test.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + if (expected != null && !expected.isBlank()) { + assertEquals(LocalDate.parse(expected), metadata.getPublishedDate()); + } else { + assertNull(metadata.getPublishedDate()); + } + } + + @Test + void testExtractFromComicInfoXml_NullInput_ThrowsIllegalArgumentException() { + IllegalArgumentException exception = assertThrows( + IllegalArgumentException.class, + () -> extractor.extractFromComicInfoXml(null) + ); + assertEquals("XML file cannot be null", exception.getMessage()); + } + + @Test + void testExtractFromComicInfoXml_CompleteMetadata_AllFieldsPopulated() throws IOException { + String xml = """ + + + Batman: The Dark Knight Returns + Batman: The Dark Knight Returns + 1 + 4 + 1 + 1986 + 3 + 15 + DC Comics + Batman comes out of retirement to fight crime in Gotham City. + Frank Miller + Frank Miller + Klaus Janson + Lynn Varley + John Costanza + Frank Miller + Superhero, Crime + Batman, DC, Frank Miller + 48 + en + + """; + + File xmlFile = createXmlFile("complete_metadata.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Batman: The Dark Knight Returns", metadata.getTitle()); + assertEquals("Batman: The Dark Knight Returns (1)", metadata.getSeriesName()); + assertEquals(1.0f, metadata.getSeriesNumber()); + assertEquals(4, metadata.getSeriesTotal()); + assertEquals(LocalDate.of(1986, 3, 15), metadata.getPublishedDate()); + assertEquals("DC Comics", metadata.getPublisher()); + assertEquals("Batman comes out of retirement to fight crime in Gotham City.", metadata.getDescription()); + assertEquals(48, metadata.getPageCount()); + assertEquals("en", metadata.getLanguage()); + + // Verify authors + assertTrue(metadata.getAuthors().contains("Frank Miller")); + assertTrue(metadata.getAuthors().contains("Klaus Janson")); + assertTrue(metadata.getAuthors().contains("Lynn Varley")); + assertTrue(metadata.getAuthors().contains("John Costanza")); + + // Verify categories + assertTrue(metadata.getCategories().contains("Superhero")); + assertTrue(metadata.getCategories().contains("Crime")); + assertTrue(metadata.getCategories().contains("Batman")); + assertTrue(metadata.getCategories().contains("DC")); + assertTrue(metadata.getCategories().contains("Frank Miller")); + } + + @Test + void testExtractFromComicInfoXml_XmlWithComments() throws IOException { + String xml = """ + + + Comic With Comments + + Comment Series + + """; + + File xmlFile = createXmlFile("with_comments.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Comic With Comments", metadata.getTitle()); + assertEquals("Comment Series", metadata.getSeriesName()); + } + + @Test + void testExtractFromComicInfoXml_LeadingAndTrailingWhitespace() throws IOException { + String xml = """ + + Trimmed Title + Trimmed Series + Writer Name + + """; + + File xmlFile = createXmlFile("with_whitespace.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Trimmed Title", metadata.getTitle()); + assertEquals("Trimmed Series", metadata.getSeriesName()); + assertTrue(metadata.getAuthors().contains("Writer Name")); + } + + @Test + void testExtractFromComicInfoXml_DuplicateAuthors_RemovedBySet() throws IOException { + String xml = """ + + Test Comic + Frank Miller + Frank Miller + Frank Miller + + """; + + File xmlFile = createXmlFile("duplicate_authors.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + // Set should contain only one "Frank Miller" + assertEquals(1, metadata.getAuthors().size()); + assertTrue(metadata.getAuthors().contains("Frank Miller")); + } + + @Test + void testExtractFromComicInfoXml_EmptyAuthorFields_NotAdded() throws IOException { + String xml = """ + + Test Comic + + + Valid Author + + """; + + File xmlFile = createXmlFile("empty_authors.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(1, metadata.getAuthors().size()); + assertTrue(metadata.getAuthors().contains("Valid Author")); + } + + @Test + void testExtractFromComicInfoXml_NoAuthors_AuthorsNull() throws IOException { + String xml = """ + + Test Comic + Test Series + + """; + + File xmlFile = createXmlFile("no_authors.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + // If no authors, the set should be null or empty + assertTrue(metadata.getAuthors() == null || metadata.getAuthors().isEmpty()); + } + + @Test + void testExtractFromComicInfoXml_NoCategories_CategoriesNull() throws IOException { + String xml = """ + + Test Comic + Test Series + + """; + + File xmlFile = createXmlFile("no_categories.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertTrue(metadata.getCategories() == null || metadata.getCategories().isEmpty()); + } + + @Test + void testExtractFromComicInfoXml_FileInRootDirectory() throws IOException { + String xml = """ + + Root Comic + + """; + + // Create file directly in tempDir (no parent directory) + File xmlFile = createXmlFile("root_comic.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals("Root Comic", metadata.getTitle()); + } + + @Test + void testExtractFromComicInfoXml_ZeroValues() throws IOException { + String xml = """ + + Test + 0 + 0 + 0 + + """; + + File xmlFile = createXmlFile("zero_values.xml", xml); + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); + + assertNotNull(metadata); + assertEquals(0.0f, metadata.getSeriesNumber()); + assertEquals(0, metadata.getSeriesTotal()); + assertEquals(0, metadata.getPageCount()); + } + + // Helper methods + + private File createXmlFile(String filename, String content) throws IOException { + return createXmlFileInDir(tempDir, filename, content); + } + + private File createXmlFileInDir(Path dir, String filename, String content) throws IOException { + Path xmlPath = dir.resolve(filename); + Files.writeString(xmlPath, content, StandardCharsets.UTF_8); + return xmlPath.toFile(); + } +} From f63a8641d8c0be65fdceae29497d1660c5c88125 Mon Sep 17 00:00:00 2001 From: acx10 Date: Tue, 6 Jan 2026 15:16:26 -0700 Subject: [PATCH 16/40] Add frontend unit tests (Part 2) --- booklore-ui/src/app/app.component.ts | 2 +- .../cover-scale-preference.service.spec.ts | 2 +- .../cover-scale-preference.service.ts | 2 +- ...sidebar-filter-toggle-pref.service.spec.ts | 2 +- .../sidebar-filter-toggle-pref.service.ts | 2 +- .../book-card-lite-component.ts | 2 +- .../book-metadata-center.component.ts | 2 +- .../metadata-editor.component.ts | 2 +- .../metadata-viewer.component.ts | 2 +- .../metadata-review-dialog-component.ts | 2 +- .../metadata-match-weights-component.ts | 2 +- .../directory-picker/utility.service.spec.ts | 102 ++++ .../file-mover/file-mover-component.ts | 6 +- .../metadata-progress-widget-component.ts | 2 +- .../components/setup/setup.service.spec.ts | 104 ++++ .../unified-notification-popover-component.ts | 2 +- .../layout-topbar/app.topbar.component.ts | 2 +- .../service/app-settings.service.spec.ts | 484 ++++++++++++++++++ .../shared/service/app-settings.service.ts | 2 +- .../app/shared/service/auth.service.spec.ts | 309 +++++++++++ .../shared/service/book-mark.service.spec.ts | 264 ++++++++++ .../app/shared/service/book-mark.service.ts | 1 + ...rvice.ts => book-metadata-host.service.ts} | 0 .../shared/service/book-note.service.spec.ts | 215 ++++++++ .../service/custom-font.service.spec.ts | 309 +++++++++++ .../service/download-progress.service.spec.ts | 174 +++++++ .../service/file-download.service.spec.ts | 215 ++++++++ .../shared/service/file-download.service.ts | 7 +- .../service/file-operations.service.spec.ts | 139 +++++ ...-service.ts => file-operations.service.ts} | 0 .../service/icon-picker.service.spec.ts | 98 ++++ .../src/app/shared/service/loading.service.ts | 12 +- .../service/local-storage.service.spec.ts | 49 ++ ...ge-service.ts => local-storage.service.ts} | 0 .../metadata-match-weights.service.spec.ts | 111 ++++ ...e.ts => metadata-match-weights.service.ts} | 23 - .../service/metadata-progress.service.spec.ts | 241 +++++++++ ...ervice.ts => metadata-progress.service.ts} | 0 .../shared/service/page-title.service.spec.ts | 84 +++ .../app/shared/service/page-title.service.ts | 4 +- .../reading-session-api.service.spec.ts | 252 +++++++++ .../service/reading-session.service.spec.ts | 250 +++++++++ .../service/settings-helper.service.spec.ts | 70 +++ .../shared/service/settings-helper.service.ts | 12 - .../src/app/shared/service/toast.service.ts | 26 - .../shared/service/url-helper.service.spec.ts | 362 +++++++++++++ .../shared/service/version.service.spec.ts | 138 +++++ 47 files changed, 3994 insertions(+), 97 deletions(-) create mode 100644 booklore-ui/src/app/shared/components/directory-picker/utility.service.spec.ts create mode 100644 booklore-ui/src/app/shared/components/setup/setup.service.spec.ts create mode 100644 booklore-ui/src/app/shared/service/app-settings.service.spec.ts create mode 100644 booklore-ui/src/app/shared/service/auth.service.spec.ts create mode 100644 booklore-ui/src/app/shared/service/book-mark.service.spec.ts rename booklore-ui/src/app/shared/service/{book-metadata-host-service.ts => book-metadata-host.service.ts} (100%) create mode 100644 booklore-ui/src/app/shared/service/book-note.service.spec.ts create mode 100644 booklore-ui/src/app/shared/service/custom-font.service.spec.ts create mode 100644 booklore-ui/src/app/shared/service/download-progress.service.spec.ts create mode 100644 booklore-ui/src/app/shared/service/file-download.service.spec.ts create mode 100644 booklore-ui/src/app/shared/service/file-operations.service.spec.ts rename booklore-ui/src/app/shared/service/{file-operations-service.ts => file-operations.service.ts} (100%) create mode 100644 booklore-ui/src/app/shared/service/icon-picker.service.spec.ts create mode 100644 booklore-ui/src/app/shared/service/local-storage.service.spec.ts rename booklore-ui/src/app/shared/service/{local-storage-service.ts => local-storage.service.ts} (100%) create mode 100644 booklore-ui/src/app/shared/service/metadata-match-weights.service.spec.ts rename booklore-ui/src/app/shared/service/{metadata-match-weights-service.ts => metadata-match-weights.service.ts} (50%) create mode 100644 booklore-ui/src/app/shared/service/metadata-progress.service.spec.ts rename booklore-ui/src/app/shared/service/{metadata-progress-service.ts => metadata-progress.service.ts} (100%) create mode 100644 booklore-ui/src/app/shared/service/page-title.service.spec.ts create mode 100644 booklore-ui/src/app/shared/service/reading-session-api.service.spec.ts create mode 100644 booklore-ui/src/app/shared/service/reading-session.service.spec.ts create mode 100644 booklore-ui/src/app/shared/service/settings-helper.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/toast.service.ts create mode 100644 booklore-ui/src/app/shared/service/url-helper.service.spec.ts create mode 100644 booklore-ui/src/app/shared/service/version.service.spec.ts diff --git a/booklore-ui/src/app/app.component.ts b/booklore-ui/src/app/app.component.ts index de85f2508..bfb4c60d4 100644 --- a/booklore-ui/src/app/app.component.ts +++ b/booklore-ui/src/app/app.component.ts @@ -9,7 +9,7 @@ import {RouterOutlet} from '@angular/router'; import {AuthInitializationService} from './core/security/auth-initialization-service'; import {AppConfigService} from './shared/service/app-config.service'; import {MetadataBatchProgressNotification} from './shared/model/metadata-batch-progress.model'; -import {MetadataProgressService} from './shared/service/metadata-progress-service'; +import {MetadataProgressService} from './shared/service/metadata-progress.service'; import {BookdropFileNotification, BookdropFileService} from './features/bookdrop/service/bookdrop-file.service'; import {Subscription} from 'rxjs'; import {DownloadProgressDialogComponent} from './shared/components/download-progress-dialog/download-progress-dialog.component'; 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 index 79cf00ac8..dcf2816ef 100644 --- 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 @@ -3,7 +3,7 @@ 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 {LocalStorageService} from '../../../../shared/service/local-storage.service'; import {take} from 'rxjs/operators'; describe('CoverScalePreferenceService', () => { diff --git a/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.ts b/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.ts index 199d81e30..5077b82af 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/cover-scale-preference.service.ts @@ -2,7 +2,7 @@ import {inject, Injectable} from '@angular/core'; import {Subject} from 'rxjs'; import {debounceTime} from 'rxjs/operators'; import {MessageService} from 'primeng/api'; -import {LocalStorageService} from '../../../../shared/service/local-storage-service'; +import {LocalStorageService} from '../../../../shared/service/local-storage.service'; @Injectable({ providedIn: 'root' 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 index 6faf75189..17fdc7a0e 100644 --- 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 @@ -3,7 +3,7 @@ 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 {LocalStorageService} from '../../../../../shared/service/local-storage.service'; import {take} from 'rxjs/operators'; describe('SidebarFilterTogglePrefService', () => { diff --git a/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.ts b/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.ts index 8cfda7139..c546af1db 100644 --- a/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.ts +++ b/booklore-ui/src/app/features/book/components/book-browser/filters/sidebar-filter-toggle-pref.service.ts @@ -1,7 +1,7 @@ import {inject, Injectable} from '@angular/core'; import {BehaviorSubject} from 'rxjs'; import {MessageService} from 'primeng/api'; -import {LocalStorageService} from '../../../../../shared/service/local-storage-service'; +import {LocalStorageService} from '../../../../../shared/service/local-storage.service'; @Injectable({ providedIn: 'root' diff --git a/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.ts b/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.ts index 995281964..2f1c639ca 100644 --- a/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.ts +++ b/booklore-ui/src/app/features/book/components/book-card-lite/book-card-lite-component.ts @@ -6,7 +6,7 @@ import {UserService} from '../../../settings/user-management/user.service'; import {Router} from '@angular/router'; import {filter, Subject} from 'rxjs'; import {NgClass} from '@angular/common'; -import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host-service'; +import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host.service'; import {takeUntil} from 'rxjs/operators'; import {TooltipModule} from 'primeng/tooltip'; diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-metadata-center.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-metadata-center.component.ts index 50183d3f0..20bd24fc3 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-metadata-center.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/book-metadata-center.component.ts @@ -8,7 +8,7 @@ import {BookService} from '../../../book/service/book.service'; import {AppSettingsService} from '../../../../shared/service/app-settings.service'; import {Tab, TabList, TabPanel, TabPanels, Tabs,} from 'primeng/tabs'; import {DynamicDialogConfig, DynamicDialogRef} from 'primeng/dynamicdialog'; -import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host-service'; +import {BookMetadataHostService} from '../../../../shared/service/book-metadata-host.service'; import {MetadataViewerComponent} from './metadata-viewer/metadata-viewer.component'; import {MetadataEditorComponent} from './metadata-editor/metadata-editor.component'; import {MetadataSearcherComponent} from './metadata-searcher/metadata-searcher.component'; diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts index 0387c9bf3..ac6f258ad 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts @@ -25,7 +25,7 @@ import {LazyLoadImageModule} from "ng-lazyload-image"; import {TaskHelperService} from '../../../../settings/task-management/task-helper.service'; import {BookDialogHelperService} from "../../../../book/components/book-browser/book-dialog-helper.service"; import {BookNavigationService} from '../../../../book/service/book-navigation.service'; -import {BookMetadataHostService} from '../../../../../shared/service/book-metadata-host-service'; +import {BookMetadataHostService} from '../../../../../shared/service/book-metadata-host.service'; import {Router} from '@angular/router'; import {UserService} from '../../../../settings/user-management/user.service'; 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 59305ed42..724d2d8fd 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 @@ -40,7 +40,7 @@ import { } 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 {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'; diff --git a/booklore-ui/src/app/features/metadata/component/metadata-review-dialog/metadata-review-dialog-component.ts b/booklore-ui/src/app/features/metadata/component/metadata-review-dialog/metadata-review-dialog-component.ts index e0afd613e..f8d026290 100644 --- a/booklore-ui/src/app/features/metadata/component/metadata-review-dialog/metadata-review-dialog-component.ts +++ b/booklore-ui/src/app/features/metadata/component/metadata-review-dialog/metadata-review-dialog-component.ts @@ -11,7 +11,7 @@ import {Button} from 'primeng/button'; import {Divider} from 'primeng/divider'; import {ProgressBar} from 'primeng/progressbar'; import {Tooltip} from 'primeng/tooltip'; -import {MetadataProgressService} from '../../../../shared/service/metadata-progress-service'; +import {MetadataProgressService} from '../../../../shared/service/metadata-progress.service'; import {takeUntilDestroyed} from '@angular/core/rxjs-interop'; import {MetadataPickerComponent} from '../book-metadata-center/metadata-picker/metadata-picker.component'; diff --git a/booklore-ui/src/app/features/settings/global-preferences/metadata-match-weights/metadata-match-weights-component.ts b/booklore-ui/src/app/features/settings/global-preferences/metadata-match-weights/metadata-match-weights-component.ts index 21ebde0d7..3b4b5824b 100644 --- a/booklore-ui/src/app/features/settings/global-preferences/metadata-match-weights/metadata-match-weights-component.ts +++ b/booklore-ui/src/app/features/settings/global-preferences/metadata-match-weights/metadata-match-weights-component.ts @@ -1,7 +1,7 @@ import {Component, inject, OnInit} from '@angular/core'; import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from '@angular/forms'; import {MessageService} from 'primeng/api'; -import {MetadataMatchWeightsService} from '../../../../shared/service/metadata-match-weights-service'; +import {MetadataMatchWeightsService} from '../../../../shared/service/metadata-match-weights.service'; import {Button} from 'primeng/button'; import {Tooltip} from 'primeng/tooltip'; import {filter, take} from 'rxjs/operators'; diff --git a/booklore-ui/src/app/shared/components/directory-picker/utility.service.spec.ts b/booklore-ui/src/app/shared/components/directory-picker/utility.service.spec.ts new file mode 100644 index 000000000..a516c9347 --- /dev/null +++ b/booklore-ui/src/app/shared/components/directory-picker/utility.service.spec.ts @@ -0,0 +1,102 @@ +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 {UtilityService} from './utility.service'; + +describe('UtilityService', () => { + let service: UtilityService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + UtilityService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext( + injector, + () => TestBed.inject(UtilityService) + ); + }); + + it('should get folders for a given path', () => { + httpClientMock.get.mockReturnValue(of(['folder1', 'folder2'])); + service.getFolders('/some/path').subscribe(folders => { + expect(folders).toEqual(['folder1', 'folder2']); + expect(httpClientMock.get).toHaveBeenCalledWith( + expect.stringContaining('/api/v1/path'), + {params: expect.anything()} + ); + }); + }); + + it('should handle error when getting folders', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service.getFolders('/bad/path').subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); +}); + +describe('UtilityService - API Contract Tests', () => { + let service: UtilityService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + UtilityService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext( + injector, + () => TestBed.inject(UtilityService) + ); + }); + + it('should call correct endpoint and params for getFolders', () => { + httpClientMock.get.mockReturnValue(of(['a', 'b'])); + service.getFolders('/root').subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/path$/), + {params: expect.objectContaining({get: expect.any(Function)})} + ); + }); + + it('should expect string[] from getFolders', () => { + httpClientMock.get.mockReturnValue(of(['dirA', 'dirB'])); + service.getFolders('/dir').subscribe(result => { + expect(Array.isArray(result)).toBe(true); + expect(typeof result[0]).toBe('string'); + }); + }); + + it('should send correct query param for path', () => { + httpClientMock.get.mockImplementation((url: string, opts: any) => { + expect(opts.params.get('path')).toBe('/my/path'); + return of([]); + }); + service.getFolders('/my/path').subscribe(); + }); +}); + diff --git a/booklore-ui/src/app/shared/components/file-mover/file-mover-component.ts b/booklore-ui/src/app/shared/components/file-mover/file-mover-component.ts index 95041c3ba..52a78b36d 100644 --- a/booklore-ui/src/app/shared/components/file-mover/file-mover-component.ts +++ b/booklore-ui/src/app/shared/components/file-mover/file-mover-component.ts @@ -10,7 +10,7 @@ import {Subject} from 'rxjs'; import {BookService} from '../../../features/book/service/book.service'; import {Book} from '../../../features/book/model/book.model'; -import {FileMoveRequest, FileOperationsService} from '../../service/file-operations-service'; +import {FileMoveRequest, FileOperationsService} from '../../service/file-operations.service'; import {LibraryService} from "../../../features/book/service/library.service"; import {AppSettingsService} from '../../service/app-settings.service'; import {Select} from 'primeng/select'; @@ -393,8 +393,4 @@ export class FileMoverComponent implements OnDestroy { togglePatternsCollapsed(): void { this.patternsCollapsed = !this.patternsCollapsed; } - - trackByBookId(index: number, preview: FilePreview): number { - return preview.bookId; - } } diff --git a/booklore-ui/src/app/shared/components/metadata-progress-widget/metadata-progress-widget-component.ts b/booklore-ui/src/app/shared/components/metadata-progress-widget/metadata-progress-widget-component.ts index 4ecd3c3e4..2a6cd4b6a 100644 --- a/booklore-ui/src/app/shared/components/metadata-progress-widget/metadata-progress-widget-component.ts +++ b/booklore-ui/src/app/shared/components/metadata-progress-widget/metadata-progress-widget-component.ts @@ -9,7 +9,7 @@ import {Tooltip} from 'primeng/tooltip'; import {MessageService} from 'primeng/api'; import {MetadataBatchProgressNotification, MetadataBatchStatus, MetadataBatchStatusLabels} from '../../model/metadata-batch-progress.model'; -import {MetadataProgressService} from '../../service/metadata-progress-service'; +import {MetadataProgressService} from '../../service/metadata-progress.service'; import {MetadataTaskService} from '../../../features/book/service/metadata-task'; import {Tag} from 'primeng/tag'; import {TaskService} from '../../../features/settings/task-management/task.service'; diff --git a/booklore-ui/src/app/shared/components/setup/setup.service.spec.ts b/booklore-ui/src/app/shared/components/setup/setup.service.spec.ts new file mode 100644 index 000000000..1930dcc6c --- /dev/null +++ b/booklore-ui/src/app/shared/components/setup/setup.service.spec.ts @@ -0,0 +1,104 @@ +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 {SetupPayload, SetupService} from './setup.service'; + +describe('SetupService', () => { + let service: SetupService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + post: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + SetupService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext( + injector, + () => TestBed.inject(SetupService) + ); + }); + + it('should create admin with correct payload', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + const payload: SetupPayload = {email: 'admin@test.com', password: 'pass'}; + service.createAdmin(payload).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringContaining('/api/v1/setup'), + payload + ); + }); + }); + + it('should handle error when creating admin', () => { + httpClientMock.post.mockReturnValue(throwError(() => new Error('fail'))); + service.createAdmin({email: 'fail', password: 'fail'}).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); +}); + +describe('SetupService - API Contract Tests', () => { + let service: SetupService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + post: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + SetupService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext( + injector, + () => TestBed.inject(SetupService) + ); + }); + + it('should call correct endpoint for createAdmin', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + const payload: SetupPayload = {email: 'a@b.com', password: 'pw'}; + service.createAdmin(payload).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/setup$/), + payload + ); + }); + + it('should expect void from createAdmin', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + service.createAdmin({email: 'x@y.com', password: 'pw'}).subscribe(result => { + expect(result).toBeUndefined(); + }); + }); + + it('should send correct payload structure', () => { + httpClientMock.post.mockImplementation((url: string, body: SetupPayload) => { + expect(body).toHaveProperty('email'); + expect(body).toHaveProperty('password'); + return of(void 0); + }); + service.createAdmin({email: 'z@z.com', password: 'pw'}).subscribe(); + }); +}); + diff --git a/booklore-ui/src/app/shared/components/unified-notification-popover/unified-notification-popover-component.ts b/booklore-ui/src/app/shared/components/unified-notification-popover/unified-notification-popover-component.ts index 593e551ec..8e3d18e91 100644 --- a/booklore-ui/src/app/shared/components/unified-notification-popover/unified-notification-popover-component.ts +++ b/booklore-ui/src/app/shared/components/unified-notification-popover/unified-notification-popover-component.ts @@ -1,6 +1,6 @@ import {Component, inject} from '@angular/core'; import {LiveNotificationBoxComponent} from '../live-notification-box/live-notification-box.component'; -import {MetadataProgressService} from '../../service/metadata-progress-service'; +import {MetadataProgressService} from '../../service/metadata-progress.service'; import {map} from 'rxjs/operators'; import {AsyncPipe} from '@angular/common'; import {BookdropFileService} from '../../../features/bookdrop/service/bookdrop-file.service'; diff --git a/booklore-ui/src/app/shared/layout/component/layout-topbar/app.topbar.component.ts b/booklore-ui/src/app/shared/layout/component/layout-topbar/app.topbar.component.ts index 8fb3740d8..41022086e 100644 --- a/booklore-ui/src/app/shared/layout/component/layout-topbar/app.topbar.component.ts +++ b/booklore-ui/src/app/shared/layout/component/layout-topbar/app.topbar.component.ts @@ -16,7 +16,7 @@ import {ThemeConfiguratorComponent} from '../theme-configurator/theme-configurat import {AuthService} from '../../../service/auth.service'; import {UserService} from '../../../../features/settings/user-management/user.service'; import {Popover} from 'primeng/popover'; -import {MetadataProgressService} from '../../../service/metadata-progress-service'; +import {MetadataProgressService} from '../../../service/metadata-progress.service'; import {takeUntil} from 'rxjs/operators'; import {Subject} from 'rxjs'; import {MetadataBatchProgressNotification} from '../../../model/metadata-batch-progress.model'; diff --git a/booklore-ui/src/app/shared/service/app-settings.service.spec.ts b/booklore-ui/src/app/shared/service/app-settings.service.spec.ts new file mode 100644 index 000000000..6f448b2e7 --- /dev/null +++ b/booklore-ui/src/app/shared/service/app-settings.service.spec.ts @@ -0,0 +1,484 @@ +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 {AppSettingsService, PublicAppSettings} from './app-settings.service'; +import {AppSettings} from '../model/app-settings.model'; +import {AuthService} from './auth.service'; + +describe('AppSettingsService', () => { + let service: AppSettingsService; + let httpClientMock: any; + let authServiceMock: any; + let injectorMock: any; + + const mockAppSettings: AppSettings = { + autoBookSearch: true, + similarBookRecommendation: false, + defaultMetadataRefreshOptions: {} as any, + libraryMetadataRefreshOptions: [], + uploadPattern: '', + opdsServerEnabled: false, + remoteAuthEnabled: false, + oidcEnabled: true, + oidcProviderDetails: { + providerName: 'TestProvider', + clientId: 'clientid', + issuerUri: 'https://issuer.example.com', + claimMapping: { + username: 'username', + email: 'email', + name: 'name' + } + }, + oidcAutoProvisionDetails: { + enableAutoProvisioning: false, + defaultPermissions: [], + defaultLibraryIds: [] + }, + cbxCacheSizeInMb: 0, + maxFileUploadSizeInMb: 0, + metadataProviderSettings: { + amazon: {enabled: false, cookie: '', domain: ''}, + google: {enabled: false, language: ''}, + goodReads: {enabled: false}, + hardcover: {enabled: false, apiKey: ''}, + comicvine: {enabled: false, apiKey: ''}, + douban: {enabled: false}, + lubimyczytac: {enabled: false} + }, + metadataMatchWeights: { + title: 0, + subtitle: 0, + description: 0, + authors: 0, + publisher: 0, + publishedDate: 0, + seriesName: 0, + seriesNumber: 0, + seriesTotal: 0, + isbn13: 0, + isbn10: 0, + language: 0, + pageCount: 0, + categories: 0, + amazonRating: 0, + amazonReviewCount: 0, + goodreadsRating: 0, + goodreadsReviewCount: 0, + hardcoverRating: 0, + hardcoverReviewCount: 0, + doubanRating: 0, + doubanReviewCount: 0, + lubimyczytacRating: 0, + coverImage: 0 + }, + metadataPersistenceSettings: { + moveFilesToLibraryPattern: false, + saveToOriginalFile: false, + convertCbrCb7ToCbz: false + }, + metadataPublicReviewsSettings: { + downloadEnabled: false, + autoDownloadEnabled: false, + providers: [] + }, + koboSettings: { + convertToKepub: false, + conversionLimitInMb: 0, + conversionImageCompressionPercentage: 0, + convertCbxToEpub: false, + conversionLimitInMbForCbx: 0, + forceEnableHyphenation: false + }, + coverCroppingSettings: { + verticalCroppingEnabled: false, + horizontalCroppingEnabled: false, + aspectRatioThreshold: 0, + smartCroppingEnabled: false + }, + metadataDownloadOnBookdrop: false, + telemetryEnabled: false + }; + + const mockPublicSettings: PublicAppSettings = { + oidcEnabled: true, + remoteAuthEnabled: false, + oidcProviderDetails: mockAppSettings.oidcProviderDetails + }; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + put: vi.fn() + }; + + authServiceMock = { + clearOIDCTokens: vi.fn() + }; + + injectorMock = { + get: vi.fn().mockReturnValue(authServiceMock) + }; + + TestBed.configureTestingModule({ + providers: [ + AppSettingsService, + {provide: HttpClient, useValue: httpClientMock}, + {provide: AuthService, useValue: authServiceMock}, + {provide: EnvironmentInjector, useValue: injectorMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(AppSettingsService)); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('should fetch app settings and update subject', () => { + httpClientMock.get.mockReturnValue(of(mockAppSettings)); + service['fetchAppSettings']().subscribe(settings => { + expect(settings).toEqual(mockAppSettings); + expect(service['appSettingsSubject'].value).toEqual(mockAppSettings); + }); + }); + + it('should handle error when fetching app settings', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service['fetchAppSettings']().subscribe({ + error: (err: any) => { + expect(service['appSettingsSubject'].value).toBeNull(); + expect(err).toBeInstanceOf(Error); + } + }); + }); + + it('should fetch public settings and update subject', () => { + httpClientMock.get.mockReturnValue(of(mockPublicSettings)); + service['fetchPublicSettings']().subscribe(settings => { + expect(settings).toEqual(mockPublicSettings); + expect(service['publicAppSettingsSubject'].value).toEqual(mockPublicSettings); + }); + }); + + it('should handle error when fetching public settings', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service['fetchPublicSettings']().subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + } + }); + }); + + it('should sync public settings from app settings', () => { + service['publicAppSettingsSubject'].next(null); + service['syncPublicSettings'](mockAppSettings); + expect(service['publicAppSettingsSubject'].value).toEqual(mockPublicSettings); + }); + + it('should not update public settings if unchanged', () => { + service['publicAppSettingsSubject'].next(mockPublicSettings); + service['syncPublicSettings'](mockAppSettings); + expect(service['publicAppSettingsSubject'].value).toEqual(mockPublicSettings); + }); + + it('should save settings and update appSettingsSubject', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service['appSettingsSubject'].next({...mockAppSettings}); + service.saveSettings([{key: 'oidcEnabled', newValue: false}]).subscribe(() => { + expect(service['appSettingsSubject'].value?.oidcEnabled).toBe(false); + }); + }); + + it('should fetch settings if current is null on save', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + httpClientMock.get.mockReturnValue(of(mockAppSettings)); + service['appSettingsSubject'].next(null); + service.saveSettings([{key: 'oidcEnabled', newValue: true}]).subscribe(() => { + expect(httpClientMock.get).toHaveBeenCalled(); + }); + }); + + it('should handle error on saveSettings', () => { + httpClientMock.put.mockReturnValue(throwError(() => new Error('fail'))); + service.saveSettings([{key: 'oidcEnabled', newValue: false}]).subscribe(result => { + expect(result).toBeUndefined(); + }); + }); + + it('should toggle OIDC enabled and update state', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service['appSettingsSubject'].next({...mockAppSettings}); + service.toggleOidcEnabled(false).subscribe(() => { + expect(service['appSettingsSubject'].value?.oidcEnabled).toBe(false); + }); + }); + + it('should call clearOIDCTokens when disabling OIDC', async () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service['appSettingsSubject'].next({...mockAppSettings}); + await new Promise(resolve => { + service.toggleOidcEnabled(false).subscribe(() => { + setTimeout(() => { + expect(authServiceMock.clearOIDCTokens).toHaveBeenCalled(); + resolve(); + }, 10); + }); + }); + }); + + it('should handle error on toggleOidcEnabled', () => { + httpClientMock.put.mockReturnValue(throwError(() => new Error('fail'))); + service.toggleOidcEnabled(true).subscribe(result => { + expect(result).toBeUndefined(); + }); + }); +}); + +describe('AppSettingsService - API Contract Tests', () => { + let service: AppSettingsService; + let httpClientMock: any; + let authServiceMock: any; + let injectorMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + put: vi.fn() + }; + + authServiceMock = { + clearOIDCTokens: vi.fn() + }; + + injectorMock = { + get: vi.fn().mockReturnValue(authServiceMock) + }; + + TestBed.configureTestingModule({ + providers: [ + AppSettingsService, + {provide: HttpClient, useValue: httpClientMock}, + {provide: AuthService, useValue: authServiceMock}, + {provide: EnvironmentInjector, useValue: injectorMock} + ] + }); + + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(AppSettingsService)); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe('PublicAppSettings interface contract', () => { + it('should validate all required PublicAppSettings fields exist', () => { + const requiredFields: (keyof PublicAppSettings)[] = [ + 'oidcEnabled', 'remoteAuthEnabled', 'oidcProviderDetails' + ]; + const mockResponse: PublicAppSettings = { + oidcEnabled: true, + remoteAuthEnabled: false, + oidcProviderDetails: { + providerName: 'Provider', + clientId: 'id', + issuerUri: 'issuer', + claimMapping: { + username: 'username', + email: 'email', + name: 'name' + } + } + }; + httpClientMock.get.mockReturnValue(of(mockResponse)); + service['fetchPublicSettings']().subscribe(settings => { + requiredFields.forEach(field => { + expect(settings).toHaveProperty(field); + expect(settings[field]).toBeDefined(); + }); + }); + }); + }); + + describe('HTTP endpoint contract', () => { + it('should call correct endpoint for fetchAppSettings', () => { + httpClientMock.get.mockReturnValue(of({})); + service['fetchAppSettings']().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/settings$/)); + }); + + it('should call correct endpoint for fetchPublicSettings', () => { + httpClientMock.get.mockReturnValue(of({})); + service['fetchPublicSettings']().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/public-settings$/)); + }); + + it('should call correct endpoint for saveSettings', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service.saveSettings([{key: 'oidcEnabled', newValue: true}]).subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/settings$/), + [{name: 'oidcEnabled', value: true}] + ); + }); + + it('should call correct endpoint for toggleOidcEnabled', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service.toggleOidcEnabled(true).subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/settings$/), + [{name: 'OIDC_ENABLED', value: true}] + ); + }); + }); + + describe('Request payload contract', () => { + it('should send correct structure for saveSettings', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service.saveSettings([{key: 'remoteAuthEnabled', newValue: false}]).subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith( + expect.any(String), + [{name: 'remoteAuthEnabled', value: false}] + ); + }); + + it('should send correct structure for toggleOidcEnabled', () => { + httpClientMock.put.mockReturnValue(of(void 0)); + service.toggleOidcEnabled(false).subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith( + expect.any(String), + [{name: 'OIDC_ENABLED', value: false}] + ); + }); + }); + + describe('Response type contract', () => { + it('should expect AppSettings from fetchAppSettings', () => { + const mockSettings: AppSettings = { + autoBookSearch: true, + similarBookRecommendation: false, + defaultMetadataRefreshOptions: {} as any, + libraryMetadataRefreshOptions: [], + uploadPattern: '', + opdsServerEnabled: false, + remoteAuthEnabled: false, + oidcEnabled: true, + oidcProviderDetails: { + providerName: 'Provider', + clientId: 'id', + issuerUri: 'issuer', + claimMapping: { + username: 'username', + email: 'email', + name: 'name' + } + }, + oidcAutoProvisionDetails: { + enableAutoProvisioning: false, + defaultPermissions: [], + defaultLibraryIds: [] + }, + cbxCacheSizeInMb: 0, + maxFileUploadSizeInMb: 0, + metadataProviderSettings: { + amazon: {enabled: false, cookie: '', domain: ''}, + google: {enabled: false, language: ''}, + goodReads: {enabled: false}, + hardcover: {enabled: false, apiKey: ''}, + comicvine: {enabled: false, apiKey: ''}, + douban: {enabled: false}, + lubimyczytac: {enabled: false} + }, + metadataMatchWeights: { + title: 0, + subtitle: 0, + description: 0, + authors: 0, + publisher: 0, + publishedDate: 0, + seriesName: 0, + seriesNumber: 0, + seriesTotal: 0, + isbn13: 0, + isbn10: 0, + language: 0, + pageCount: 0, + categories: 0, + amazonRating: 0, + amazonReviewCount: 0, + goodreadsRating: 0, + goodreadsReviewCount: 0, + hardcoverRating: 0, + hardcoverReviewCount: 0, + doubanRating: 0, + doubanReviewCount: 0, + lubimyczytacRating: 0, + coverImage: 0 + }, + metadataPersistenceSettings: { + moveFilesToLibraryPattern: false, + saveToOriginalFile: false, + convertCbrCb7ToCbz: false + }, + metadataPublicReviewsSettings: { + downloadEnabled: false, + autoDownloadEnabled: false, + providers: [] + }, + koboSettings: { + convertToKepub: false, + conversionLimitInMb: 0, + conversionImageCompressionPercentage: 0, + convertCbxToEpub: false, + conversionLimitInMbForCbx: 0, + forceEnableHyphenation: false + }, + coverCroppingSettings: { + verticalCroppingEnabled: false, + horizontalCroppingEnabled: false, + aspectRatioThreshold: 0, + smartCroppingEnabled: false + }, + metadataDownloadOnBookdrop: false, + telemetryEnabled: false + }; + httpClientMock.get.mockReturnValue(of(mockSettings)); + service['fetchAppSettings']().subscribe(settings => { + expect(settings).toHaveProperty('oidcEnabled'); + expect(settings).toHaveProperty('remoteAuthEnabled'); + expect(settings).toHaveProperty('oidcProviderDetails'); + }); + }); + + it('should expect PublicAppSettings from fetchPublicSettings', () => { + const mockSettings: PublicAppSettings = { + oidcEnabled: false, + remoteAuthEnabled: true, + oidcProviderDetails: { + providerName: 'Provider', + clientId: 'id', + issuerUri: 'issuer', + claimMapping: { + username: 'username', + email: 'email', + name: 'name' + } + } + }; + httpClientMock.get.mockReturnValue(of(mockSettings)); + service['fetchPublicSettings']().subscribe(settings => { + expect(settings).toHaveProperty('oidcEnabled'); + expect(settings).toHaveProperty('remoteAuthEnabled'); + expect(settings).toHaveProperty('oidcProviderDetails'); + }); + }); + }); +}); + diff --git a/booklore-ui/src/app/shared/service/app-settings.service.ts b/booklore-ui/src/app/shared/service/app-settings.service.ts index 42c641d4c..9ab2f87f7 100644 --- a/booklore-ui/src/app/shared/service/app-settings.service.ts +++ b/booklore-ui/src/app/shared/service/app-settings.service.ts @@ -131,8 +131,8 @@ export class AppSettingsService { this.syncPublicSettings(current); } if (!enabled) { + const authService = this.injector.get(AuthService); setTimeout(() => { - const authService = this.injector.get(AuthService); authService.clearOIDCTokens(); }); } diff --git a/booklore-ui/src/app/shared/service/auth.service.spec.ts b/booklore-ui/src/app/shared/service/auth.service.spec.ts new file mode 100644 index 000000000..40b2f8f28 --- /dev/null +++ b/booklore-ui/src/app/shared/service/auth.service.spec.ts @@ -0,0 +1,309 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {HttpClient} from '@angular/common/http'; +import {of} from 'rxjs'; +import {AuthService} from './auth.service'; +import {OAuthService, OAuthStorage} from 'angular-oauth2-oidc'; +import {Router} from '@angular/router'; +import {PostLoginInitializerService} from '../../core/services/post-login-initializer.service'; +import {RxStompService} from '../websocket/rx-stomp.service'; + +describe('AuthService', () => { + let service: AuthService; + let httpClientMock: any; + let oAuthServiceMock: any; + let oAuthStorageMock: any; + let routerMock: any; + let postLoginInitializerMock: any; + let rxStompServiceMock: any; + let injectorMock: any; + + beforeEach(() => { + httpClientMock = { + post: vi.fn(), + get: vi.fn() + }; + oAuthServiceMock = { + getIdToken: vi.fn().mockReturnValue('oidc-token') + }; + oAuthStorageMock = { + removeItem: vi.fn() + }; + routerMock = { + navigate: vi.fn() + }; + postLoginInitializerMock = { + initialize: vi.fn().mockReturnValue(of(void 0)) + }; + rxStompServiceMock = { + updateConfig: vi.fn(), + activate: vi.fn(), + deactivate: vi.fn() + }; + injectorMock = { + get: vi.fn((token: any) => { + if (token === RxStompService) return rxStompServiceMock; + return undefined; + }) + }; + + vi.stubGlobal('localStorage', { + getItem: vi.fn().mockReturnValue(null), + setItem: vi.fn(), + removeItem: vi.fn() + }); + + TestBed.configureTestingModule({ + providers: [ + AuthService, + {provide: HttpClient, useValue: httpClientMock}, + {provide: OAuthService, useValue: oAuthServiceMock}, + {provide: OAuthStorage, useValue: oAuthStorageMock}, + {provide: Router, useValue: routerMock}, + {provide: PostLoginInitializerService, useValue: postLoginInitializerMock}, + {provide: RxStompService, useValue: rxStompServiceMock}, + {provide: 'Injector', useValue: injectorMock} + ] + }); + + // Patch inject() for Injector + (AuthService.prototype as any).injector = injectorMock; + + service = TestBed.inject(AuthService); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('should save and get internal tokens', () => { + service.saveInternalTokens('access', 'refresh'); + expect(localStorage.setItem).toHaveBeenCalledWith('accessToken_Internal', 'access'); + expect(localStorage.setItem).toHaveBeenCalledWith('refreshToken_Internal', 'refresh'); + expect(service.tokenSubject.value).toBe('access'); + }); + + it('should get internal access and refresh tokens', () => { + (localStorage.getItem as any).mockImplementation((key: string) => key === 'accessToken_Internal' ? 'access' : 'refresh'); + expect(service.getInternalAccessToken()).toBe('access'); + expect(service.getInternalRefreshToken()).toBe('refresh'); + }); + + it('should get OIDC access token', () => { + expect(service.getOidcAccessToken()).toBe('oidc-token'); + }); + + it('should call internalLogin and save tokens', () => { + httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'})); + const spy = vi.spyOn(service, 'saveInternalTokens'); + service.internalLogin({username: 'u', password: 'p'}).subscribe(res => { + expect(res.accessToken).toBe('a'); + expect(spy).toHaveBeenCalledWith('a', 'r'); + }); + }); + + it('should call internalRefreshToken and save tokens', () => { + (localStorage.getItem as any).mockReturnValue('refresh'); + httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'})); + const spy = vi.spyOn(service, 'saveInternalTokens'); + service.internalRefreshToken().subscribe(res => { + expect(res.accessToken).toBe('a'); + expect(spy).toHaveBeenCalledWith('a', 'r'); + }); + }); + + it('should call remoteLogin and save tokens', () => { + httpClientMock.get.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'})); + const spy = vi.spyOn(service, 'saveInternalTokens'); + service.remoteLogin().subscribe(res => { + expect(res.accessToken).toBe('a'); + expect(spy).toHaveBeenCalledWith('a', 'r'); + }); + }); + + it('should clear OIDC tokens and navigate if no internal tokens', () => { + (localStorage.getItem as any).mockReturnValue(null); + service.clearOIDCTokens(); + expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('access_token'); + expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('refresh_token'); + expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('id_token'); + expect(routerMock.navigate).toHaveBeenCalledWith(['/login']); + }); + + it('should not clear OIDC tokens if internal tokens exist', () => { + (localStorage.getItem as any).mockReturnValue('access'); + service.clearOIDCTokens(); + expect(oAuthStorageMock.removeItem).not.toHaveBeenCalled(); + expect(routerMock.navigate).not.toHaveBeenCalled(); + }); + + it('should logout and clear all tokens', () => { + service.getRxStompService = vi.fn().mockReturnValue(rxStompServiceMock); + const loc = {href: ''}; + vi.stubGlobal('window', {location: loc}); + service.logout(); + expect(localStorage.removeItem).toHaveBeenCalledWith('accessToken_Internal'); + expect(localStorage.removeItem).toHaveBeenCalledWith('refreshToken_Internal'); + expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('access_token'); + expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('refresh_token'); + expect(oAuthStorageMock.removeItem).toHaveBeenCalledWith('id_token'); + expect(rxStompServiceMock.deactivate).toHaveBeenCalled(); + expect(loc.href).toBe('/login'); + }); + + it('should initialize websocket connection if token exists', () => { + vi.spyOn(service, 'getOidcAccessToken').mockReturnValue('token'); + service.getRxStompService = vi.fn().mockReturnValue(rxStompServiceMock); + service['postLoginInitialized'] = false; + service.initializeWebSocketConnection(); + expect(rxStompServiceMock.updateConfig).toHaveBeenCalled(); + expect(rxStompServiceMock.activate).toHaveBeenCalled(); + }); + + it('should not initialize websocket connection if no token', () => { + vi.spyOn(service, 'getOidcAccessToken').mockReturnValue(null); + vi.spyOn(service, 'getInternalAccessToken').mockReturnValue(null); + service.getRxStompService = vi.fn().mockReturnValue(rxStompServiceMock); + service.initializeWebSocketConnection(); + expect(rxStompServiceMock.updateConfig).not.toHaveBeenCalled(); + expect(rxStompServiceMock.activate).not.toHaveBeenCalled(); + }); + + it('should call postLoginInitializer only once', () => { + service['postLoginInitialized'] = false; + service['handleSuccessfulAuth'](); + expect(postLoginInitializerMock.initialize).toHaveBeenCalled(); + service['handleSuccessfulAuth'](); + expect(postLoginInitializerMock.initialize).toHaveBeenCalledTimes(1); + }); + + it('should get RxStompService from injector', () => { + service['rxStompService'] = undefined; + expect(service.getRxStompService()).toBe(rxStompServiceMock); + expect(service.getRxStompService()).toBe(rxStompServiceMock); // cached + }); +}); + +describe('AuthService - API Contract Tests', () => { + let service: AuthService; + let httpClientMock: any; + let oAuthServiceMock: any; + let oAuthStorageMock: any; + let routerMock: any; + let postLoginInitializerMock: any; + let rxStompServiceMock: any; + let injectorMock: any; + + beforeEach(() => { + httpClientMock = { + post: vi.fn(), + get: vi.fn() + }; + oAuthServiceMock = {getIdToken: vi.fn()}; + oAuthStorageMock = {removeItem: vi.fn()}; + routerMock = {navigate: vi.fn()}; + postLoginInitializerMock = {initialize: vi.fn().mockReturnValue(of(void 0))}; + rxStompServiceMock = {updateConfig: vi.fn(), activate: vi.fn(), deactivate: vi.fn()}; + injectorMock = {get: vi.fn((token: any) => rxStompServiceMock)}; + + vi.stubGlobal('localStorage', { + getItem: vi.fn(), + setItem: vi.fn(), + removeItem: vi.fn() + }); + + TestBed.configureTestingModule({ + providers: [ + AuthService, + {provide: HttpClient, useValue: httpClientMock}, + {provide: OAuthService, useValue: oAuthServiceMock}, + {provide: OAuthStorage, useValue: oAuthStorageMock}, + {provide: Router, useValue: routerMock}, + {provide: PostLoginInitializerService, useValue: postLoginInitializerMock}, + {provide: RxStompService, useValue: rxStompServiceMock}, + {provide: 'Injector', useValue: injectorMock} + ] + }); + + (AuthService.prototype as any).injector = injectorMock; + service = TestBed.inject(AuthService); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe('HTTP endpoint contract', () => { + it('should call correct endpoint for internalLogin', () => { + httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'})); + service.internalLogin({username: 'u', password: 'p'}).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/auth\/login$/), + {username: 'u', password: 'p'} + ); + }); + + it('should call correct endpoint for internalRefreshToken', () => { + (localStorage.getItem as any).mockReturnValue('refresh'); + httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'})); + service.internalRefreshToken().subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/auth\/refresh$/), + {refreshToken: 'refresh'} + ); + }); + + it('should call correct endpoint for remoteLogin', () => { + httpClientMock.get.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'})); + service.remoteLogin().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/auth\/remote$/) + ); + }); + }); + + describe('Request payload contract', () => { + it('should send correct structure for internalLogin', () => { + httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'})); + const payload = {username: 'user', password: 'pass'}; + service.internalLogin(payload).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), payload); + }); + + it('should send correct structure for internalRefreshToken', () => { + (localStorage.getItem as any).mockReturnValue('refresh'); + httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'})); + service.internalRefreshToken().subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), {refreshToken: 'refresh'}); + }); + }); + + describe('Response type contract', () => { + it('should expect token object from internalLogin', () => { + httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'})); + service.internalLogin({username: 'u', password: 'p'}).subscribe(res => { + expect(res).toHaveProperty('accessToken'); + expect(res).toHaveProperty('refreshToken'); + expect(res).toHaveProperty('isDefaultPassword'); + }); + }); + + it('should expect token object from remoteLogin', () => { + httpClientMock.get.mockReturnValue(of({accessToken: 'a', refreshToken: 'r', isDefaultPassword: 'false'})); + service.remoteLogin().subscribe(res => { + expect(res).toHaveProperty('accessToken'); + expect(res).toHaveProperty('refreshToken'); + expect(res).toHaveProperty('isDefaultPassword'); + }); + }); + + it('should expect token object from internalRefreshToken', () => { + httpClientMock.post.mockReturnValue(of({accessToken: 'a', refreshToken: 'r'})); + service.internalRefreshToken().subscribe(res => { + expect(res).toHaveProperty('accessToken'); + expect(res).toHaveProperty('refreshToken'); + }); + }); + }); +}); + diff --git a/booklore-ui/src/app/shared/service/book-mark.service.spec.ts b/booklore-ui/src/app/shared/service/book-mark.service.spec.ts new file mode 100644 index 000000000..0b203fe4a --- /dev/null +++ b/booklore-ui/src/app/shared/service/book-mark.service.spec.ts @@ -0,0 +1,264 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {HttpClient} from '@angular/common/http'; +import {of, throwError} from 'rxjs'; +import {BookMarkService, BookMark, CreateBookMarkRequest, UpdateBookMarkRequest} from './book-mark.service'; + +describe('BookMarkService', () => { + let service: BookMarkService; + let httpClientMock: any; + + const mockBookmark: BookMark = { + id: 1, + userId: 2, + bookId: 3, + cfi: 'epubcfi(/6/2[cover]!/6)', + title: 'Bookmark 1', + color: 'yellow', + notes: 'note', + priority: 1, + createdAt: '2024-01-01T00:00:00Z', + updatedAt: '2024-01-01T01:00:00Z' + }; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + BookMarkService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + service = TestBed.inject(BookMarkService); + }); + + it('should get bookmarks for a book', () => { + httpClientMock.get.mockReturnValue(of([mockBookmark])); + service.getBookmarksForBook(3).subscribe(bookmarks => { + expect(bookmarks).toEqual([mockBookmark]); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/book/3')); + }); + }); + + it('should create a bookmark', () => { + httpClientMock.post.mockReturnValue(of(mockBookmark)); + const req: CreateBookMarkRequest = {bookId: 3, cfi: 'epubcfi(/6/2[cover]!/6)', title: 'Bookmark 1'}; + service.createBookmark(req).subscribe(bm => { + expect(bm).toEqual(mockBookmark); + expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req); + }); + }); + + it('should update a bookmark', () => { + httpClientMock.put.mockReturnValue(of(mockBookmark)); + const req: UpdateBookMarkRequest = {title: 'Updated', notes: 'Updated note'}; + service.updateBookmark(1, req).subscribe(bm => { + expect(bm).toEqual(mockBookmark); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/1'), req); + }); + }); + + it('should delete a bookmark', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteBookmark(1).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1')); + }); + }); + + it('should handle getBookmarksForBook error', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service.getBookmarksForBook(3).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + } + }); + }); + + it('should handle createBookmark error', () => { + httpClientMock.post.mockReturnValue(throwError(() => new Error('fail'))); + service.createBookmark({bookId: 3, cfi: 'cfi'}).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + } + }); + }); + + it('should handle updateBookmark error', () => { + httpClientMock.put.mockReturnValue(throwError(() => new Error('fail'))); + service.updateBookmark(1, {title: 'fail'}).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + } + }); + }); + + it('should handle deleteBookmark error', () => { + httpClientMock.delete.mockReturnValue(throwError(() => new Error('fail'))); + service.deleteBookmark(1).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + } + }); + }); +}); + +describe('BookMarkService - API Contract Tests', () => { + let service: BookMarkService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + BookMarkService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + service = TestBed.inject(BookMarkService); + }); + + describe('BookMark interface contract', () => { + it('should validate all required BookMark fields exist', () => { + const requiredFields: (keyof BookMark)[] = [ + 'id', 'bookId', 'cfi', 'title', 'createdAt' + ]; + const mockResponse: BookMark = { + id: 1, + bookId: 2, + cfi: 'cfi', + title: 't', + createdAt: '2024-01-01T00:00:00Z' + }; + httpClientMock.get.mockReturnValue(of([mockResponse])); + service.getBookmarksForBook(2).subscribe(bookmarks => { + requiredFields.forEach(field => { + expect(bookmarks[0]).toHaveProperty(field); + expect(bookmarks[0][field]).toBeDefined(); + }); + }); + }); + }); + + describe('HTTP endpoint contract', () => { + it('should call correct endpoint for getBookmarksForBook', () => { + httpClientMock.get.mockReturnValue(of([])); + service.getBookmarksForBook(5).subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/bookmarks\/book\/5$/)); + }); + + it('should call correct endpoint for createBookmark', () => { + httpClientMock.post.mockReturnValue(of({})); + const req: CreateBookMarkRequest = {bookId: 2, cfi: 'cfi', title: 't'}; + service.createBookmark(req).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/bookmarks$/), + req + ); + }); + + it('should call correct endpoint for updateBookmark', () => { + httpClientMock.put.mockReturnValue(of({})); + const req: UpdateBookMarkRequest = {title: 't'}; + service.updateBookmark(7, req).subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/bookmarks\/7$/), + req + ); + }); + + it('should call correct endpoint for deleteBookmark', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteBookmark(8).subscribe(); + expect(httpClientMock.delete).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/bookmarks\/8$/) + ); + }); + }); + + describe('Request payload contract', () => { + it('should send correct structure for createBookmark', () => { + httpClientMock.post.mockReturnValue(of({})); + const req: CreateBookMarkRequest = {bookId: 2, cfi: 'cfi', title: 't'}; + service.createBookmark(req).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req); + }); + + it('should send correct structure for updateBookmark', () => { + httpClientMock.put.mockReturnValue(of({})); + const req: UpdateBookMarkRequest = {title: 't', notes: 'n'}; + service.updateBookmark(9, req).subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.any(String), req); + }); + }); + + describe('Response type contract', () => { + it('should expect BookMark[] from getBookmarksForBook', () => { + const mockBookmarks: BookMark[] = [{ + id: 1, + bookId: 2, + cfi: 'cfi', + title: 't', + createdAt: '2024-01-01T00:00:00Z' + }]; + httpClientMock.get.mockReturnValue(of(mockBookmarks)); + service.getBookmarksForBook(2).subscribe(bookmarks => { + expect(Array.isArray(bookmarks)).toBe(true); + expect(bookmarks[0]).toHaveProperty('id'); + expect(bookmarks[0]).toHaveProperty('bookId'); + }); + }); + + it('should expect BookMark from createBookmark', () => { + const mockBookmark: BookMark = { + id: 1, + bookId: 2, + cfi: 'cfi', + title: 't', + createdAt: '2024-01-01T00:00:00Z' + }; + httpClientMock.post.mockReturnValue(of(mockBookmark)); + service.createBookmark({bookId: 2, cfi: 'cfi', title: 't'}).subscribe(bm => { + expect(bm).toHaveProperty('id'); + expect(bm).toHaveProperty('bookId'); + }); + }); + + it('should expect BookMark from updateBookmark', () => { + const mockBookmark: BookMark = { + id: 1, + bookId: 2, + cfi: 'cfi', + title: 't', + createdAt: '2024-01-01T00:00:00Z' + }; + httpClientMock.put.mockReturnValue(of(mockBookmark)); + service.updateBookmark(1, {title: 't'}).subscribe(bm => { + expect(bm).toHaveProperty('id'); + expect(bm).toHaveProperty('bookId'); + }); + }); + + it('should expect void from deleteBookmark', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteBookmark(1).subscribe(result => { + expect(result).toBeUndefined(); + }); + }); + }); +}); + diff --git a/booklore-ui/src/app/shared/service/book-mark.service.ts b/booklore-ui/src/app/shared/service/book-mark.service.ts index e385bb648..0d5fb6552 100644 --- a/booklore-ui/src/app/shared/service/book-mark.service.ts +++ b/booklore-ui/src/app/shared/service/book-mark.service.ts @@ -49,6 +49,7 @@ export class BookMarkService { deleteBookmark(bookmarkId: number): Observable { return this.http.delete(`${this.url}/${bookmarkId}`); } + updateBookmark(bookmarkId: number, request: UpdateBookMarkRequest): Observable { return this.http.put(`${this.url}/${bookmarkId}`, request); } diff --git a/booklore-ui/src/app/shared/service/book-metadata-host-service.ts b/booklore-ui/src/app/shared/service/book-metadata-host.service.ts similarity index 100% rename from booklore-ui/src/app/shared/service/book-metadata-host-service.ts rename to booklore-ui/src/app/shared/service/book-metadata-host.service.ts diff --git a/booklore-ui/src/app/shared/service/book-note.service.spec.ts b/booklore-ui/src/app/shared/service/book-note.service.spec.ts new file mode 100644 index 000000000..7c42b5404 --- /dev/null +++ b/booklore-ui/src/app/shared/service/book-note.service.spec.ts @@ -0,0 +1,215 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {HttpClient} from '@angular/common/http'; +import {of, throwError} from 'rxjs'; +import {BookNote, BookNoteService, CreateBookNoteRequest} from './book-note.service'; + +describe('BookNoteService', () => { + let service: BookNoteService; + let httpClientMock: any; + + const mockNote: BookNote = { + id: 1, + userId: 2, + bookId: 3, + title: 'Note Title', + content: 'Note content', + createdAt: '2024-01-01T00:00:00Z', + updatedAt: '2024-01-01T01:00:00Z' + }; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + delete: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + BookNoteService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + service = TestBed.inject(BookNoteService); + }); + + it('should get notes for a book', () => { + httpClientMock.get.mockReturnValue(of([mockNote])); + service.getNotesForBook(3).subscribe(notes => { + expect(notes).toEqual([mockNote]); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/book/3')); + }); + }); + + it('should create or update a note', () => { + httpClientMock.post.mockReturnValue(of(mockNote)); + const req: CreateBookNoteRequest = {bookId: 3, title: 'Note Title', content: 'Note content'}; + service.createOrUpdateNote(req).subscribe(note => { + expect(note).toEqual(mockNote); + expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req); + }); + }); + + it('should delete a note', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteNote(1).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringContaining('/1')); + }); + }); + + it('should handle getNotesForBook error', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service.getNotesForBook(3).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + } + }); + }); + + it('should handle createOrUpdateNote error', () => { + httpClientMock.post.mockReturnValue(throwError(() => new Error('fail'))); + service.createOrUpdateNote({bookId: 3, title: 'fail', content: 'fail'}).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + } + }); + }); + + it('should handle deleteNote error', () => { + httpClientMock.delete.mockReturnValue(throwError(() => new Error('fail'))); + service.deleteNote(1).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + } + }); + }); +}); + +describe('BookNoteService - API Contract Tests', () => { + let service: BookNoteService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + delete: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + BookNoteService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + service = TestBed.inject(BookNoteService); + }); + + describe('BookNote interface contract', () => { + it('should validate all required BookNote fields exist', () => { + const requiredFields: (keyof BookNote)[] = [ + 'id', 'userId', 'bookId', 'title', 'content', 'createdAt', 'updatedAt' + ]; + const mockResponse: BookNote = { + id: 1, + userId: 2, + bookId: 3, + title: 't', + content: 'c', + createdAt: '2024-01-01T00:00:00Z', + updatedAt: '2024-01-01T01:00:00Z' + }; + httpClientMock.get.mockReturnValue(of([mockResponse])); + service.getNotesForBook(3).subscribe(notes => { + requiredFields.forEach(field => { + expect(notes[0]).toHaveProperty(field); + expect(notes[0][field]).toBeDefined(); + }); + }); + }); + }); + + describe('HTTP endpoint contract', () => { + it('should call correct endpoint for getNotesForBook', () => { + httpClientMock.get.mockReturnValue(of([])); + service.getNotesForBook(5).subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/book-notes\/book\/5$/)); + }); + + it('should call correct endpoint for createOrUpdateNote', () => { + httpClientMock.post.mockReturnValue(of({})); + const req: CreateBookNoteRequest = {bookId: 2, title: 't', content: 'c'}; + service.createOrUpdateNote(req).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/book-notes$/), + req + ); + }); + + it('should call correct endpoint for deleteNote', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteNote(8).subscribe(); + expect(httpClientMock.delete).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/book-notes\/8$/) + ); + }); + }); + + describe('Request payload contract', () => { + it('should send correct structure for createOrUpdateNote', () => { + httpClientMock.post.mockReturnValue(of({})); + const req: CreateBookNoteRequest = {bookId: 2, title: 't', content: 'c'}; + service.createOrUpdateNote(req).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith(expect.any(String), req); + }); + }); + + describe('Response type contract', () => { + it('should expect BookNote[] from getNotesForBook', () => { + const mockNotes: BookNote[] = [{ + id: 1, + userId: 2, + bookId: 3, + title: 't', + content: 'c', + createdAt: '2024-01-01T00:00:00Z', + updatedAt: '2024-01-01T01:00:00Z' + }]; + httpClientMock.get.mockReturnValue(of(mockNotes)); + service.getNotesForBook(3).subscribe(notes => { + expect(Array.isArray(notes)).toBe(true); + expect(notes[0]).toHaveProperty('id'); + expect(notes[0]).toHaveProperty('title'); + }); + }); + + it('should expect BookNote from createOrUpdateNote', () => { + const mockNote: BookNote = { + id: 1, + userId: 2, + bookId: 3, + title: 't', + content: 'c', + createdAt: '2024-01-01T00:00:00Z', + updatedAt: '2024-01-01T01:00:00Z' + }; + httpClientMock.post.mockReturnValue(of(mockNote)); + service.createOrUpdateNote({bookId: 2, title: 't', content: 'c'}).subscribe(note => { + expect(note).toHaveProperty('id'); + expect(note).toHaveProperty('title'); + }); + }); + + it('should expect void from deleteNote', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteNote(1).subscribe(result => { + expect(result).toBeUndefined(); + }); + }); + }); +}); + diff --git a/booklore-ui/src/app/shared/service/custom-font.service.spec.ts b/booklore-ui/src/app/shared/service/custom-font.service.spec.ts new file mode 100644 index 000000000..773d5e979 --- /dev/null +++ b/booklore-ui/src/app/shared/service/custom-font.service.spec.ts @@ -0,0 +1,309 @@ +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} from 'rxjs'; +import {CustomFontService} from './custom-font.service'; +import {CustomFont, FontFormat} from '../model/custom-font.model'; +import {AuthService} from './auth.service'; + +describe('CustomFontService', () => { + let service: CustomFontService; + let httpClientMock: any; + let authServiceMock: any; + + const mockFont: CustomFont = { + id: 1, + fontName: 'TestFont', + originalFileName: 'testfont.ttf', + format: FontFormat.TTF, + fileSize: 1024, + uploadedAt: '2024-01-01T00:00:00Z' + }; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn() + }; + + authServiceMock = { + getOidcAccessToken: vi.fn().mockReturnValue('token'), + getInternalAccessToken: vi.fn().mockReturnValue(null) + }; + + (globalThis as any).FontFace = function (family: string, source: string, descriptors?: any) { + this.family = family; + this.source = source; + this.descriptors = descriptors; + this.load = vi.fn().mockResolvedValue(this); + }; + + const fontsSet: any[] = []; + (globalThis as any).document = { + fonts: { + add: vi.fn(font => fontsSet.push(font)), + delete: vi.fn(font => { + const idx = fontsSet.indexOf(font); + if (idx !== -1) fontsSet.splice(idx, 1); + }), + [Symbol.iterator]: function* () { + yield* fontsSet; + } + } + }; + + TestBed.configureTestingModule({ + providers: [ + CustomFontService, + {provide: HttpClient, useValue: httpClientMock}, + {provide: AuthService, useValue: authServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(CustomFontService)); + }); + + it('should initialize with empty fontsSubject', () => { + expect(service['fontsSubject'].value).toEqual([]); + }); + + it('should upload font and update cache', () => { + httpClientMock.post.mockReturnValue(of(mockFont)); + const file = new File(['dummy'], 'testfont.ttf'); + service.uploadFont(file, 'TestFont').subscribe(font => { + expect(font).toEqual(mockFont); + expect(service['fontsSubject'].value).toContainEqual(mockFont); + }); + }); + + it('should get user fonts and update cache', () => { + httpClientMock.get.mockReturnValue(of([mockFont])); + service.getUserFonts().subscribe(fonts => { + expect(fonts).toEqual([mockFont]); + expect(service['fontsSubject'].value).toEqual([mockFont]); + }); + }); + + it('should delete font and update cache', () => { + service['fontsSubject'].next([mockFont]); + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteFont(1).subscribe(result => { + expect(result).toBeUndefined(); + expect(service['fontsSubject'].value).toEqual([]); + }); + }); + + it('should get font URL', () => { + expect(service.getFontUrl(123)).toMatch(/\/api\/v1\/custom-fonts\/123\/file$/); + }); + + it('should append token to URL', () => { + const url = 'http://test.com/font.ttf'; + expect(service.appendToken(url)).toContain('token='); + }); + + it('should mark font as loaded after loadFontFace', async () => { + await service.loadFontFace(mockFont); + expect(service.isFontLoaded(mockFont.fontName)).toBe(true); + const fontsArr = Array.from((globalThis as any).document.fonts); + expect(fontsArr.some((f: any) => f.family === mockFont.fontName)).toBe(true); + }); + + it('should call removeFontFace on delete', () => { + const fontObj = {family: mockFont.fontName}; + (globalThis as any).document.fonts.add(fontObj); + service['fontsSubject'].next([mockFont]); + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteFont(mockFont.id).subscribe(() => { + const fontsArr = Array.from((globalThis as any).document.fonts); + expect(fontsArr.some((f: any) => f.family === mockFont.fontName)).toBe(false); + }); + }); + + it('should handle loadAllFonts', async () => { + vi.spyOn(service, 'loadFontFace').mockResolvedValue(undefined); + await service.loadAllFonts([mockFont]); + expect(service.loadFontFace).toHaveBeenCalledWith(mockFont); + }); + + it('should return false for isFontLoaded if not loaded', () => { + expect(service.isFontLoaded('NotLoaded')).toBe(false); + }); +}); + +describe('CustomFontService - API Contract Tests', () => { + let service: CustomFontService; + let httpClientMock: any; + let authServiceMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + post: vi.fn(), + put: vi.fn(), + delete: vi.fn() + }; + + authServiceMock = { + getOidcAccessToken: vi.fn().mockReturnValue('token'), + getInternalAccessToken: vi.fn().mockReturnValue(null) + }; + + TestBed.configureTestingModule({ + providers: [ + CustomFontService, + {provide: HttpClient, useValue: httpClientMock}, + {provide: AuthService, useValue: authServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(CustomFontService)); + }); + + describe('CustomFont interface contract', () => { + it('should validate all required CustomFont fields exist', () => { + const requiredFields: (keyof CustomFont)[] = [ + 'id', 'fontName', 'originalFileName', 'format', 'fileSize', 'uploadedAt' + ]; + const mockResponse: CustomFont = { + id: 1, + fontName: 'Font', + originalFileName: 'font.ttf', + format: FontFormat.TTF, + fileSize: 1234, + uploadedAt: '2024-01-01T00:00:00Z' + }; + httpClientMock.get.mockReturnValue(of([mockResponse])); + service.getUserFonts().subscribe(fonts => { + requiredFields.forEach(field => { + expect(fonts[0]).toHaveProperty(field); + expect(fonts[0][field]).toBeDefined(); + }); + }); + }); + + it('should fail if API returns CustomFont without required id field', () => { + const invalidResponse = [{ + fontName: 'Font', + originalFileName: 'font.ttf', + format: FontFormat.TTF, + fileSize: 1234, + uploadedAt: '2024-01-01T00:00:00Z' + }]; + httpClientMock.get.mockReturnValue(of(invalidResponse)); + service.getUserFonts().subscribe(fonts => { + expect(fonts[0]).not.toHaveProperty('id'); + }); + }); + }); + + describe('Enum value contract', () => { + it('should validate FontFormat enum values from API', () => { + const validValues = [FontFormat.TTF, FontFormat.OTF, FontFormat.WOFF, FontFormat.WOFF2]; + validValues.forEach(value => { + expect(Object.values(FontFormat)).toContain(value); + }); + expect(Object.keys(FontFormat)).toHaveLength(4); + }); + }); + + describe('HTTP endpoint contract', () => { + it('should call correct endpoint for getUserFonts', () => { + httpClientMock.get.mockReturnValue(of([])); + service.getUserFonts().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/custom-fonts$/)); + }); + + it('should call correct endpoint for uploadFont', () => { + httpClientMock.post.mockReturnValue(of({})); + const file = new File(['dummy'], 'font.ttf'); + service.uploadFont(file, 'Font').subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/custom-fonts\/upload$/), + expect.any(FormData) + ); + }); + + it('should call correct endpoint for deleteFont', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteFont(123).subscribe(); + expect(httpClientMock.delete).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/custom-fonts\/123$/)); + }); + + it('should call getFontUrl with correct format', () => { + expect(service.getFontUrl(42)).toMatch(/\/api\/v1\/custom-fonts\/42\/file$/); + }); + }); + + describe('Request payload contract', () => { + it('should send FormData with file and fontName for uploadFont', () => { + httpClientMock.post.mockReturnValue(of({})); + const file = new File(['dummy'], 'font.ttf'); + service.uploadFont(file, 'Font').subscribe(); + const formData = httpClientMock.post.mock.calls[0][1]; + expect(formData instanceof FormData).toBe(true); + expect(formData.has('file')).toBe(true); + expect(formData.has('fontName')).toBe(true); + }); + + it('should send FormData with only file if fontName not provided', () => { + httpClientMock.post.mockReturnValue(of({})); + const file = new File(['dummy'], 'font.ttf'); + service.uploadFont(file).subscribe(); + const formData = httpClientMock.post.mock.calls[0][1]; + expect(formData instanceof FormData).toBe(true); + expect(formData.has('file')).toBe(true); + expect(formData.has('fontName')).toBe(false); + }); + }); + + describe('Response type contract', () => { + it('should expect CustomFont array from getUserFonts', () => { + const mockFonts: CustomFont[] = [{ + id: 1, + fontName: 'Font', + originalFileName: 'font.ttf', + format: FontFormat.TTF, + fileSize: 1234, + uploadedAt: '2024-01-01T00:00:00Z' + }]; + httpClientMock.get.mockReturnValue(of(mockFonts)); + service.getUserFonts().subscribe(fonts => { + expect(Array.isArray(fonts)).toBe(true); + expect(fonts[0]).toHaveProperty('id'); + expect(fonts[0]).toHaveProperty('fontName'); + }); + }); + + it('should expect CustomFont from uploadFont', () => { + const mockFont: CustomFont = { + id: 2, + fontName: 'Font2', + originalFileName: 'font2.ttf', + format: FontFormat.OTF, + fileSize: 2048, + uploadedAt: '2024-01-02T00:00:00Z' + }; + httpClientMock.post.mockReturnValue(of(mockFont)); + const file = new File(['dummy'], 'font2.ttf'); + service.uploadFont(file, 'Font2').subscribe(font => { + expect(font).toHaveProperty('id'); + expect(font).toHaveProperty('fontName'); + expect(font).toHaveProperty('format'); + }); + }); + + it('should expect void from deleteFont', () => { + httpClientMock.delete.mockReturnValue(of(void 0)); + service.deleteFont(1).subscribe(result => { + expect(result).toBeUndefined(); + }); + }); + }); +}); + diff --git a/booklore-ui/src/app/shared/service/download-progress.service.spec.ts b/booklore-ui/src/app/shared/service/download-progress.service.spec.ts new file mode 100644 index 000000000..a6afde116 --- /dev/null +++ b/booklore-ui/src/app/shared/service/download-progress.service.spec.ts @@ -0,0 +1,174 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {DownloadProgressService} from './download-progress.service'; +import {Subject, take} from 'rxjs'; + +describe('DownloadProgressService', () => { + let service: DownloadProgressService; + + beforeEach(() => { + service = new DownloadProgressService(); + }); + + it('should initialize with default state', () => { + service.downloadProgress$.pipe(take(1)).subscribe(progress => { + expect(progress).toEqual({ + visible: false, + filename: '', + progress: 0, + loaded: 0, + total: 0 + }); + }); + expect(service.isDownloadInProgress()).toBe(false); + }); + + it('should start a download and set state', () => { + const cancelSubject = new Subject(); + service.startDownload('file.pdf', cancelSubject); + service.downloadProgress$.pipe(take(1)).subscribe(progress => { + expect(progress.visible).toBe(true); + expect(progress.filename).toBe('file.pdf'); + expect(progress.progress).toBe(0); + expect(progress.cancelSubject).toBe(cancelSubject); + }); + expect(service.isDownloadInProgress()).toBe(true); + }); + + it('should update progress and throttle updates', async () => { + const cancelSubject = new Subject(); + service.startDownload('file.pdf', cancelSubject); + + // First update should be immediate + service.updateProgress(50, 100); + service.downloadProgress$.pipe(take(1)).subscribe(progress => { + expect(progress.progress).toBe(50); + expect(progress.loaded).toBe(50); + expect(progress.total).toBe(100); + }); + + // Throttled update (simulate time) + vi.useFakeTimers(); + service.updateProgress(60, 100); + // Should not emit immediately + let emitted = false; + service.downloadProgress$.subscribe(progress => { + if (progress.loaded === 60) emitted = true; + }); + vi.advanceTimersByTime(100); + expect(emitted).toBe(true); + vi.useRealTimers(); + }); + + it('should immediately update when progress is 100', () => { + const cancelSubject = new Subject(); + service.startDownload('file.pdf', cancelSubject); + service.updateProgress(100, 100); + service.downloadProgress$.pipe(take(1)).subscribe(progress => { + expect(progress.progress).toBe(100); + expect(progress.loaded).toBe(100); + expect(progress.total).toBe(100); + }); + }); + + it('should complete download and reset state', () => { + const cancelSubject = new Subject(); + service.startDownload('file.pdf', cancelSubject); + service.completeDownload(); + service.downloadProgress$.pipe(take(1)).subscribe(progress => { + expect(progress.visible).toBe(false); + expect(progress.filename).toBe(''); + expect(progress.progress).toBe(0); + }); + expect(service.isDownloadInProgress()).toBe(false); + }); + + it('should cancel download and call cancelSubject', () => { + const cancelSubject = new Subject(); + const nextSpy = vi.fn(); + const completeSpy = vi.fn(); + cancelSubject.subscribe({next: nextSpy, complete: completeSpy}); + service.startDownload('file.pdf', cancelSubject); + service.cancelDownload(); + expect(nextSpy).toHaveBeenCalled(); + expect(completeSpy).toHaveBeenCalled(); + expect(service.isDownloadInProgress()).toBe(false); + }); +}); + +describe('DownloadProgressService - API Contract Tests', () => { + let service: DownloadProgressService; + + beforeEach(() => { + service = new DownloadProgressService(); + }); + + describe('DownloadProgress interface contract', () => { + it('should have all required fields', () => { + const cancelSubject = new Subject(); + service.startDownload('test.txt', cancelSubject); + service.downloadProgress$.pipe(take(1)).subscribe(progress => { + expect(progress).toHaveProperty('visible'); + expect(progress).toHaveProperty('filename'); + expect(progress).toHaveProperty('progress'); + expect(progress).toHaveProperty('loaded'); + expect(progress).toHaveProperty('total'); + expect(progress).toHaveProperty('cancelSubject'); + }); + }); + + it('should allow cancelSubject to be undefined after complete', () => { + service.completeDownload(); + service.downloadProgress$.pipe(take(1)).subscribe(progress => { + expect(progress.cancelSubject).toBeUndefined(); + }); + }); + }); + + describe('Behavior contract', () => { + it('should emit correct progress values', () => { + const cancelSubject = new Subject(); + service.startDownload('file.pdf', cancelSubject); + service.updateProgress(25, 100); + service.downloadProgress$.pipe(take(1)).subscribe(progress => { + expect(progress.progress).toBe(25); + expect(progress.loaded).toBe(25); + expect(progress.total).toBe(100); + }); + }); + + it('should not exceed 100% progress', () => { + const cancelSubject = new Subject(); + service.startDownload('file.pdf', cancelSubject); + service.updateProgress(150, 100); + service.downloadProgress$.pipe(take(1)).subscribe(progress => { + expect(progress.progress).toBe(100); + }); + }); + + it('should set progress to 0 if total is 0', () => { + const cancelSubject = new Subject(); + service.startDownload('file.pdf', cancelSubject); + service.updateProgress(50, 0); + service.downloadProgress$.pipe(take(1)).subscribe(progress => { + expect(progress.progress).toBe(0); + }); + }); + }); + + describe('API contract', () => { + it('should expose downloadProgress$ as observable', () => { + expect(typeof service.downloadProgress$.subscribe).toBe('function'); + }); + + it('should expose isDownloadInProgress as boolean', () => { + expect(typeof service.isDownloadInProgress()).toBe('boolean'); + }); + + it('should expose startDownload, updateProgress, completeDownload, cancelDownload', () => { + expect(typeof service.startDownload).toBe('function'); + expect(typeof service.updateProgress).toBe('function'); + expect(typeof service.completeDownload).toBe('function'); + expect(typeof service.cancelDownload).toBe('function'); + }); + }); +}); diff --git a/booklore-ui/src/app/shared/service/file-download.service.spec.ts b/booklore-ui/src/app/shared/service/file-download.service.spec.ts new file mode 100644 index 000000000..dfc8a25e4 --- /dev/null +++ b/booklore-ui/src/app/shared/service/file-download.service.spec.ts @@ -0,0 +1,215 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {HttpClient, HttpEventType, HttpHeaders, HttpResponse} from '@angular/common/http'; +import {of, Subject, throwError} from 'rxjs'; +import {FileDownloadService} from './file-download.service'; +import {DownloadProgressService} from './download-progress.service'; +import {MessageService} from 'primeng/api'; + +describe('FileDownloadService', () => { + let service: FileDownloadService; + let httpClientMock: any; + let downloadProgressServiceMock: any; + let messageServiceMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn() + }; + downloadProgressServiceMock = { + isDownloadInProgress: vi.fn().mockReturnValue(false), + startDownload: vi.fn(), + updateProgress: vi.fn(), + completeDownload: vi.fn() + }; + messageServiceMock = { + add: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + FileDownloadService, + {provide: HttpClient, useValue: httpClientMock}, + {provide: DownloadProgressService, useValue: downloadProgressServiceMock}, + {provide: MessageService, useValue: messageServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(FileDownloadService)); + }); + + it('should trigger download and handle progress and completion', () => { + const events = [ + {type: HttpEventType.DownloadProgress, loaded: 50, total: 100}, + { + type: HttpEventType.Response, + body: new Blob(['test']), + headers: new HttpHeaders(), + clone: () => this, + status: 200, + statusText: 'OK', + url: '', + ok: true + } + ]; + httpClientMock.get.mockReturnValue(of(...events)); + // Mock DOM for download + const appendChild = vi.fn(); + const removeChild = vi.fn(); + (globalThis as any).document = { + createElement: vi.fn().mockReturnValue({ + setAttribute: vi.fn(), + click: vi.fn(), + style: {}, + href: '', + download: '' + }), + body: {appendChild, removeChild} + }; + (globalThis as any).window = { + URL: { + createObjectURL: vi.fn().mockReturnValue('blob:url'), + revokeObjectURL: vi.fn() + } + }; + + service.downloadFile('/api/file', 'file.txt').subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith('/api/file', expect.objectContaining({observe: 'events'})); + expect(downloadProgressServiceMock.startDownload).toHaveBeenCalledWith('file.txt', expect.any(Subject)); + expect(downloadProgressServiceMock.updateProgress).toHaveBeenCalledWith(50, 100); + expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled(); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'})); + }); + + it('should extract filename from Content-Disposition header', () => { + const headers = new HttpHeaders({'Content-Disposition': "attachment; filename*=UTF-8''test%20file.txt"}); + const response = new HttpResponse({body: new Blob(['test']), headers}); + const filename = (service as any).extractFilenameFromResponse(response, 'default.txt'); + expect(filename).toBe('test file.txt'); + }); + + it('should fallback to default filename if Content-Disposition is missing', () => { + const headers = new HttpHeaders(); + const response = new HttpResponse({body: new Blob(['test']), headers}); + const filename = (service as any).extractFilenameFromResponse(response, 'default.txt'); + expect(filename).toBe('default.txt'); + }); + + it('should handle download error and show error message', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service.downloadFile('/api/file', 'file.txt').subscribe({ + error: () => { + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); + expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled(); + } + }); + }); + + it('should not show error message for AbortError', () => { + httpClientMock.get.mockReturnValue(throwError(() => ({name: 'AbortError'}))); + service.downloadFile('/api/file', 'file.txt').subscribe({ + error: () => { + expect(messageServiceMock.add).not.toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); + expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled(); + } + }); + }); + + it('should throw if no file content received', () => { + const response = new HttpResponse({body: undefined, headers: new HttpHeaders()}); + expect(() => (service as any).handleDownloadComplete(response, 'file.txt')).toThrow('No file content received'); + }); +}); + +describe('FileDownloadService - API Contract Tests', () => { + let service: FileDownloadService; + let httpClientMock: any; + let downloadProgressServiceMock: any; + let messageServiceMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn() + }; + downloadProgressServiceMock = { + isDownloadInProgress: vi.fn().mockReturnValue(false), + startDownload: vi.fn(), + updateProgress: vi.fn(), + completeDownload: vi.fn() + }; + messageServiceMock = { + add: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + FileDownloadService, + {provide: HttpClient, useValue: httpClientMock}, + {provide: DownloadProgressService, useValue: downloadProgressServiceMock}, + {provide: MessageService, useValue: messageServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(FileDownloadService)); + }); + + describe('API contract', () => { + it('should expose downloadFile as a function', () => { + expect(typeof service.downloadFile).toBe('function'); + }); + }); + + describe('HTTP endpoint contract', () => { + it('should call correct endpoint and options for downloadFile', () => { + httpClientMock.get.mockReturnValue(of()); + service.downloadFile('/api/file', 'file.txt'); + expect(httpClientMock.get).toHaveBeenCalledWith( + '/api/file', + expect.objectContaining({ + responseType: 'blob', + observe: 'events', + reportProgress: true + }) + ); + }); + }); + + describe('Request/Response contract', () => { + it('should expect Blob in HttpResponse', () => { + const headers = new HttpHeaders(); + const response = new HttpResponse({body: new Blob(['test']), headers}); + expect((service as any).extractFilenameFromResponse(response, 'file.txt')).toBe('file.txt'); + }); + + it('should handle Content-Disposition with encoded filename', () => { + const headers = new HttpHeaders({'Content-Disposition': "attachment; filename*=UTF-8''encoded%20file.pdf"}); + const response = new HttpResponse({body: new Blob(['test']), headers}); + expect((service as any).extractFilenameFromResponse(response, 'fallback.pdf')).toBe('encoded file.pdf'); + }); + }); + + describe('Behavior contract', () => { + it('should call startDownload and updateProgress on DownloadProgressService', () => { + httpClientMock.get.mockReturnValue(of({type: HttpEventType.DownloadProgress, loaded: 10, total: 20})); + service.downloadFile('/api/file', 'file.txt').subscribe(); + expect(downloadProgressServiceMock.startDownload).toHaveBeenCalled(); + expect(downloadProgressServiceMock.updateProgress).toHaveBeenCalledWith(10, 20); + }); + + it('should call completeDownload on finalize', () => { + httpClientMock.get.mockReturnValue(of({type: HttpEventType.Response, body: new Blob(['test']), headers: new HttpHeaders(), clone: () => this, status: 200, statusText: 'OK', url: '', ok: true})); + service.downloadFile('/api/file', 'file.txt').subscribe(); + expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled(); + }); + + it('should show success message on download complete', () => { + httpClientMock.get.mockReturnValue(of({type: HttpEventType.Response, body: new Blob(['test']), headers: new HttpHeaders(), clone: () => this, status: 200, statusText: 'OK', url: '', ok: true})); + service.downloadFile('/api/file', 'file.txt').subscribe(); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'})); + }); + }); +}); + diff --git a/booklore-ui/src/app/shared/service/file-download.service.ts b/booklore-ui/src/app/shared/service/file-download.service.ts index 9fe17ef6c..96be67a83 100644 --- a/booklore-ui/src/app/shared/service/file-download.service.ts +++ b/booklore-ui/src/app/shared/service/file-download.service.ts @@ -13,10 +13,10 @@ export class FileDownloadService { private downloadProgressService = inject(DownloadProgressService); private messageService = inject(MessageService); - downloadFile(url: string, defaultFilename: string): void { + downloadFile(url: string, defaultFilename: string): Observable { const cancelSubject = new Subject(); - this.initiateDownload(url) + return this.initiateDownload(url) .pipe( takeUntil(cancelSubject), tap(event => this.handleDownloadProgress(event, defaultFilename, cancelSubject)), @@ -25,8 +25,7 @@ export class FileDownloadService { this.handleDownloadError(error); return throwError(() => error); }) - ) - .subscribe(); + ); } private initiateDownload(url: string): Observable> { diff --git a/booklore-ui/src/app/shared/service/file-operations.service.spec.ts b/booklore-ui/src/app/shared/service/file-operations.service.spec.ts new file mode 100644 index 000000000..3b9e05878 --- /dev/null +++ b/booklore-ui/src/app/shared/service/file-operations.service.spec.ts @@ -0,0 +1,139 @@ +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 {FileMoveRequest, FileOperationsService} from './file-operations.service'; + +describe('FileOperationsService', () => { + let service: FileOperationsService; + let httpClientMock: any; + + const mockRequest: FileMoveRequest = { + bookIds: [1, 2], + moves: [ + {bookId: 1, targetLibraryId: 10, targetLibraryPathId: 100}, + {bookId: 2, targetLibraryId: 20, targetLibraryPathId: 200} + ] + }; + + beforeEach(() => { + httpClientMock = { + post: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + FileOperationsService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(FileOperationsService)); + }); + + it('should move files and return void', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + service.moveFiles(mockRequest).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/files\/move$/), + mockRequest + ); + }); + }); + + it('should handle move files error', () => { + httpClientMock.post.mockReturnValue(throwError(() => new Error('fail'))); + service.moveFiles(mockRequest).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); +}); + +describe('FileOperationsService - API Contract Tests', () => { + let service: FileOperationsService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + post: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + FileOperationsService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(FileOperationsService)); + }); + + describe('FileMoveRequest interface contract', () => { + it('should have required fields', () => { + const req: FileMoveRequest = { + bookIds: [1], + moves: [{bookId: 1, targetLibraryId: 2, targetLibraryPathId: 3}] + }; + expect(req).toHaveProperty('bookIds'); + expect(req).toHaveProperty('moves'); + expect(Array.isArray(req.bookIds)).toBe(true); + expect(Array.isArray(req.moves)).toBe(true); + expect(req.moves[0]).toHaveProperty('bookId'); + expect(req.moves[0]).toHaveProperty('targetLibraryId'); + expect(req.moves[0]).toHaveProperty('targetLibraryPathId'); + }); + }); + + describe('HTTP endpoint contract', () => { + it('should call correct endpoint for moveFiles', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + const req: FileMoveRequest = { + bookIds: [1], + moves: [{bookId: 1, targetLibraryId: 2, targetLibraryPathId: 3}] + }; + service.moveFiles(req).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/files\/move$/), + req + ); + }); + }); + + describe('Request payload contract', () => { + it('should send FileMoveRequest with correct structure', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + const req: FileMoveRequest = { + bookIds: [1, 2], + moves: [ + {bookId: 1, targetLibraryId: 10, targetLibraryPathId: 100}, + {bookId: 2, targetLibraryId: 20, targetLibraryPathId: 200} + ] + }; + service.moveFiles(req).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.any(String), + req + ); + }); + }); + + describe('Response type contract', () => { + it('should expect void from moveFiles', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + const req: FileMoveRequest = { + bookIds: [1], + moves: [{bookId: 1, targetLibraryId: 2, targetLibraryPathId: 3}] + }; + service.moveFiles(req).subscribe(result => { + expect(result).toBeUndefined(); + }); + }); + }); +}); diff --git a/booklore-ui/src/app/shared/service/file-operations-service.ts b/booklore-ui/src/app/shared/service/file-operations.service.ts similarity index 100% rename from booklore-ui/src/app/shared/service/file-operations-service.ts rename to booklore-ui/src/app/shared/service/file-operations.service.ts diff --git a/booklore-ui/src/app/shared/service/icon-picker.service.spec.ts b/booklore-ui/src/app/shared/service/icon-picker.service.spec.ts new file mode 100644 index 000000000..4877a5ea2 --- /dev/null +++ b/booklore-ui/src/app/shared/service/icon-picker.service.spec.ts @@ -0,0 +1,98 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {of, Subject, take} from 'rxjs'; +import {IconPickerService, IconSelection} from './icon-picker.service'; +import {DialogLauncherService} from '../services/dialog-launcher.service'; + +describe('IconPickerService', () => { + let service: IconPickerService; + let dialogLauncherServiceMock: any; + + beforeEach(() => { + dialogLauncherServiceMock = { + openIconPickerDialog: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + IconPickerService, + {provide: DialogLauncherService, useValue: dialogLauncherServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(IconPickerService)); + }); + + it('should open icon picker dialog and return selection observable', () => { + const selection: IconSelection = {type: 'PRIME_NG', value: 'pi pi-book'}; + const subject = new Subject(); + dialogLauncherServiceMock.openIconPickerDialog.mockReturnValue({onClose: subject.asObservable()}); + let result: IconSelection | undefined; + service.open().pipe(take(1)).subscribe(sel => { + result = sel; + }); + subject.next(selection); + expect(result).toEqual(selection); + }); + + it('should call openIconPickerDialog on open()', () => { + dialogLauncherServiceMock.openIconPickerDialog.mockReturnValue({onClose: of({type: 'CUSTOM_SVG', value: ''})}); + service.open().pipe(take(1)).subscribe(); + expect(dialogLauncherServiceMock.openIconPickerDialog).toHaveBeenCalled(); + }); +}); + +describe('IconPickerService - API Contract Tests', () => { + let service: IconPickerService; + let dialogLauncherServiceMock: any; + + beforeEach(() => { + dialogLauncherServiceMock = { + openIconPickerDialog: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + IconPickerService, + {provide: DialogLauncherService, useValue: dialogLauncherServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(IconPickerService)); + }); + + describe('IconSelection interface contract', () => { + it('should have required fields', () => { + const selection: IconSelection = {type: 'PRIME_NG', value: 'pi pi-user'}; + expect(selection).toHaveProperty('type'); + expect(selection).toHaveProperty('value'); + expect(typeof selection.type).toBe('string'); + expect(typeof selection.value).toBe('string'); + }); + + it('should only allow valid type values', () => { + const validTypes = ['PRIME_NG', 'CUSTOM_SVG']; + const selection: IconSelection = {type: 'PRIME_NG', value: 'pi pi-user'}; + expect(validTypes).toContain(selection.type); + }); + }); + + describe('API contract', () => { + it('should expose open as a function', () => { + expect(typeof service.open).toBe('function'); + }); + + it('should return Observable from open()', () => { + const selection: IconSelection = {type: 'CUSTOM_SVG', value: ''}; + dialogLauncherServiceMock.openIconPickerDialog.mockReturnValue({onClose: of(selection)}); + let result: IconSelection | undefined; + service.open().pipe(take(1)).subscribe(sel => { + result = sel; + }); + expect(result).toEqual(selection); + }); + }); +}); diff --git a/booklore-ui/src/app/shared/service/loading.service.ts b/booklore-ui/src/app/shared/service/loading.service.ts index ec0d5e21b..9ad88af78 100644 --- a/booklore-ui/src/app/shared/service/loading.service.ts +++ b/booklore-ui/src/app/shared/service/loading.service.ts @@ -1,5 +1,5 @@ -import { Injectable } from '@angular/core'; -import { BehaviorSubject } from 'rxjs'; +import {Injectable} from '@angular/core'; +import {BehaviorSubject} from 'rxjs'; @Injectable({ providedIn: 'root' @@ -7,12 +7,4 @@ import { BehaviorSubject } from 'rxjs'; export class LoadingService { private loadingSubject = new BehaviorSubject(false); loading$ = this.loadingSubject.asObservable(); - - show(): void { - this.loadingSubject.next(true); - } - - hide(): void { - this.loadingSubject.next(false); - } } diff --git a/booklore-ui/src/app/shared/service/local-storage.service.spec.ts b/booklore-ui/src/app/shared/service/local-storage.service.spec.ts new file mode 100644 index 000000000..d4cc533b5 --- /dev/null +++ b/booklore-ui/src/app/shared/service/local-storage.service.spec.ts @@ -0,0 +1,49 @@ +import {describe, it, expect, beforeEach, vi} from 'vitest'; +import {LocalStorageService} from './local-storage.service'; + +describe('LocalStorageService', () => { + let service: LocalStorageService; + + beforeEach(() => { + service = new LocalStorageService(); + vi.spyOn(window.localStorage, 'getItem').mockClear(); + vi.spyOn(window.localStorage, 'setItem').mockClear(); + vi.spyOn(window.localStorage, 'removeItem').mockClear(); + }); + + it('should get value from localStorage', () => { + window.localStorage.setItem('test', JSON.stringify({foo: 'bar'})); + const result = service.get<{foo: string}>('test'); + expect(result).toEqual({foo: 'bar'}); + }); + + it('should return null if key does not exist', () => { + window.localStorage.removeItem('notfound'); + const result = service.get('notfound'); + expect(result).toBeNull(); + }); + + it('should handle JSON parse error and return null', () => { + window.localStorage.setItem('bad', 'not-json'); + const result = service.get('bad'); + expect(result).toBeNull(); + }); + + it('should set value in localStorage', () => { + service.set('foo', {bar: 123}); + const stored = window.localStorage.getItem('foo'); + expect(stored).toBe(JSON.stringify({bar: 123})); + }); + + it('should handle set error gracefully', () => { + vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => { throw new Error('fail'); }); + expect(() => service.set('fail', {a: 1})).not.toThrow(); + }); + + it('should remove value from localStorage', () => { + window.localStorage.setItem('toremove', '1'); + service.remove('toremove'); + expect(window.localStorage.getItem('toremove')).toBeNull(); + }); +}); + diff --git a/booklore-ui/src/app/shared/service/local-storage-service.ts b/booklore-ui/src/app/shared/service/local-storage.service.ts similarity index 100% rename from booklore-ui/src/app/shared/service/local-storage-service.ts rename to booklore-ui/src/app/shared/service/local-storage.service.ts diff --git a/booklore-ui/src/app/shared/service/metadata-match-weights.service.spec.ts b/booklore-ui/src/app/shared/service/metadata-match-weights.service.spec.ts new file mode 100644 index 000000000..d99f46e21 --- /dev/null +++ b/booklore-ui/src/app/shared/service/metadata-match-weights.service.spec.ts @@ -0,0 +1,111 @@ +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 {MetadataMatchWeightsService} from './metadata-match-weights.service'; +import {API_CONFIG} from '../../core/config/api-config'; + +describe('MetadataMatchWeightsService', () => { + let service: MetadataMatchWeightsService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + post: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + MetadataMatchWeightsService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + + service = runInInjectionContext( + injector, + () => TestBed.inject(MetadataMatchWeightsService) + ); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); + + it('should call recalculateAll and return void', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + service.recalculateAll().subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.post).toHaveBeenCalledWith( + `${API_CONFIG.BASE_URL}/api/v1/books/metadata/recalculate-match-scores`, + {} + ); + }); + }); + + it('should handle error from recalculateAll', () => { + httpClientMock.post.mockReturnValue(throwError(() => new Error('fail'))); + service.recalculateAll().subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); +}); + +describe('MetadataMatchWeightsService - API Contract Tests', () => { + let service: MetadataMatchWeightsService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + post: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + MetadataMatchWeightsService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(MetadataMatchWeightsService)); + }); + + describe('HTTP endpoint contract', () => { + it('should call correct endpoint for recalculateAll', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + service.recalculateAll().subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + `${API_CONFIG.BASE_URL}/api/v1/books/metadata/recalculate-match-scores`, + {} + ); + }); + }); + + describe('Request payload contract', () => { + it('should send empty object as payload for recalculateAll', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + service.recalculateAll().subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.any(String), + {} + ); + }); + }); + + describe('Response type contract', () => { + it('should expect void from recalculateAll', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + service.recalculateAll().subscribe(result => { + expect(result).toBeUndefined(); + }); + }); + }); +}); + diff --git a/booklore-ui/src/app/shared/service/metadata-match-weights-service.ts b/booklore-ui/src/app/shared/service/metadata-match-weights.service.ts similarity index 50% rename from booklore-ui/src/app/shared/service/metadata-match-weights-service.ts rename to booklore-ui/src/app/shared/service/metadata-match-weights.service.ts index 8ae5920d3..5084597c5 100644 --- a/booklore-ui/src/app/shared/service/metadata-match-weights-service.ts +++ b/booklore-ui/src/app/shared/service/metadata-match-weights.service.ts @@ -3,29 +3,6 @@ import {HttpClient} from '@angular/common/http'; import {Observable} from 'rxjs'; import {API_CONFIG} from '../../core/config/api-config'; -export interface MetadataMatchWeights { - title: number; - subtitle: number; - description: number; - publisher: number; - publishedDate: number; - authors: number; - categories: number; - seriesName: number; - seriesNumber: number; - isbn13: number; - isbn10: number; - pageCount: number; - language: number; - amazonRating: number; - amazonReviewCount: number; - goodreadsRating: number; - goodreadsReviewCount: number; - hardcoverRating: number; - hardcoverReviewCount: number; - coverImage: number; -} - @Injectable({providedIn: 'root'}) export class MetadataMatchWeightsService { private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1`; diff --git a/booklore-ui/src/app/shared/service/metadata-progress.service.spec.ts b/booklore-ui/src/app/shared/service/metadata-progress.service.spec.ts new file mode 100644 index 000000000..cdaf7e5de --- /dev/null +++ b/booklore-ui/src/app/shared/service/metadata-progress.service.spec.ts @@ -0,0 +1,241 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {of} from 'rxjs'; + +import {MetadataProgressService} from './metadata-progress.service'; +import {MetadataBatchProgressNotification, MetadataBatchStatus} from '../model/metadata-batch-progress.model'; +import {MetadataTaskService} from '../../features/book/service/metadata-task'; +import {UserService} from '../../features/settings/user-management/user.service'; + +describe('MetadataProgressService', () => { + let service: MetadataProgressService; + let metadataTaskServiceMock: any; + let userServiceMock: any; + + const mockUserState = { + user: { + permissions: { + admin: true, + canEditMetadata: true + } + } + }; + + const mockTasks: MetadataBatchProgressNotification[] = [ + {taskId: '1', completed: 10, total: 100, message: '', status: MetadataBatchStatus.IN_PROGRESS, review: false}, + {taskId: '2', completed: 100, total: 100, message: '', status: MetadataBatchStatus.COMPLETED, review: false} + ]; + + beforeEach(() => { + metadataTaskServiceMock = { + getActiveTasks: vi.fn().mockReturnValue(of(mockTasks)) + }; + userServiceMock = { + userState$: of(mockUserState) + }; + + TestBed.configureTestingModule({ + providers: [ + MetadataProgressService, + {provide: MetadataTaskService, useValue: metadataTaskServiceMock}, + {provide: UserService, useValue: userServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext( + injector, + () => TestBed.inject(MetadataProgressService) + ); + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); + + it('should initialize and fetch active tasks if user has permissions', () => { + expect(metadataTaskServiceMock.getActiveTasks).toHaveBeenCalled(); + }); + + it('should not fetch active tasks if user has no permissions', () => { + userServiceMock.userState$ = of({user: {permissions: {admin: false, canEditMetadata: false}}}); + metadataTaskServiceMock.getActiveTasks.mockClear(); + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + MetadataProgressService, + {provide: MetadataTaskService, useValue: metadataTaskServiceMock}, + {provide: UserService, useValue: userServiceMock} + ] + }); + const injector = TestBed.inject(EnvironmentInjector); + TestBed.inject(MetadataProgressService); + expect(metadataTaskServiceMock.getActiveTasks).not.toHaveBeenCalled(); + }); + + it('should handle incoming progress and update state', () => { + const progress: MetadataBatchProgressNotification = { + taskId: '3', + completed: 50, + total: 100, + message: '', + status: MetadataBatchStatus.IN_PROGRESS, + review: false + }; + let update: MetadataBatchProgressNotification | undefined; + const sub = service.progressUpdates$.subscribe(val => update = val); + service.handleIncomingProgress(progress); + expect(update).toEqual(progress); + expect(service.getActiveTasks()['3']).toEqual(progress); + sub.unsubscribe(); + }); + + it('should clear task from active tasks', () => { + const progress: MetadataBatchProgressNotification = { + taskId: '4', + completed: 20, + total: 100, + message: '', + status: MetadataBatchStatus.IN_PROGRESS, + review: false + }; + service.handleIncomingProgress(progress); + expect(service.getActiveTasks()['4']).toBeDefined(); + service.clearTask('4'); + expect(service.getActiveTasks()['4']).toBeUndefined(); + }); + + it('should complete all subjects on destroy', () => { + const spy = vi.spyOn(service['progressUpdatesSubject'], 'complete'); + service.ngOnDestroy(); + expect(spy).toHaveBeenCalled(); + }); +}); + +describe('MetadataProgressService - API Contract Tests', () => { + let service: MetadataProgressService; + let metadataTaskServiceMock: any; + let userServiceMock: any; + + beforeEach(() => { + metadataTaskServiceMock = { + getActiveTasks: vi.fn().mockReturnValue(of([])) + }; + userServiceMock = { + userState$: of({ + user: { + permissions: { + admin: true, + canEditMetadata: true + } + } + }) + }; + + TestBed.configureTestingModule({ + providers: [ + MetadataProgressService, + {provide: MetadataTaskService, useValue: metadataTaskServiceMock}, + {provide: UserService, useValue: userServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext( + injector, + () => TestBed.inject(MetadataProgressService) + ); + }); + + describe('MetadataBatchProgressNotification contract', () => { + it('should require taskId, completed, total, message, status, and review fields', () => { + const progress: MetadataBatchProgressNotification = { + taskId: 'abc', + completed: 42, + total: 100, + message: '', + status: MetadataBatchStatus.IN_PROGRESS, + review: false + }; + expect(progress).toHaveProperty('taskId'); + expect(progress).toHaveProperty('completed'); + expect(progress).toHaveProperty('total'); + expect(progress).toHaveProperty('message'); + expect(progress).toHaveProperty('status'); + expect(progress).toHaveProperty('review'); + }); + }); + + describe('Active tasks structure', () => { + it('should return an object with taskId keys and progress notification values', () => { + const progress: MetadataBatchProgressNotification = { + taskId: 'xyz', + completed: 99, + total: 100, + message: '', + status: MetadataBatchStatus.COMPLETED, + review: false + }; + service.handleIncomingProgress(progress); + const active = service.getActiveTasks(); + expect(active).toHaveProperty('xyz'); + expect(active['xyz']).toEqual(progress); + }); + }); + + describe('Observable contract', () => { + it('should emit progress updates on progressUpdates$', () => { + const progress: MetadataBatchProgressNotification = { + taskId: 'emit', + completed: 1, + total: 100, + message: '', + status: MetadataBatchStatus.IN_PROGRESS, + review: false + }; + let emitted: MetadataBatchProgressNotification | undefined; + const sub = service.progressUpdates$.subscribe(val => { + emitted = val; + }); + service.handleIncomingProgress(progress); + expect(emitted).toEqual(progress); + sub.unsubscribe(); + }); + + it('should emit active tasks on activeTasks$', () => { + const progress: MetadataBatchProgressNotification = { + taskId: 'active', + completed: 2, + total: 100, + message: '', + status: MetadataBatchStatus.IN_PROGRESS, + review: false + }; + let emitted: { [taskId: string]: MetadataBatchProgressNotification } | undefined; + const sub = service.activeTasks$.subscribe(val => { + emitted = val; + }); + service.handleIncomingProgress(progress); + expect(emitted && emitted['active']).toEqual(progress); + sub.unsubscribe(); + }); + }); + + describe('Permissions contract', () => { + it('should only fetch tasks if user has admin or canEditMetadata', () => { + userServiceMock.userState$ = of({user: {permissions: {admin: false, canEditMetadata: false}}}); + metadataTaskServiceMock.getActiveTasks.mockClear(); + TestBed.resetTestingModule(); + TestBed.configureTestingModule({ + providers: [ + MetadataProgressService, + {provide: MetadataTaskService, useValue: metadataTaskServiceMock}, + {provide: UserService, useValue: userServiceMock} + ] + }); + TestBed.inject(MetadataProgressService); + expect(metadataTaskServiceMock.getActiveTasks).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/booklore-ui/src/app/shared/service/metadata-progress-service.ts b/booklore-ui/src/app/shared/service/metadata-progress.service.ts similarity index 100% rename from booklore-ui/src/app/shared/service/metadata-progress-service.ts rename to booklore-ui/src/app/shared/service/metadata-progress.service.ts diff --git a/booklore-ui/src/app/shared/service/page-title.service.spec.ts b/booklore-ui/src/app/shared/service/page-title.service.spec.ts new file mode 100644 index 000000000..ab18b86e0 --- /dev/null +++ b/booklore-ui/src/app/shared/service/page-title.service.spec.ts @@ -0,0 +1,84 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {Title} from '@angular/platform-browser'; +import {PageTitleService} from './page-title.service'; +import {Book, BookType} from '../../features/book/model/book.model'; + +describe('PageTitleService', () => { + let service: PageTitleService; + let titleService: Title; + let setTitleMock: ReturnType; + + beforeEach(() => { + setTitleMock = vi.fn(); + TestBed.configureTestingModule({ + providers: [ + PageTitleService, + { provide: Title, useValue: { setTitle: setTitleMock } } + ] + }); + service = TestBed.inject(PageTitleService); + titleService = TestBed.inject(Title); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('should set page title with setPageTitle', () => { + service.setPageTitle('Dashboard'); + expect(setTitleMock).toHaveBeenCalledWith('Dashboard - BookLore'); + }); + + it('should set book page title with all fields', () => { + const book: Book = { + id: 1, + bookType: 'PDF' as BookType, + libraryId: 2, + libraryName: 'Lib', + fileName: 'file.pdf', + metadata: { + bookId: 1, + title: 'Book Title', + seriesName: 'Series', + authors: ['Author1', 'Author2'] + } + }; + service.setBookPageTitle(book); + expect(setTitleMock).toHaveBeenCalledWith( + 'Lib/Book Title (Series series) - by Author1 and Author2 (PDF) - BookLore' + ); + }); + + it('should set book page title without series and authors', () => { + const book: Book = { + id: 1, + bookType: 'EPUB' as BookType, + libraryId: 2, + libraryName: 'Lib', + fileName: 'file.epub', + metadata: { + bookId: 1, + title: 'Book Title' + } + }; + service.setBookPageTitle(book); + expect(setTitleMock).toHaveBeenCalledWith( + 'Lib/Book Title (EPUB) - BookLore' + ); + }); + + it('should set book page title with fallback to fileName', () => { + const book: Book = { + id: 1, + bookType: 'CBX' as BookType, + libraryId: 2, + libraryName: 'Lib', + fileName: 'file.cbx' + }; + service.setBookPageTitle(book); + expect(setTitleMock).toHaveBeenCalledWith( + 'Lib/file.cbx (CBX) - BookLore' + ); + }); +}); diff --git a/booklore-ui/src/app/shared/service/page-title.service.ts b/booklore-ui/src/app/shared/service/page-title.service.ts index 7ed16b1ab..c89b74e6b 100644 --- a/booklore-ui/src/app/shared/service/page-title.service.ts +++ b/booklore-ui/src/app/shared/service/page-title.service.ts @@ -4,7 +4,7 @@ import {Book} from "../../features/book/model/book.model"; @Injectable({providedIn: 'root'}) export class PageTitleService { - private titleService = inject(Title) + protected titleService = inject(Title) private appName = 'BookLore' @@ -22,4 +22,4 @@ export class PageTitleService { setPageTitle(pageTitle: string) { this.titleService.setTitle([pageTitle, this.appName].filter(part => part).join(' - ')); } -} \ No newline at end of file +} diff --git a/booklore-ui/src/app/shared/service/reading-session-api.service.spec.ts b/booklore-ui/src/app/shared/service/reading-session-api.service.spec.ts new file mode 100644 index 000000000..9cd18dcfb --- /dev/null +++ b/booklore-ui/src/app/shared/service/reading-session-api.service.spec.ts @@ -0,0 +1,252 @@ +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 {CreateReadingSessionDto, PageableResponse, ReadingSessionApiService, ReadingSessionResponse} from './reading-session-api.service'; +import {BookType} from '../../features/book/model/book.model'; + +describe('ReadingSessionApiService', () => { + let service: ReadingSessionApiService; + let httpClientMock: any; + + const BASE_URL = '/api/v1/reading-sessions'; + + const mockSessionDto: CreateReadingSessionDto = { + bookId: 1, + bookType: 'PDF' as BookType, + startTime: '2024-01-01T00:00:00Z', + endTime: '2024-01-01T00:10:00Z', + durationSeconds: 600, + durationFormatted: '10m 0s', + startProgress: 0, + endProgress: 10, + progressDelta: 10, + startLocation: 'start', + endLocation: 'end' + }; + + const mockPageableResponse: PageableResponse = { + content: [{ + id: 1, + bookId: 1, + bookTitle: 'Book', + bookType: 'PDF', + startTime: '2024-01-01T00:00:00Z', + endTime: '2024-01-01T00:10:00Z', + durationSeconds: 600, + startProgress: 0, + endProgress: 10, + progressDelta: 10, + startLocation: 'start', + endLocation: 'end', + createdAt: '2024-01-01T00:10:01Z' + }], + pageable: { + pageNumber: 0, + pageSize: 5, + sort: {empty: true, sorted: false, unsorted: true}, + offset: 0, + paged: true, + unpaged: false + }, + totalElements: 1, + last: true, + totalPages: 1, + numberOfElements: 1, + first: true, + size: 5, + number: 0, + sort: {empty: true, sorted: false, unsorted: true}, + empty: false + }; + + beforeEach(() => { + httpClientMock = { + post: vi.fn(), + get: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + ReadingSessionApiService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(ReadingSessionApiService)); + }); + + it('should call POST to createSession', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + service.createSession(mockSessionDto).subscribe(result => { + expect(result).toBeUndefined(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringContaining(BASE_URL), + mockSessionDto + ); + }); + }); + + it('should call GET to getSessionsByBookId with correct params', () => { + httpClientMock.get.mockReturnValue(of(mockPageableResponse)); + service.getSessionsByBookId(1, 2, 10).subscribe(resp => { + expect(resp).toEqual(mockPageableResponse); + expect(httpClientMock.get).toHaveBeenCalledWith( + expect.stringContaining(`${BASE_URL}/book/1`), + expect.objectContaining({ + params: expect.any(HttpParams) + }) + ); + const params = httpClientMock.get.mock.calls[0][1].params; + expect(params.get('page')).toBe('2'); + expect(params.get('size')).toBe('10'); + }); + }); + + it('should default to page=0 and size=5 if not provided', () => { + httpClientMock.get.mockReturnValue(of(mockPageableResponse)); + service.getSessionsByBookId(2).subscribe(); + const params = httpClientMock.get.mock.calls[0][1].params; + expect(params.get('page')).toBe('0'); + expect(params.get('size')).toBe('5'); + }); + + it('should handle error in createSession', () => { + httpClientMock.post.mockReturnValue(throwError(() => new Error('fail'))); + service.createSession(mockSessionDto).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should handle error in getSessionsByBookId', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service.getSessionsByBookId(1).subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should send beacon successfully', () => { + const sendBeaconMock = vi.fn().mockReturnValue(true); + (globalThis.navigator as any) = {sendBeacon: sendBeaconMock}; + const result = service.sendSessionBeacon(mockSessionDto); + expect(sendBeaconMock).toHaveBeenCalledWith( + expect.stringContaining(BASE_URL), + expect.any(Blob) + ); + expect(result).toBe(true); + }); + + it('should return false if sendBeacon throws', () => { + (globalThis.navigator as any) = { + sendBeacon: vi.fn().mockImplementation(() => { + throw new Error('fail'); + }) + }; + const result = service.sendSessionBeacon(mockSessionDto); + expect(result).toBe(false); + }); +}); + +describe('ReadingSessionApiService - API Contract Tests', () => { + let service: ReadingSessionApiService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + post: vi.fn(), + get: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + ReadingSessionApiService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(ReadingSessionApiService)); + }); + + it('should call correct endpoint for createSession', () => { + httpClientMock.post.mockReturnValue(of(void 0)); + const dto: CreateReadingSessionDto = { + bookId: 1, + bookType: 'PDF', + startTime: '2024-01-01T00:00:00Z', + endTime: '2024-01-01T00:10:00Z', + durationSeconds: 600, + durationFormatted: '10m 0s' + }; + service.createSession(dto).subscribe(); + expect(httpClientMock.post).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/reading-sessions$/), + dto + ); + }); + + it('should call correct endpoint for getSessionsByBookId', () => { + httpClientMock.get.mockReturnValue(of({content: []})); + service.getSessionsByBookId(123).subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/reading-sessions\/book\/123$/), + expect.objectContaining({params: expect.any(HttpParams)}) + ); + }); + + it('should send beacon to correct endpoint', () => { + const sendBeaconMock = vi.fn().mockReturnValue(true); + (globalThis.navigator as any) = {sendBeacon: sendBeaconMock}; + const dto: CreateReadingSessionDto = { + bookId: 1, + bookType: 'PDF', + startTime: '2024-01-01T00:00:00Z', + endTime: '2024-01-01T00:10:00Z', + durationSeconds: 600, + durationFormatted: '10m 0s' + }; + service.sendSessionBeacon(dto); + expect(sendBeaconMock).toHaveBeenCalledWith( + expect.stringMatching(/\/api\/v1\/reading-sessions$/), + expect.any(Blob) + ); + }); + + it('should expect PageableResponse from getSessionsByBookId', () => { + const mockResponse: PageableResponse = { + content: [], + pageable: { + pageNumber: 0, + pageSize: 5, + sort: {empty: true, sorted: false, unsorted: true}, + offset: 0, + paged: true, + unpaged: false + }, + totalElements: 0, + last: true, + totalPages: 1, + numberOfElements: 0, + first: true, + size: 5, + number: 0, + sort: {empty: true, sorted: false, unsorted: true}, + empty: true + }; + httpClientMock.get.mockReturnValue(of(mockResponse)); + service.getSessionsByBookId(1).subscribe(resp => { + expect(resp).toHaveProperty('content'); + expect(Array.isArray(resp.content)).toBe(true); + expect(resp).toHaveProperty('totalElements'); + }); + }); +}); + diff --git a/booklore-ui/src/app/shared/service/reading-session.service.spec.ts b/booklore-ui/src/app/shared/service/reading-session.service.spec.ts new file mode 100644 index 000000000..bec667937 --- /dev/null +++ b/booklore-ui/src/app/shared/service/reading-session.service.spec.ts @@ -0,0 +1,250 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {BookType} from '../../features/book/model/book.model'; +import {ReadingSessionService, ReadingSession} from './reading-session.service'; +import {ReadingSessionApiService, CreateReadingSessionDto} from './reading-session-api.service'; +import {of} from 'rxjs'; + +describe('ReadingSessionService', () => { + let service: ReadingSessionService; + let apiServiceMock: any; + + const now = new Date(); + const mockSession: ReadingSession = { + bookId: 42, + bookType: 'PDF' as BookType, + startTime: now, + startLocation: 'start-cfi', + startProgress: 10 + }; + + beforeEach(() => { + apiServiceMock = { + createSession: vi.fn().mockReturnValue(of(void 0)), + sendSessionBeacon: vi.fn().mockReturnValue(true) + }; + + TestBed.configureTestingModule({ + providers: [ + ReadingSessionService, + {provide: ReadingSessionApiService, useValue: apiServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(ReadingSessionService)); + }); + + it('should start a session', () => { + service.startSession(1, 'PDF', 'loc', 5); + expect(service.isSessionActive()).toBe(true); + }); + + it('should end a session and send to backend if duration is sufficient', () => { + vi.useFakeTimers(); + service.startSession(1, 'PDF', 'loc', 5); + // Simulate session duration > MIN_SESSION_DURATION_SECONDS + (service as any).currentSession!.startTime = new Date(Date.now() - 60000); + service.endSession('endloc', 10); + expect(apiServiceMock.createSession).toHaveBeenCalled(); + expect(service.isSessionActive()).toBe(false); + vi.useRealTimers(); + }); + + it('should discard session if duration is too short', () => { + vi.useFakeTimers(); + service.startSession(1, 'PDF', 'loc', 5); + (service as any).currentSession!.startTime = new Date(Date.now() - 10000); + service.endSession('endloc', 10); + expect(apiServiceMock.createSession).not.toHaveBeenCalled(); + expect(service.isSessionActive()).toBe(false); + vi.useRealTimers(); + }); + + it('should update progress', () => { + service.startSession(1, 'PDF', 'loc', 5); + service.updateProgress('newloc', 15); + const session = (service as any).currentSession; + expect(session.endLocation).toBe('newloc'); + expect(session.endProgress).toBe(15); + }); + + it('should end session synchronously with sendSessionBeacon', () => { + service.startSession(1, 'PDF', 'loc', 5); + (service as any).currentSession!.startTime = new Date(Date.now() - 60000); + service['endSessionSync'](); + expect(apiServiceMock.sendSessionBeacon).toHaveBeenCalled(); + expect(service.isSessionActive()).toBe(false); + }); + + it('should not send beacon if session duration is too short', () => { + service.startSession(1, 'PDF', 'loc', 5); + (service as any).currentSession!.startTime = new Date(Date.now() - 10000); + service['endSessionSync'](); + expect(apiServiceMock.sendSessionBeacon).not.toHaveBeenCalled(); + expect(service.isSessionActive()).toBe(false); + }); + + it('should return false for isSessionActive when no session', () => { + expect(service.isSessionActive()).toBe(false); + }); + + it('should build session data correctly', () => { + const endTime = new Date(now.getTime() + 60000); + const session: ReadingSession = { + bookId: 1, + bookType: 'PDF', + startTime: now, + endTime, + durationSeconds: 60, + startProgress: 10, + endProgress: 20, + progressDelta: 10, + startLocation: 'loc1', + endLocation: 'loc2' + }; + const dto = (service as any).buildSessionData(session, endTime, 60); + expect(dto.bookId).toBe(1); + expect(dto.bookType).toBe('PDF'); + expect(dto.durationSeconds).toBe(60); + expect(dto.startProgress).toBe(10); + expect(dto.endProgress).toBe(20); + expect(dto.progressDelta).toBe(10); + expect(dto.startLocation).toBe('loc1'); + expect(dto.endLocation).toBe('loc2'); + expect(typeof dto.startTime).toBe('string'); + expect(typeof dto.endTime).toBe('string'); + expect(dto.durationFormatted).toBe('1m 0s'); + }); + + it('should format duration correctly', () => { + expect((service as any).formatDuration(3661)).toBe('1h 1m 1s'); + expect((service as any).formatDuration(61)).toBe('1m 1s'); + expect((service as any).formatDuration(10)).toBe('10s'); + }); +}); + +describe('ReadingSessionService - API Contract Tests', () => { + let service: ReadingSessionService; + let apiServiceMock: any; + + beforeEach(() => { + apiServiceMock = { + createSession: vi.fn().mockReturnValue(of(void 0)), + sendSessionBeacon: vi.fn().mockReturnValue(true) + }; + + TestBed.configureTestingModule({ + providers: [ + ReadingSessionService, + {provide: ReadingSessionApiService, useValue: apiServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(ReadingSessionService)); + }); + + it('should call createSession with correct payload', () => { + const session: ReadingSession = { + bookId: 1, + bookType: 'PDF', + startTime: new Date(Date.now() - 60000), + endTime: new Date(), + durationSeconds: 60, + startProgress: 10, + endProgress: 20, + progressDelta: 10, + startLocation: 'loc1', + endLocation: 'loc2' + }; + (service as any).sendSessionToBackend(session); + expect(apiServiceMock.createSession).toHaveBeenCalledWith(expect.objectContaining({ + bookId: 1, + bookType: 'PDF', + durationSeconds: 60, + startProgress: 10, + endProgress: 20, + progressDelta: 10, + startLocation: 'loc1', + endLocation: 'loc2' + })); + }); + + it('should call sendSessionBeacon with correct payload', () => { + const session: ReadingSession = { + bookId: 2, + bookType: 'EPUB', + startTime: new Date(Date.now() - 120000), + startProgress: 0, + endProgress: 100, + progressDelta: 100, + startLocation: 'start', + endLocation: 'end' + }; + const endTime = new Date(); + const durationSeconds = 120; + const dto = (service as any).buildSessionData(session, endTime, durationSeconds); + (service as any).currentSession = session; + apiServiceMock.sendSessionBeacon.mockClear(); + (service as any).endSessionSync(); + expect(apiServiceMock.sendSessionBeacon).toHaveBeenCalledWith(expect.objectContaining({ + bookId: 2, + bookType: 'EPUB', + startLocation: 'start', + endLocation: 'end' + })); + }); + + it('should not call createSession if endTime or durationSeconds missing', () => { + const session: ReadingSession = { + bookId: 1, + bookType: 'PDF', + startTime: new Date() + // missing endTime and durationSeconds + }; + (service as any).sendSessionToBackend(session); + expect(apiServiceMock.createSession).not.toHaveBeenCalled(); + }); + + it('should not call sendSessionBeacon if duration too short', () => { + const session: ReadingSession = { + bookId: 1, + bookType: 'PDF', + startTime: new Date(Date.now() - 10000) + }; + (service as any).currentSession = session; + apiServiceMock.sendSessionBeacon.mockClear(); + (service as any).endSessionSync(); + expect(apiServiceMock.sendSessionBeacon).not.toHaveBeenCalled(); + }); + + it('should send correct types in CreateReadingSessionDto', () => { + const session: ReadingSession = { + bookId: 3, + bookType: 'CBX', + startTime: new Date(Date.now() - 180000), + endTime: new Date(), + durationSeconds: 180, + startProgress: 0, + endProgress: 50, + progressDelta: 50, + startLocation: 'foo', + endLocation: 'bar' + }; + const dto: CreateReadingSessionDto = (service as any).buildSessionData(session, session.endTime!, session.durationSeconds!); + expect(typeof dto.bookId).toBe('number'); + expect(typeof dto.bookType).toBe('string'); + expect(typeof dto.startTime).toBe('string'); + expect(typeof dto.endTime).toBe('string'); + expect(typeof dto.durationSeconds).toBe('number'); + expect(typeof dto.durationFormatted).toBe('string'); + expect(typeof dto.startProgress).toBe('number'); + expect(typeof dto.endProgress).toBe('number'); + expect(typeof dto.progressDelta).toBe('number'); + expect(typeof dto.startLocation).toBe('string'); + expect(typeof dto.endLocation).toBe('string'); + }); +}); + diff --git a/booklore-ui/src/app/shared/service/settings-helper.service.spec.ts b/booklore-ui/src/app/shared/service/settings-helper.service.spec.ts new file mode 100644 index 000000000..58dfd74ff --- /dev/null +++ b/booklore-ui/src/app/shared/service/settings-helper.service.spec.ts @@ -0,0 +1,70 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {of, throwError} from 'rxjs'; +import {SettingsHelperService} from './settings-helper.service'; +import {AppSettingsService} from './app-settings.service'; +import {MessageService} from 'primeng/api'; + +describe('SettingsHelperService', () => { + let service: SettingsHelperService; + let appSettingsServiceMock: any; + let messageServiceMock: any; + + beforeEach(() => { + appSettingsServiceMock = { + saveSettings: vi.fn() + }; + messageServiceMock = { + add: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + SettingsHelperService, + {provide: AppSettingsService, useValue: appSettingsServiceMock}, + {provide: MessageService, useValue: messageServiceMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(SettingsHelperService)); + }); + + it('should call saveSettings and show success message on success', () => { + appSettingsServiceMock.saveSettings.mockReturnValue(of(void 0)); + service.saveSetting('theme', 'dark').subscribe(result => { + expect(result).toBeUndefined(); + expect(appSettingsServiceMock.saveSettings).toHaveBeenCalledWith([{key: 'theme', newValue: 'dark'}]); + expect(messageServiceMock.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'Settings Saved', + detail: 'The settings were successfully saved!' + }); + }); + }); + + it('should call saveSettings and show error message on error', () => { + appSettingsServiceMock.saveSettings.mockReturnValue(throwError(() => new Error('fail'))); + service.saveSetting('theme', 'light').subscribe({ + error: (err: any) => { + expect(appSettingsServiceMock.saveSettings).toHaveBeenCalledWith([{key: 'theme', newValue: 'light'}]); + expect(messageServiceMock.add).toHaveBeenCalledWith({ + severity: 'error', + summary: 'Error', + detail: 'There was an error saving the settings.' + }); + expect(err).toBeInstanceOf(Error); + } + }); + }); + + it('should show custom message via showMessage', () => { + service.showMessage('success', 'Yay', 'It worked!'); + expect(messageServiceMock.add).toHaveBeenCalledWith({ + severity: 'success', + summary: 'Yay', + detail: 'It worked!' + }); + }); +}); diff --git a/booklore-ui/src/app/shared/service/settings-helper.service.ts b/booklore-ui/src/app/shared/service/settings-helper.service.ts index df88aa858..6ba17f08d 100644 --- a/booklore-ui/src/app/shared/service/settings-helper.service.ts +++ b/booklore-ui/src/app/shared/service/settings-helper.service.ts @@ -25,18 +25,6 @@ export class SettingsHelperService { return observable; } - saveMultipleSettings(settings: { key: string, newValue: unknown }[]): Observable { - const observable = this.appSettingsService.saveSettings(settings); - observable.subscribe({ - next: () => this.showSuccessMessage(), - error: (error) => { - console.error('Failed to save settings:', error); - this.showErrorMessage(); - } - }); - return observable; - } - private showSuccessMessage(): void { this.messageService.add({ severity: 'success', diff --git a/booklore-ui/src/app/shared/service/toast.service.ts b/booklore-ui/src/app/shared/service/toast.service.ts deleted file mode 100644 index 56f3af471..000000000 --- a/booklore-ui/src/app/shared/service/toast.service.ts +++ /dev/null @@ -1,26 +0,0 @@ -import {inject, Injectable} from '@angular/core'; -import {MessageService} from 'primeng/api'; - -@Injectable({ - providedIn: 'root' -}) -export class ToastService { - - private messageService = inject(MessageService); - - showSuccess(summary: string, detail: string) { - this.messageService.add({ severity: 'success', summary, detail }); - } - - showError(summary: string, detail: string) { - this.messageService.add({ severity: 'error', summary, detail }); - } - - showInfo(summary: string, detail: string) { - this.messageService.add({ severity: 'info', summary, detail }); - } - - showWarning(summary: string, detail: string) { - this.messageService.add({ severity: 'warn', summary, detail }); - } -} diff --git a/booklore-ui/src/app/shared/service/url-helper.service.spec.ts b/booklore-ui/src/app/shared/service/url-helper.service.spec.ts new file mode 100644 index 000000000..77c629831 --- /dev/null +++ b/booklore-ui/src/app/shared/service/url-helper.service.spec.ts @@ -0,0 +1,362 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {TestBed} from '@angular/core/testing'; +import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; +import {UrlHelperService} from './url-helper.service'; +import {AuthService} from './auth.service'; +import {BookService} from '../../features/book/service/book.service'; +import {Router, UrlTree} from '@angular/router'; +import {Book} from '../../features/book/model/book.model'; +import {CoverGeneratorComponent} from '../components/cover-generator/cover-generator.component'; + +describe('UrlHelperService', () => { + let service: UrlHelperService; + let authServiceMock: any; + let bookServiceMock: any; + let routerMock: any; + + beforeEach(() => { + authServiceMock = { + getOidcAccessToken: vi.fn(), + getInternalAccessToken: vi.fn() + }; + bookServiceMock = { + getBookByIdFromState: vi.fn() + }; + routerMock = { + createUrlTree: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + UrlHelperService, + {provide: AuthService, useValue: authServiceMock}, + {provide: BookService, useValue: bookServiceMock}, + {provide: Router, useValue: routerMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(UrlHelperService)); + }); + + describe('Token handling', () => { + it('should append token from OIDC', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('oidc-token'); + authServiceMock.getInternalAccessToken.mockReturnValue(null); + const url = (service as any).appendToken('http://test'); + expect(url).toContain('token=oidc-token'); + }); + + it('should append token from internal', () => { + authServiceMock.getOidcAccessToken.mockReturnValue(null); + authServiceMock.getInternalAccessToken.mockReturnValue('internal-token'); + const url = (service as any).appendToken('http://test'); + expect(url).toContain('token=internal-token'); + }); + + it('should not append token if none present', () => { + authServiceMock.getOidcAccessToken.mockReturnValue(null); + authServiceMock.getInternalAccessToken.mockReturnValue(null); + const url = (service as any).appendToken('http://test'); + expect(url).toBe('http://test'); + }); + + it('should append token with correct separator', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + expect((service as any).appendToken('http://a')).toBe('http://a?token=tok'); + expect((service as any).appendToken('http://a?x=1')).toBe('http://a?x=1&token=tok'); + }); + + it('should handle empty string token gracefully', () => { + authServiceMock.getOidcAccessToken.mockReturnValue(''); + authServiceMock.getInternalAccessToken.mockReturnValue(''); + const url = (service as any).appendToken('http://test'); + expect(url).toBe('http://test'); + }); + + it('should handle undefined url in appendToken', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + expect(() => (service as any).appendToken(undefined)).toThrow(); + }); + }); + + describe('getThumbnailUrl', () => { + it('should use CoverGenerator if no coverUpdatedOn and book/metadata present', () => { + const book: Book = {id: 1, metadata: {title: 'T', authors: ['A']}} as any; + bookServiceMock.getBookByIdFromState.mockReturnValue(book); + const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url'); + const url = service.getThumbnailUrl(1); + expect(genSpy).toHaveBeenCalled(); + expect(url).toBe('cover-url'); + genSpy.mockRestore(); + }); + + it('should use API url if coverUpdatedOn present', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + const url = service.getThumbnailUrl(2, 'v123'); + expect(url).toMatch(/\/api\/v1\/media\/book\/2\/thumbnail\?v123.*token=tok/); + }); + + it('should use API url if no book in state', () => { + bookServiceMock.getBookByIdFromState.mockReturnValue(undefined); + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + const url = service.getThumbnailUrl(3); + expect(url).toMatch(/\/api\/v1\/media\/book\/3\/thumbnail\?token=tok/); + }); + + it('should handle book with no metadata', () => { + const book: Book = {id: 1} as any; + bookServiceMock.getBookByIdFromState.mockReturnValue(book); + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + const url = service.getThumbnailUrl(1); + expect(url).toMatch(/\/api\/v1\/media\/book\/1\/thumbnail\?token=tok/); + }); + + it('should handle book with empty metadata', () => { + const book: Book = {id: 1, metadata: {}} as any; + bookServiceMock.getBookByIdFromState.mockReturnValue(book); + const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url'); + const url = service.getThumbnailUrl(1); + expect(genSpy).toHaveBeenCalled(); + expect(url).toBe('cover-url'); + genSpy.mockRestore(); + }); + + it('should handle coverUpdatedOn with empty string', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + const url = service.getThumbnailUrl(2, ''); + expect(url).toMatch(/\/api\/v1\/media\/book\/2\/thumbnail\?token=tok/); + }); + }); + + describe('getThumbnailUrl1', () => { + it('should always use API url and append token', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + const url = service.getThumbnailUrl1(4, 'v456'); + expect(url).toMatch(/\/api\/v1\/media\/book\/4\/thumbnail\?v456.*token=tok/); + }); + + it('should handle undefined coverUpdatedOn', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + const url = service.getThumbnailUrl1(4); + expect(url).toMatch(/\/api\/v1\/media\/book\/4\/thumbnail\?token=tok/); + }); + }); + + describe('getCoverUrl', () => { + it('should use CoverGenerator if no coverUpdatedOn and book/metadata present', () => { + const book: Book = {id: 5, metadata: {title: 'T', authors: ['A']}} as any; + bookServiceMock.getBookByIdFromState.mockReturnValue(book); + const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url2'); + const url = service.getCoverUrl(5); + expect(genSpy).toHaveBeenCalled(); + expect(url).toBe('cover-url2'); + genSpy.mockRestore(); + }); + + it('should use API url if coverUpdatedOn present', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + const url = service.getCoverUrl(6, 'v789'); + expect(url).toMatch(/\/api\/v1\/media\/book\/6\/cover\?v789.*token=tok/); + }); + + it('should use API url if no book in state', () => { + bookServiceMock.getBookByIdFromState.mockReturnValue(undefined); + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + const url = service.getCoverUrl(7); + expect(url).toMatch(/\/api\/v1\/media\/book\/7\/cover\?token=tok/); + }); + + it('should handle book with no metadata', () => { + const book: Book = {id: 5} as any; + bookServiceMock.getBookByIdFromState.mockReturnValue(book); + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + const url = service.getCoverUrl(5); + expect(url).toMatch(/\/api\/v1\/media\/book\/5\/cover\?token=tok/); + }); + + it('should handle book with empty metadata', () => { + const book: Book = {id: 5, metadata: {}} as any; + bookServiceMock.getBookByIdFromState.mockReturnValue(book); + const genSpy = vi.spyOn(CoverGeneratorComponent.prototype, 'generateCover').mockReturnValue('cover-url2'); + const url = service.getCoverUrl(5); + expect(genSpy).toHaveBeenCalled(); + expect(url).toBe('cover-url2'); + genSpy.mockRestore(); + }); + + it('should handle coverUpdatedOn with empty string', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + const url = service.getCoverUrl(6, ''); + expect(url).toMatch(/\/api\/v1\/media\/book\/6\/cover\?token=tok/); + }); + }); + + describe('getBackupCoverUrl', () => { + it('should return backup cover url with token', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + const url = service.getBackupCoverUrl(8); + expect(url).toMatch(/\/api\/v1\/media\/book\/8\/backup-cover\?token=tok/); + }); + + it('should handle missing token', () => { + authServiceMock.getOidcAccessToken.mockReturnValue(null); + authServiceMock.getInternalAccessToken.mockReturnValue(null); + const url = service.getBackupCoverUrl(8); + expect(url).toMatch(/\/api\/v1\/media\/book\/8\/backup-cover$/); + }); + }); + + describe('getBookdropCoverUrl', () => { + it('should return bookdrop cover url with token', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + const url = service.getBookdropCoverUrl(9); + expect(url).toMatch(/\/api\/v1\/media\/bookdrop\/9\/cover\?token=tok/); + }); + + it('should handle missing token', () => { + authServiceMock.getOidcAccessToken.mockReturnValue(null); + authServiceMock.getInternalAccessToken.mockReturnValue(null); + const url = service.getBookdropCoverUrl(9); + expect(url).toMatch(/\/api\/v1\/media\/bookdrop\/9\/cover$/); + }); + }); + + describe('getBookUrl', () => { + it('should call router.createUrlTree with correct args', () => { + const book: Book = {id: 10} as any; + routerMock.createUrlTree.mockReturnValue('url-tree'); + const urlTree = service.getBookUrl(book); + expect(routerMock.createUrlTree).toHaveBeenCalledWith(['/book', 10], {queryParams: {tab: 'view'}}); + expect(urlTree).toBe('url-tree'); + }); + + it('should handle book with undefined id', () => { + routerMock.createUrlTree.mockReturnValue('url-tree'); + const minimalBook = { + id: undefined, + bookType: undefined, + libraryId: undefined, + libraryName: undefined + } as any; + const urlTree = service.getBookUrl(minimalBook); + expect(routerMock.createUrlTree).toHaveBeenCalledWith(['/book', undefined], {queryParams: {tab: 'view'}}); + expect(urlTree).toBe('url-tree'); + }); + }); + + describe('filterBooksBy', () => { + it('should route to /series if filterKey is series', () => { + routerMock.createUrlTree.mockReturnValue('series-url'); + const urlTree = service.filterBooksBy('series', 'My Series'); + expect(routerMock.createUrlTree).toHaveBeenCalledWith(['/series', encodeURIComponent('My Series')]); + expect(urlTree).toBe('series-url'); + }); + + it('should route to /all-books with correct queryParams for other filters', () => { + routerMock.createUrlTree.mockReturnValue('all-books-url'); + const urlTree = service.filterBooksBy('author', 'Author Name'); + expect(routerMock.createUrlTree).toHaveBeenCalledWith( + ['/all-books'], + { + queryParams: { + view: 'grid', + sort: 'title', + direction: 'asc', + sidebar: true, + filter: 'author:' + encodeURIComponent('Author Name') + } + } + ); + expect(urlTree).toBe('all-books-url'); + }); + + it('should handle empty filterValue', () => { + routerMock.createUrlTree.mockReturnValue('empty-filter-url'); + const urlTree = service.filterBooksBy('author', ''); + expect(routerMock.createUrlTree).toHaveBeenCalledWith( + ['/all-books'], + expect.objectContaining({ + queryParams: expect.objectContaining({ + filter: 'author:' + }) + }) + ); + expect(urlTree).toBe('empty-filter-url'); + }); + + it('should handle empty filterKey', () => { + routerMock.createUrlTree.mockReturnValue('empty-key-url'); + const urlTree = service.filterBooksBy('', 'SomeValue'); + expect(routerMock.createUrlTree).toHaveBeenCalledWith( + ['/all-books'], + expect.objectContaining({ + queryParams: expect.objectContaining({ + filter: ':' + encodeURIComponent('SomeValue') + }) + }) + ); + expect(urlTree).toBe('empty-key-url'); + }); + }); +}); + +describe('UrlHelperService - API Contract Tests', () => { + let service: UrlHelperService; + let authServiceMock: any; + let bookServiceMock: any; + let routerMock: any; + + beforeEach(() => { + authServiceMock = { + getOidcAccessToken: vi.fn(), + getInternalAccessToken: vi.fn() + }; + bookServiceMock = { + getBookByIdFromState: vi.fn() + }; + routerMock = { + createUrlTree: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + UrlHelperService, + {provide: AuthService, useValue: authServiceMock}, + {provide: BookService, useValue: bookServiceMock}, + {provide: Router, useValue: routerMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(UrlHelperService)); + }); + + it('should generate correct API endpoints for covers and thumbnails', () => { + authServiceMock.getOidcAccessToken.mockReturnValue('tok'); + expect(service.getThumbnailUrl1(11)).toMatch(/\/api\/v1\/media\/book\/11\/thumbnail\?token=tok/); + expect(service.getCoverUrl(12, 'v1')).toMatch(/\/api\/v1\/media\/book\/12\/cover\?v1.*token=tok/); + expect(service.getBackupCoverUrl(13)).toMatch(/\/api\/v1\/media\/book\/13\/backup-cover\?token=tok/); + expect(service.getBookdropCoverUrl(14)).toMatch(/\/api\/v1\/media\/bookdrop\/14\/cover\?token=tok/); + }); + + it('should encode filter values in filterBooksBy', () => { + routerMock.createUrlTree.mockReturnValue('tree'); + service.filterBooksBy('author', 'A&B'); + expect(routerMock.createUrlTree).toHaveBeenCalledWith( + ['/all-books'], + expect.objectContaining({ + queryParams: expect.objectContaining({ + filter: 'author:' + encodeURIComponent('A&B') + }) + }) + ); + }); + + it('should always return a string or UrlTree from getBookUrl/filterBooksBy', () => { + routerMock.createUrlTree.mockReturnValueOnce('tree1').mockReturnValueOnce({} as UrlTree); + expect(typeof service.getBookUrl({id: 1} as any)).toMatch(/string|object/); + expect(typeof service.filterBooksBy('series', 'X')).toMatch(/string|object/); + }); +}); + diff --git a/booklore-ui/src/app/shared/service/version.service.spec.ts b/booklore-ui/src/app/shared/service/version.service.spec.ts new file mode 100644 index 000000000..1727e63b4 --- /dev/null +++ b/booklore-ui/src/app/shared/service/version.service.spec.ts @@ -0,0 +1,138 @@ +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 {AppVersion, ReleaseNote, VersionService} from './version.service'; + +describe('VersionService', () => { + let service: VersionService; + let httpClientMock: any; + + const mockVersion: AppVersion = { + current: '1.0.0', + latest: '1.2.0' + }; + + const mockChangelog: ReleaseNote[] = [ + { + version: '1.2.0', + name: 'Release 1.2.0', + changelog: 'Bug fixes and improvements', + url: 'https://example.com/release/1.2.0', + publishedAt: '2024-01-01T00:00:00Z' + } + ]; + + beforeEach(() => { + httpClientMock = { + get: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + VersionService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(VersionService)); + }); + + it('should get version', () => { + httpClientMock.get.mockReturnValue(of(mockVersion)); + service.getVersion().subscribe(version => { + expect(version).toEqual(mockVersion); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version$/)); + }); + }); + + it('should get changelog', () => { + httpClientMock.get.mockReturnValue(of(mockChangelog)); + service.getChangelog().subscribe(changelog => { + expect(changelog).toEqual(mockChangelog); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version\/changelog$/)); + }); + }); + + it('should handle getVersion error', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service.getVersion().subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); + + it('should handle getChangelog error', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service.getChangelog().subscribe({ + error: (err: any) => { + expect(err).toBeInstanceOf(Error); + expect(err.message).toBe('fail'); + } + }); + }); +}); + +describe('VersionService - API Contract Tests', () => { + let service: VersionService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + VersionService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(VersionService)); + }); + + it('should expect AppVersion from getVersion', () => { + const response: AppVersion = {current: '1.0.0', latest: '1.2.0'}; + httpClientMock.get.mockReturnValue(of(response)); + service.getVersion().subscribe(version => { + expect(typeof version.current).toBe('string'); + expect(typeof version.latest).toBe('string'); + }); + }); + + it('should expect ReleaseNote[] from getChangelog', () => { + const response: ReleaseNote[] = [ + { + version: '1.2.0', + name: 'Release 1.2.0', + changelog: 'Bug fixes and improvements', + url: 'https://example.com/release/1.2.0', + publishedAt: '2024-01-01T00:00:00Z' + } + ]; + httpClientMock.get.mockReturnValue(of(response)); + service.getChangelog().subscribe(notes => { + expect(Array.isArray(notes)).toBe(true); + expect(notes[0]).toHaveProperty('version'); + expect(notes[0]).toHaveProperty('name'); + expect(notes[0]).toHaveProperty('changelog'); + expect(notes[0]).toHaveProperty('url'); + expect(notes[0]).toHaveProperty('publishedAt'); + }); + }); + + it('should call correct endpoints', () => { + httpClientMock.get.mockReturnValue(of({})); + service.getVersion().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version$/)); + service.getChangelog().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/version\/changelog$/)); + }); +}); + From fa3005369fd4c1b786daa07d29a55c9a419c3a13 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Wed, 7 Jan 2026 11:26:41 -0700 Subject: [PATCH 17/40] Revamp metadata search UI to display live results (#2195) Co-authored-by: acx10 --- booklore-api/build.gradle | 3 + .../config/security/SecurityConfig.java | 9 +- .../controller/MetadataController.java | 13 +- .../service/metadata/BookMetadataService.java | 38 +- booklore-ui/package-lock.json | 177 +++-- booklore-ui/package.json | 1 + .../book/service/book-metadata.service.ts | 55 ++ .../book/service/book.service.spec.ts | 13 - .../app/features/book/service/book.service.ts | 4 - .../metadata-searcher.component.html | 269 ++++--- .../metadata-searcher.component.scss | 739 +++++++++++++++++- .../metadata-searcher.component.ts | 208 ++++- 12 files changed, 1288 insertions(+), 241 deletions(-) create mode 100644 booklore-ui/src/app/features/book/service/book-metadata.service.ts diff --git a/booklore-api/build.gradle b/booklore-api/build.gradle index a54edd655..69fa19505 100644 --- a/booklore-api/build.gradle +++ b/booklore-api/build.gradle @@ -37,6 +37,9 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-mail' implementation 'org.springframework.boot:spring-boot-starter-oauth2-client' + // --- Reactive Streams --- + implementation 'io.projectreactor:reactor-core' + // --- Database & Migration --- implementation 'org.mariadb.jdbc:mariadb-java-client:3.5.6' implementation 'org.flywaydb:flyway-mysql:11.19.0' 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 6789c5db5..716eaac9b 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 @@ -1,12 +1,9 @@ package com.adityachandel.booklore.config.security; import com.adityachandel.booklore.config.AppProperties; -import com.adityachandel.booklore.config.security.filter.CoverJwtFilter; -import com.adityachandel.booklore.config.security.filter.CustomFontJwtFilter; -import com.adityachandel.booklore.config.security.filter.DualJwtAuthenticationFilter; -import com.adityachandel.booklore.config.security.filter.KoboAuthFilter; -import com.adityachandel.booklore.config.security.filter.KoreaderAuthFilter; +import com.adityachandel.booklore.config.security.filter.*; import com.adityachandel.booklore.config.security.service.OpdsUserDetailsService; +import jakarta.servlet.DispatcherType; import jakarta.servlet.http.HttpServletResponse; import lombok.AllArgsConstructor; import org.springframework.context.annotation.Bean; @@ -159,6 +156,7 @@ public class SecurityConfig { .csrf(AbstractHttpConfigurer::disable) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(auth -> auth + .dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll() .requestMatchers(publicEndpoints.toArray(new String[0])).permitAll() .anyRequest().authenticated() ) @@ -168,7 +166,6 @@ public class SecurityConfig { @Bean public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception { - // Configure the shared AuthenticationManagerBuilder with the UserDetailsService and PasswordEncoder AuthenticationManagerBuilder auth = http.getSharedObject(AuthenticationManagerBuilder.class); auth.userDetailsService(opdsUserDetailsService).passwordEncoder(passwordEncoder()); return auth.build(); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/MetadataController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/MetadataController.java index 074a89449..ad3bd6aef 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/MetadataController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/MetadataController.java @@ -17,11 +17,13 @@ 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.AllArgsConstructor; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; +import reactor.core.publisher.Flux; import java.util.List; import java.util.Map; @@ -42,13 +44,13 @@ public class MetadataController { @Operation(summary = "Get prospective metadata for a book", description = "Fetch prospective metadata for a book by its ID. Requires metadata edit permission or admin.") @ApiResponse(responseCode = "200", description = "Prospective metadata returned successfully") - @PostMapping("/{bookId}/metadata/prospective") + @PostMapping(value = "/{bookId}/metadata/prospective", produces = MediaType.TEXT_EVENT_STREAM_VALUE) @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") @CheckBookAccess(bookIdParam = "bookId") - public ResponseEntity> getMetadataList( + public Flux getMetadataList( @Parameter(description = "Fetch metadata request") @RequestBody(required = false) FetchMetadataRequest fetchMetadataRequest, @Parameter(description = "ID of the book") @PathVariable Long bookId) { - return ResponseEntity.ok(bookMetadataService.getProspectiveMetadataListForBookId(bookId, fetchMetadataRequest)); + return bookMetadataService.getProspectiveMetadataListForBookId(bookId, fetchMetadataRequest); } @Operation(summary = "Update book metadata", description = "Update metadata for a book. Requires metadata edit permission or admin.") @@ -180,7 +182,7 @@ public class MetadataController { @PreAuthorize("@securityUtil.canBulkEditMetadata() or @securityUtil.isAdmin()") public ResponseEntity bulkUploadCover( @Parameter(description = "Cover image file") @RequestParam("file") MultipartFile file, - @Parameter(description = "Comma-separated book IDs") @RequestParam("bookIds") @jakarta.validation.constraints.NotEmpty java.util.Set bookIds) { + @Parameter(description = "Comma-separated book IDs") @RequestParam("bookIds") @RequestBody java.util.Set bookIds) { bookMetadataService.updateCoverImageFromFileForBooks(bookIds, file); return ResponseEntity.noContent().build(); } @@ -221,4 +223,5 @@ public class MetadataController { metadataManagementService.deleteMetadata(request.getMetadataType(), request.getValuesToDelete()); return ResponseEntity.noContent().build(); } -} \ No newline at end of file +} + 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 0b85d4b1f..3e24cafe2 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 @@ -30,6 +30,9 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; import java.io.File; import java.lang.reflect.Method; @@ -58,33 +61,20 @@ public class BookMetadataService { bookCoverService.generateCustomCover(bookId); } - public List getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) { + public Flux getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) { BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); Book book = bookMapper.toBook(bookEntity); - List> allMetadata = request.getProviders().stream() - .map(provider -> CompletableFuture.supplyAsync(() -> fetchMetadataListFromAProvider(provider, book, request)) - .exceptionally(e -> { - log.error("Error fetching metadata from provider: {}", provider, e); - return List.of(); - })) - .toList() - .stream() - .map(CompletableFuture::join) - .filter(Objects::nonNull) - .toList(); - List interleavedMetadata = new ArrayList<>(); - int maxSize = allMetadata.stream().mapToInt(List::size).max().orElse(0); - - for (int i = 0; i < maxSize; i++) { - for (List metadataList : allMetadata) { - if (i < metadataList.size()) { - interleavedMetadata.add(metadataList.get(i)); - } - } - } - - return interleavedMetadata; + return Flux.fromIterable(request.getProviders()) + .flatMap(provider -> + Mono.fromCallable(() -> fetchMetadataListFromAProvider(provider, book, request)) + .subscribeOn(Schedulers.boundedElastic()) + .flatMapMany(Flux::fromIterable) + .onErrorResume(e -> { + log.error("Error fetching metadata from provider: {}", provider, e); + return Flux.empty(); + }) + ); } public List fetchMetadataListFromAProvider(MetadataProvider provider, Book book, FetchMetadataRequest request) { diff --git a/booklore-ui/package-lock.json b/booklore-ui/package-lock.json index 794484b3e..e9d8a6b84 100644 --- a/booklore-ui/package-lock.json +++ b/booklore-ui/package-lock.json @@ -33,6 +33,7 @@ "ng2-charts": "^8.0.0", "ngx-extended-pdf-viewer": "^25.6.4", "ngx-infinite-scroll": "^21.0.0", + "ngx-sse-client": "^20.0.1", "primeicons": "^7.0.0", "primeng": "^21.0.2", "quill": "^2.0.3", @@ -453,7 +454,6 @@ "integrity": "sha512-PYVgNbjNtuD5/QOuS6cHR8A7bRqsVqxtUUXGqdv76FYMAajQcAvyfR0QxOkqf3NmYxgNgO3hlUHWq0ILjVbcow==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@angular-eslint/bundled-angular-compiler": "21.1.0", "eslint-scope": "^9.0.0" @@ -483,7 +483,6 @@ "resolved": "https://registry.npmjs.org/@angular/animations/-/animations-21.0.5.tgz", "integrity": "sha512-7Lr60wLlYcGG+VDnnOY9xpn8Zz3yyJcWGSjNEbXPEGaaD0nTZLNZ1nIXRhTeYZwosK5GvPDFxq68kdLxczskHA==", "license": "MIT", - "peer": true, "dependencies": { "tslib": "^2.3.0" }, @@ -599,7 +598,6 @@ "resolved": "https://registry.npmjs.org/@angular/cdk/-/cdk-21.0.3.tgz", "integrity": "sha512-abfckeZfFvovdpxuQHRE4gS1VLNa05Dx0ZSKLGVL9DsQsi4pgn6wWg1y9TkXMlmtpG/EhLmCBxUc6LOHfdeWQA==", "license": "MIT", - "peer": true, "dependencies": { "parse5": "^8.0.0", "tslib": "^2.3.0" @@ -616,7 +614,6 @@ "integrity": "sha512-3lMR3J231JhLgAt37yEULSHFte3zPeta9VYpIIf92JiBsTnWrvKnaK8RXhfdiSQrvhqQ9FMQdl5AG62r1c4dbA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@angular-devkit/architect": "0.2100.3", "@angular-devkit/core": "21.0.3", @@ -652,7 +649,6 @@ "resolved": "https://registry.npmjs.org/@angular/common/-/common-21.0.5.tgz", "integrity": "sha512-/ZI11F6Wxr8TZRVO4O7pmhBJ9YxDg9mvA76e0PiivmqZggM02HY0y3XPMP3hAOe4K+PfaVBgMAu3P9t32klzfA==", "license": "MIT", - "peer": true, "dependencies": { "tslib": "^2.3.0" }, @@ -669,7 +665,6 @@ "resolved": "https://registry.npmjs.org/@angular/compiler/-/compiler-21.0.5.tgz", "integrity": "sha512-92sv9pVm9o/8KfPM7T8j5VQmTaSOqmIajrJF8evXE2dNJcwkBpVtzZUqDzr23AV3vg94C7eYU64i8qrsmJ+cYQ==", "license": "MIT", - "peer": true, "dependencies": { "tslib": "^2.3.0" }, @@ -683,7 +678,6 @@ "integrity": "sha512-45sFKqt+badXl6Ab2XsxuOsdi0BbIZgcc9TdwmFPdXMNfcSUYDcPiOA0l1iPwDIZiu4VyqzepMfnHB9IwCatgA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/core": "7.28.4", "@jridgewell/sourcemap-codec": "^1.4.14", @@ -716,7 +710,6 @@ "resolved": "https://registry.npmjs.org/@angular/core/-/core-21.0.5.tgz", "integrity": "sha512-HFXfO5YsBVM+IEaU8h3DZSxO98yDZM2v49NlSVNDzFD3fhnkpTmcgT2NKz9ulIiuV9N376itt+x+NG12sg/+Fw==", "license": "MIT", - "peer": true, "dependencies": { "tslib": "^2.3.0" }, @@ -742,7 +735,6 @@ "resolved": "https://registry.npmjs.org/@angular/forms/-/forms-21.0.5.tgz", "integrity": "sha512-RcmXs/LgKyc7D70xVT+3aK/H2SCFEyuebAiw72Iz1te1Gbql2GDFF6hgEOaNwOUglDg8ogN5MdVif2DbRLD3Hw==", "license": "MIT", - "peer": true, "dependencies": { "tslib": "^2.3.0" }, @@ -762,7 +754,6 @@ "resolved": "https://registry.npmjs.org/@angular/platform-browser/-/platform-browser-21.0.5.tgz", "integrity": "sha512-UVCrqOxFmX6kAG3Y6jqjCWvLoTP7fxeY96AsxTMp1fkBdqbQbEPleWQpwngNimsuUPvf+rA6XOxsqiDmRex5mA==", "license": "MIT", - "peer": true, "dependencies": { "tslib": "^2.3.0" }, @@ -803,7 +794,6 @@ "resolved": "https://registry.npmjs.org/@angular/router/-/router-21.0.5.tgz", "integrity": "sha512-IFmf0Wd7jSOoZ8TI+4RXMsYmnIfHQG+kGxeMQVKrefTdr3uEHW/TEsNzbW5bkCpVJHRm4EhkH4hSu8D8tUQffQ==", "license": "MIT", - "peer": true, "dependencies": { "tslib": "^2.3.0" }, @@ -903,7 +893,6 @@ "integrity": "sha512-2BCOP7TN8M+gVDj7/ht3hsaO/B/n5oDbiAyyvnRlNOs+u1o+JWNYTQrmpuNp1/Wq2gcFrI01JAW+paEKDMx/CA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.27.1", "@babel/generator": "^7.28.3", @@ -1200,6 +1189,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=0.1.90" } @@ -1292,7 +1282,6 @@ } ], "license": "MIT", - "peer": true, "engines": { "node": ">=18" }, @@ -1336,7 +1325,6 @@ } ], "license": "MIT", - "peer": true, "engines": { "node": ">=18" } @@ -2348,7 +2336,6 @@ "integrity": "sha512-X7/+dG9SLpSzRkwgG5/xiIzW0oMrV3C0HOa7YHG1WnrLK+vCQHfte4k/T80059YBdei29RBC3s+pSMvPJDU9/A==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@inquirer/checkbox": "^4.3.0", "@inquirer/confirm": "^5.1.19", @@ -4563,14 +4550,14 @@ "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==", "dev": true, "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/@standard-schema/spec": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@stomp/rx-stomp": { "version": "2.3.0", @@ -4587,8 +4574,7 @@ "version": "7.2.1", "resolved": "https://registry.npmjs.org/@stomp/stompjs/-/stompjs-7.2.1.tgz", "integrity": "sha512-DLd/WeicnHS5SsWWSk3x6/pcivqchNaEvg9UEGVqAcfYEBVmS9D6980ckXjTtfpXLjdLDsd96M7IuX4w7nzq5g==", - "license": "Apache-2.0", - "peer": true + "license": "Apache-2.0" }, "node_modules/@tailwindcss/typography": { "version": "0.5.19", @@ -4631,8 +4617,7 @@ "version": "25.0.0", "resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-25.0.0.tgz", "integrity": "sha512-XKLA6syeBUaPzx4j3qwMqzzq+V4uo72BnlbOjmuljLrRqdsd3qnzvZZoxvMHZ23ndsRS4aufU6JOZYpCbU6T1A==", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@tybys/wasm-util": { "version": "0.10.1", @@ -4663,6 +4648,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "@types/node": "*" } @@ -4757,7 +4743,6 @@ "integrity": "sha512-6/cmF2piao+f6wSxUsJLZjck7OQsYyRtcOZS02k7XINSNlz93v6emM8WutDQSXnroG2xwYlEVHJI+cPA7CPM3Q==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.50.0", "@typescript-eslint/types": "8.50.0", @@ -4865,7 +4850,6 @@ "integrity": "sha512-iX1mgmGrXdANhhITbpp2QQM2fGehBse9LbTf0sidWK6yg/NE+uhV5dfU1g6EYPlcReYmkE9QLPq/2irKAmtS9w==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": "^18.18.0 || ^20.9.0 || >=21.1.0" }, @@ -4908,7 +4892,6 @@ "integrity": "sha512-87KgUXET09CRjGCi2Ejxy3PULXna63/bMYv72tCAlDJC3Yqwln0HiFJ3VJMst2+mEtNtZu5oFvX4qJGjKsnAgg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.7.0", "@typescript-eslint/scope-manager": "8.50.0", @@ -5181,7 +5164,6 @@ "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", "dev": true, "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -5496,6 +5478,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": "^4.5.0 || >= 5.9" } @@ -5626,7 +5609,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "baseline-browser-mapping": "^2.9.0", "caniuse-lite": "^1.0.30001759", @@ -5848,7 +5830,6 @@ "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz", "integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==", "license": "MIT", - "peer": true, "dependencies": { "@kurkle/color": "^0.3.0" }, @@ -6069,6 +6050,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "debug": "2.6.9", "finalhandler": "1.1.2", @@ -6086,6 +6068,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "ms": "2.0.0" } @@ -6097,6 +6080,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">= 0.8" } @@ -6108,6 +6092,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "debug": "2.6.9", "encodeurl": "~1.0.2", @@ -6127,7 +6112,8 @@ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true, "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/connect/node_modules/on-finished": { "version": "2.3.0", @@ -6136,6 +6122,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "ee-first": "1.1.1" }, @@ -6150,6 +6137,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -6339,7 +6327,8 @@ "integrity": "sha512-GAj5FOq0Hd+RsCGVJxZuKaIDXDf3h6GQoNEjFgbLLI/trgtavwUbSnZ5pVfg27DVCaWjIohryS0JFwIJyT2cMg==", "dev": true, "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/d": { "version": "1.0.2", @@ -6385,6 +6374,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=4.0" } @@ -6438,6 +6428,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">= 0.8", "npm": "1.2.8000 || >= 1.4.16" @@ -6460,7 +6451,8 @@ "integrity": "sha512-uJaamHkagcZtHPqCIHZxnFrXlunQXgBOsZSUOWwFw31QJCAbyTBoHMW75YOTur5ZNx8pIeAKgf6GWIgaqqiLhA==", "dev": true, "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/didyoumean": { "version": "1.2.2", @@ -6481,6 +6473,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "custom-event": "~1.0.0", "ent": "~2.2.0", @@ -6625,6 +6618,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "@types/cors": "^2.8.12", "@types/node": ">=10.0.0", @@ -6647,6 +6641,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=10.0.0" } @@ -6658,6 +6653,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" @@ -6673,6 +6669,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -6692,6 +6689,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -6703,6 +6701,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "mime-db": "1.52.0" }, @@ -6717,6 +6716,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -6728,6 +6728,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=10.0.0" }, @@ -6751,6 +6752,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "call-bound": "^1.0.3", "es-errors": "^1.3.0", @@ -6979,7 +6981,6 @@ "integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.1", @@ -7280,7 +7281,8 @@ "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", "dev": true, "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/eventsource": { "version": "3.0.7", @@ -7328,7 +7330,6 @@ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", @@ -7398,7 +7399,8 @@ "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", "dev": true, "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/fast-deep-equal": { "version": "3.1.3", @@ -7596,6 +7598,7 @@ ], "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=4.0" }, @@ -7646,6 +7649,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", @@ -7674,7 +7678,8 @@ "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", "dev": true, "license": "ISC", - "optional": true + "optional": true, + "peer": true }, "node_modules/fsevents": { "version": "2.3.3", @@ -7779,6 +7784,7 @@ "dev": true, "license": "ISC", "optional": true, + "peer": true, "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", @@ -7820,6 +7826,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -7832,6 +7839,7 @@ "dev": true, "license": "ISC", "optional": true, + "peer": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -7902,6 +7910,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "has-symbols": "^1.0.3" }, @@ -8035,6 +8044,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "eventemitter3": "^4.0.0", "follow-redirects": "^1.0.0", @@ -8176,6 +8186,7 @@ "dev": true, "license": "ISC", "optional": true, + "peer": true, "dependencies": { "once": "^1.3.0", "wrappy": "1" @@ -8324,6 +8335,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "call-bound": "^1.0.2", "gopd": "^1.2.0", @@ -8363,6 +8375,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">= 8.0.0" }, @@ -8491,7 +8504,6 @@ "integrity": "sha512-mjzqwWRD9Y1J1KUi7W97Gja1bwOOM5Ug0EZ6UDK3xS7j7mndrkwozHtSblfomlzyB4NepioNt+B2sOSzczVgtQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@acemir/cssom": "^0.9.28", "@asamuzakjp/dom-selector": "^6.7.6", @@ -8597,6 +8609,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "optionalDependencies": { "graceful-fs": "^4.1.6" } @@ -8639,6 +8652,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "@colors/colors": "1.5.0", "body-parser": "^1.19.0", @@ -8679,6 +8693,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=8" } @@ -8690,6 +8705,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "bytes": "~3.1.2", "content-type": "~1.0.5", @@ -8716,6 +8732,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -8728,6 +8745,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "anymatch": "~3.1.2", "braces": "~3.0.2", @@ -8754,6 +8772,7 @@ "dev": true, "license": "ISC", "optional": true, + "peer": true, "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", @@ -8767,6 +8786,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "ms": "2.0.0" } @@ -8777,7 +8797,8 @@ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", "dev": true, "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/karma/node_modules/glob-parent": { "version": "5.1.2", @@ -8786,6 +8807,7 @@ "dev": true, "license": "ISC", "optional": true, + "peer": true, "dependencies": { "is-glob": "^4.0.1" }, @@ -8800,6 +8822,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "safer-buffer": ">= 2.1.2 < 3" }, @@ -8814,6 +8837,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=8" } @@ -8825,6 +8849,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -8836,6 +8861,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -8847,6 +8873,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "mime-db": "1.52.0" }, @@ -8861,6 +8888,7 @@ "dev": true, "license": "ISC", "optional": true, + "peer": true, "dependencies": { "brace-expansion": "^1.1.7" }, @@ -8874,7 +8902,8 @@ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "dev": true, "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/karma/node_modules/picomatch": { "version": "2.3.1", @@ -8883,6 +8912,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=8.6" }, @@ -8897,6 +8927,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", @@ -8914,6 +8945,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "picomatch": "^2.2.1" }, @@ -8928,6 +8960,7 @@ "dev": true, "license": "BSD-3-Clause", "optional": true, + "peer": true, "engines": { "node": ">=0.10.0" } @@ -8939,6 +8972,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", @@ -8955,6 +8989,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "ansi-regex": "^5.0.1" }, @@ -8969,6 +9004,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "media-typer": "0.3.0", "mime-types": "~2.1.24" @@ -8984,6 +9020,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", @@ -9003,6 +9040,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "cliui": "^7.0.2", "escalade": "^3.1.1", @@ -9023,6 +9061,7 @@ "dev": true, "license": "ISC", "optional": true, + "peer": true, "engines": { "node": ">=10" } @@ -9084,7 +9123,6 @@ "integrity": "sha512-ME4Fb83LgEgwNw96RKNvKV4VTLuXfoKudAmm2lP8Kk87KaMK0/Xrx/aAkMWmT8mDb+3MlFDspfbCs7adjRxA2g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "cli-truncate": "^5.0.0", "colorette": "^2.0.20", @@ -9304,6 +9342,7 @@ "dev": true, "license": "Apache-2.0", "optional": true, + "peer": true, "dependencies": { "date-format": "^4.0.14", "debug": "^4.3.4", @@ -9496,6 +9535,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "bin": { "mime": "cli.js" }, @@ -9566,6 +9606,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "funding": { "url": "https://github.com/sponsors/ljharb" } @@ -9730,6 +9771,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "minimist": "^1.2.6" }, @@ -9908,6 +9950,19 @@ "@angular/core": ">=21.0.0 <22.0.0" } }, + "node_modules/ngx-sse-client": { + "version": "20.0.1", + "resolved": "https://registry.npmjs.org/ngx-sse-client/-/ngx-sse-client-20.0.1.tgz", + "integrity": "sha512-OSFRirL5beveGj4An3lOzWwg/JZWJG4Q1TdbyW7lqSDacfwINpIjSHdWlpiQwIghKU7BtLAc6TonUGlU4MzGTQ==", + "license": "MIT", + "dependencies": { + "tslib": "^2.8.1" + }, + "peerDependencies": { + "@angular/common": ">=20.0.0", + "@angular/core": ">=20.0.0" + } + }, "node_modules/node-addon-api": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-6.1.0.tgz", @@ -10525,6 +10580,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=0.10.0" } @@ -10674,7 +10730,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", @@ -10921,7 +10976,8 @@ "integrity": "sha512-jmYNElW7yvO7TV33CjSmvSiE2yco3bV2czu/OzDKdMNVZQWfxCblURLhf+47syQRBntjfLdd/H0egrzIG+oaFQ==", "dev": true, "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/qjobs": { "version": "1.2.0", @@ -10930,6 +10986,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=0.9" } @@ -11083,6 +11140,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=0.10.0" } @@ -11103,7 +11161,8 @@ "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", "dev": true, "license": "MIT", - "optional": true + "optional": true, + "peer": true }, "node_modules/resolve": { "version": "1.22.11", @@ -11187,6 +11246,7 @@ "dev": true, "license": "ISC", "optional": true, + "peer": true, "dependencies": { "glob": "^7.1.3" }, @@ -11317,7 +11377,6 @@ "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", "license": "Apache-2.0", - "peer": true, "dependencies": { "tslib": "^2.1.0" } @@ -11335,6 +11394,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", @@ -11662,6 +11722,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "accepts": "~1.3.4", "base64id": "~2.0.0", @@ -11682,6 +11743,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "debug": "~4.3.4", "ws": "~8.17.1" @@ -11694,6 +11756,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -11713,6 +11776,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=10.0.0" }, @@ -11736,6 +11800,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "@socket.io/component-emitter": "~3.1.0", "debug": "~4.3.1" @@ -11751,6 +11816,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -11770,6 +11836,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" @@ -11785,6 +11852,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "ms": "^2.1.3" }, @@ -11804,6 +11872,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -11815,6 +11884,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "mime-db": "1.52.0" }, @@ -11829,6 +11899,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">= 0.6" } @@ -11996,6 +12067,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "dependencies": { "date-format": "^4.0.14", "debug": "^4.3.4", @@ -12129,7 +12201,6 @@ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.18.tgz", "integrity": "sha512-6A2rnmW5xZMdw11LYjhcI5846rt9pbLSabY5XPxo+XWdxwZaFEn47Go4NzFiHu9sNNmr/kXivP1vStfvMaK1GQ==", "license": "MIT", - "peer": true, "dependencies": { "@alloc/quick-lru": "^5.2.0", "arg": "^5.0.2", @@ -12371,6 +12442,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=14.14" } @@ -12456,8 +12528,7 @@ "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "license": "0BSD", - "peer": true + "license": "0BSD" }, "node_modules/tuf-js": { "version": "4.0.0", @@ -12514,7 +12585,6 @@ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -12529,7 +12599,6 @@ "integrity": "sha512-Q1/6yNUmCpH94fbgMUMg2/BSAr/6U7GBk61kZTv1/asghQOWOjTlp9K8mixS5NcJmm2creY+UFfGeW/+OcA64A==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/eslint-plugin": "8.50.0", "@typescript-eslint/parser": "8.50.0", @@ -12569,6 +12638,7 @@ ], "license": "MIT", "optional": true, + "peer": true, "bin": { "ua-parser-js": "script/cli.js" }, @@ -12626,6 +12696,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">= 4.0.0" } @@ -12704,6 +12775,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">= 0.4.0" } @@ -12759,7 +12831,6 @@ "integrity": "sha512-BxAKBWmIbrDgrokdGZH1IgkIk/5mMHDreLDmCJ0qpyJaAteP8NvMhkwr/ZCQNqNH97bw/dANTE9PDzqwJghfMQ==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.5.0", @@ -13319,7 +13390,6 @@ "integrity": "sha512-E4t7DJ9pESL6E3I8nFjPa4xGUd3PmiWDLsDztS2qXSJWfHtbQnwAWylaBvSNY48I3vr8PTqIZlyK8TE3V3CA4Q==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@vitest/expect": "4.0.16", "@vitest/mocker": "4.0.16", @@ -13409,6 +13479,7 @@ "dev": true, "license": "MIT", "optional": true, + "peer": true, "engines": { "node": ">=0.10.0" } @@ -13730,7 +13801,6 @@ "integrity": "sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig==", "dev": true, "license": "MIT", - "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } @@ -13749,8 +13819,7 @@ "version": "0.16.0", "resolved": "https://registry.npmjs.org/zone.js/-/zone.js-0.16.0.tgz", "integrity": "sha512-LqLPpIQANebrlxY6jKcYKdgN5DTXyyHAKnnWWjE5pPfEQ4n7j5zn7mOEEpwNZVKGqx3kKKmvplEmoBrvpgROTA==", - "license": "MIT", - "peer": true + "license": "MIT" } } } diff --git a/booklore-ui/package.json b/booklore-ui/package.json index 69be34c35..fa5c7888b 100644 --- a/booklore-ui/package.json +++ b/booklore-ui/package.json @@ -37,6 +37,7 @@ "ng2-charts": "^8.0.0", "ngx-extended-pdf-viewer": "^25.6.4", "ngx-infinite-scroll": "^21.0.0", + "ngx-sse-client": "^20.0.1", "primeicons": "^7.0.0", "primeng": "^21.0.2", "quill": "^2.0.3", diff --git a/booklore-ui/src/app/features/book/service/book-metadata.service.ts b/booklore-ui/src/app/features/book/service/book-metadata.service.ts new file mode 100644 index 000000000..e24f725d0 --- /dev/null +++ b/booklore-ui/src/app/features/book/service/book-metadata.service.ts @@ -0,0 +1,55 @@ +import {inject, Injectable} from '@angular/core'; +import {Observable} from 'rxjs'; +import {API_CONFIG} from '../../../core/config/api-config'; +import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-request.model'; +import {BookMetadata} from '../model/book.model'; +import {AuthService} from '../../../shared/service/auth.service'; +import {SseClient} from 'ngx-sse-client'; +import {HttpHeaders} from '@angular/common/http'; +import {map} from 'rxjs/operators'; + +@Injectable({providedIn: 'root'}) +export class BookMetadataService { + private readonly url = `${API_CONFIG.BASE_URL}/api/v1/books`; + private authService = inject(AuthService); + private sseClient = inject(SseClient); + + fetchBookMetadata(bookId: number, request: FetchMetadataRequest): Observable { + const token = + this.authService.getOidcAccessToken() || + this.authService.getInternalAccessToken(); + + if (!token) { + throw new Error('No authentication token available'); + } + + const headers = new HttpHeaders() + .set('Content-Type', 'application/json') + .set('Authorization', `Bearer ${token}`); + + return this.sseClient.stream( + `${this.url}/${bookId}/metadata/prospective`, + { + keepAlive: false, + reconnectionDelay: 1000, + responseType: 'event' + }, + { + headers, + body: request, + withCredentials: true + }, + 'POST' + ).pipe( + map((event) => { + if (event.type === 'error') { + const errorEvent = event as ErrorEvent; + throw new Error(errorEvent.message); + } else { + const messageEvent = event as MessageEvent; + return JSON.parse(messageEvent.data) as BookMetadata; + } + }) + ); + } +} 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 index 7c83de699..68dff8057 100644 --- a/booklore-ui/src/app/features/book/service/book.service.spec.ts +++ b/booklore-ui/src/app/features/book/service/book.service.spec.ts @@ -12,7 +12,6 @@ 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'; -import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-request.model'; describe('BookService', () => { let service: BookService; @@ -376,18 +375,6 @@ describe('BookService', () => { }); describe('Metadata Operations', () => { - it('should fetch book metadata', async () => { - httpMock.post.mockReturnValue(of([{bookId: 1}])); - const req: FetchMetadataRequest = { - bookId: 1, - providers: [], - title: '', - author: '', - isbn: '' - }; - const result = await firstValueFrom(service.fetchBookMetadata(1, req)); - expect(result).toEqual([{bookId: 1}]); - }); it('should update book metadata', async () => { httpMock.put.mockReturnValue(of({bookId: 1})); 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 09562bf0d..d8029e2f9 100644 --- a/booklore-ui/src/app/features/book/service/book.service.ts +++ b/booklore-ui/src/app/features/book/service/book.service.ts @@ -5,7 +5,6 @@ import {catchError, distinctUntilChanged, filter, finalize, map, shareReplay, ta import {AdditionalFile, AdditionalFileType, Book, BookDeletionResponse, BookMetadata, BookRecommendation, BookSetting, BulkMetadataUpdateRequest, MetadataUpdateWrapper, ReadStatus} from '../model/book.model'; import {BookState} from '../model/state/book-state.model'; import {API_CONFIG} from '../../../core/config/api-config'; -import {FetchMetadataRequest} from '../../metadata/model/request/fetch-metadata-request.model'; import {MessageService} from 'primeng/api'; import {ResetProgressType} from '../../../shared/constants/reset-progress-type'; import {AuthService} from '../../../shared/service/auth.service'; @@ -426,9 +425,6 @@ export class BookService { /*------------------ Metadata Operations ------------------*/ - fetchBookMetadata(bookId: number, request: FetchMetadataRequest): Observable { - return this.http.post(`${this.url}/${bookId}/metadata/prospective`, request); - } updateBookMetadata(bookId: number | undefined, wrapper: MetadataUpdateWrapper, mergeCategories: boolean): Observable { const params = new HttpParams().set('mergeCategories', mergeCategories.toString()); diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.html b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.html index 437b5bede..59038b2ce 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.html +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.html @@ -1,5 +1,5 @@ @if (selectedFetchedMetadata$ | async; as selectedFetchedMetadata) { -
+ } @else { -
- -
-
-
- +
+ +
+
+ + placeholder="Select providers" + [styleClass]="'custom-multiselect'">
-
- - +
+ +
-
- - +
+ +
-
- - +
+ +
-
- -
- - +
+ + +
+
+ + + @if (loading || searchTriggered) { +
+
+
+

+ + Search Results +

+ {{ filteredMetadata.length }} books found
+ @if (loading) { + + + Fetching... + + }
-
-
- - - When an ISBN is provided, the search will use only the ISBN. If no ISBN is given, the search will fall back to Title and Author. - -
-
- - @if (loading) { -
- -

- Fetching metadata from your selected sources.
- This may take a few moments... -

-
- } - - @if (!loading) { - @if (searchTriggered && allFetchedMetadata.length === 0) { -
-

No metadata results found.
Try adjusting your search criteria.

-
- } - @if (!searchTriggered && allFetchedMetadata.length === 0) { -
-

Start by searching for metadata using the search bar above.

-
- } - @if (allFetchedMetadata.length > 0) { -
- @for (metadata of allFetchedMetadata; track metadata) { -
-
- Image -
-
-

{{ truncateText(metadata['title']!, 90) }}

-
- @if (metadata['isbn10']) { -

ISBN10: {{ metadata['isbn10']}}

- - } - @if (metadata['isbn13']) { -

ISBN13: {{ metadata['isbn13']}}

- - } -

Published: {{ metadata['publishedDate'] }}

-
-
-
- @if (metadata['authors'] && metadata['authors'].length > 0) { -

by {{ truncateText(metadata['authors'].join(', '), 70) }}

- - } -

Source:

-
-

- {{ sanitizeHtml(metadata['description']) }} -

-
+
+ @for (tab of getProviderTabs(); track tab.provider) { +
+
+ +
+
+ {{ tab.provider }} + @if (isProviderLoading(tab.provider)) { + + } @else { + {{ tab.count }} + }
-
}
- } +
} - + + @if (!searchTriggered && allFetchedMetadata.length === 0) { +
+
+ +
+

Ready to Search

+

Enter your search criteria above and click Search to find metadata

+
+ } + + @if (searchTriggered && allFetchedMetadata.length === 0 && !loading) { +
+
+ +
+

No Results Found

+

Try adjusting your search criteria or selecting different providers

+
+ } + + @if (allFetchedMetadata.length > 0) { +
+
+ @for (metadata of filteredMetadata; track trackByMetadata($index, metadata)) { + + } +
+
+ } +
} diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.scss b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.scss index 93112b5f1..1de005bb5 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.scss +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.scss @@ -1,36 +1,725 @@ -.truncate-text { +$provider-colors: ( + 'amazon': #FF9902, + 'goodreads': #bc957a, + 'google': #0DB65D, + 'hardcover': #6366F1, + 'douban': #1474E9, + 'lubimyczytac': #FF5501, + 'comicvine': #F9E04F +); + +.metadata-container { + height: 100%; + width: 100%; + flex: auto; +} + +.searcher-container { + max-width: 1600px; + margin: 0 auto; + animation: fadeIn 0.3s ease-in; +} + +@keyframes fadeIn { + from { + opacity: 0; + transform: translateY(10px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +.search-header { + margin-bottom: 1.5rem; + + .header-content { + text-align: center; + } + + .header-title { + font-size: 1.5rem; + font-weight: 700; + margin: 0 0 0.375rem; + color: var(--text-color); + display: flex; + align-items: center; + justify-content: center; + gap: 0.5rem; + + i { + color: var(--primary-color); + font-size: 1.5rem; + } + } + + .header-subtitle { + font-size: 0.875rem; + color: var(--text-color-secondary); + margin: 0; + } +} + +.search-card { + background: var(--p-surface-900); + border-radius: 0.75rem; + padding: 1.25rem; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); + border: 1px solid var(--border-color); + margin-bottom: 1.25rem; + transition: all 0.3s ease; + + &:hover { + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3); + } +} + +.search-grid { + display: grid; + grid-template-columns: 1fr; + gap: 1rem; + margin-bottom: 1rem; + + @media (min-width: 640px) { + grid-template-columns: repeat(2, 1fr); + } + + @media (min-width: 1024px) { + grid-template-columns: 2fr 1fr 1.5fr 1.5fr auto; + align-items: end; + } +} + +.search-field { + display: flex; + flex-direction: column; + gap: 0.375rem; + + label { + font-weight: 600; + font-size: 0.875rem; + color: var(--text-color); + display: flex; + align-items: center; + gap: 0.375rem; + + i { + color: var(--primary-color); + font-size: 0.8125rem; + } + } + + &.search-field-provider { + @media (min-width: 640px) { + grid-column: span 2; + } + + @media (min-width: 1024px) { + grid-column: auto; + } + } + + &.search-button-field { + @media (min-width: 640px) { + grid-column: span 2; + } + + @media (min-width: 1024px) { + grid-column: auto; + } + } +} + +::ng-deep { + .custom-search-button { + width: 100%; + height: 2.5rem; + font-weight: 600; + font-size: 0.9375rem; + border-radius: 0.5rem; + + @media (min-width: 1024px) { + width: auto; + min-width: 8rem; + } + } +} + +.search-info { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.75rem; + background: var(--p-surface-900); + border-radius: 0.5rem; + font-size: 0.875rem; + color: var(--text-color-secondary); + border-left: 3px solid var(--primary-color); + + i { + color: var(--primary-color); + font-size: 0.9375rem; + flex-shrink: 0; + } +} + +.provider-status { + background: var(--p-surface-900); + border-radius: 0.75rem; + padding: 1rem; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); + border: 1px solid var(--border-color); + margin-bottom: 1.25rem; + animation: slideIn 0.3s ease-out; +} + +@keyframes slideIn { + from { + opacity: 0; + transform: translateX(-20px); + } + to { + opacity: 1; + transform: translateX(0); + } +} + +@keyframes slideInFromTop { + from { + opacity: 0; + transform: translateY(-20px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +.status-header { + display: flex; + justify-content: flex-start; + align-items: center; + margin-bottom: 1rem; + flex-wrap: wrap; + gap: 0.75rem; + + .results-info { + display: flex; + align-items: center; + gap: 0.75rem; + } + + h3 { + margin: 0; + font-size: 1.0625rem; + font-weight: 600; + color: var(--text-color); + display: flex; + align-items: center; + gap: 0.375rem; + + i { + color: var(--primary-color); + font-size: 0.9375rem; + } + } + + .results-count { + padding: 0.25rem 0.75rem; + background: rgba(var(--primary-color-rgb, 99, 102, 241), 0.2); + color: var(--primary-color); + border-radius: 2rem; + font-size: 0.875rem; + font-weight: 700; + border: 1px solid var(--primary-color); + } +} + +.fetching-badge { + display: flex; + align-items: center; + gap: 0.375rem; + padding: 0.25rem 0.85rem; + background: rgba(34, 197, 94, 0.8); + color: white; + border-radius: 2rem; + font-size: 0.85rem; + font-weight: 700; + box-shadow: 0 2px 8px rgba(34, 197, 94, 0.35); +} + +.provider-pills { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); + gap: 0.75rem; +} + +.provider-pill { + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.5rem 0.75rem; + background: var(--p-surface-900); + border: 1px solid var(--p-surface-600); + border-radius: 0.5rem; + transition: all 0.3s ease; + user-select: none; + + &.has-results { + background: var(--p-surface-900); + border-color: var(--primary-color); + cursor: pointer; + + .pill-icon { + background: rgba(var(--primary-color-rgb, 99, 102, 241), 0.12); + color: var(--primary-color); + } + + .pill-count { + background: rgba(var(--primary-color-rgb, 99, 102, 241), 0.18); + color: #fff; + font-weight: 700; + } + } + + &.active { + background: rgba(var(--primary-color-rgb, 99, 102, 241), 0.10); + border-color: var(--primary-color); + box-shadow: 0 0 0 2px rgba(var(--primary-color-rgb, 99, 102, 241), 0.10), + 0 2px 6px rgba(var(--primary-color-rgb, 99, 102, 241), 0.10); + transform: translateY(-1px); + + .pill-icon { + background: rgba(var(--primary-color-rgb, 99, 102, 241), 0.18); + color: var(--primary-color); + } + + .pill-name { + color: var(--primary-color); + font-weight: 700; + } + + .pill-count { + background: rgba(var(--primary-color-rgb, 99, 102, 241), 0.22); + color: #fff; + font-weight: 800; + } + } + + @each $provider, $color in $provider-colors { + &.provider-#{$provider} { + &.has-results { + border-color: $color; + + .pill-icon { + background: rgba($color, 0.12); + color: $color; + } + + .pill-count { + background: rgba($color, 0.18); + color: #fff; + font-weight: 700; + } + + .pill-name { + color: $color; + } + } + + &.active { + background: rgba($color, 0.2); + border-color: $color; + box-shadow: 0 0 0 2px rgba($color, 0.10), 0 2px 6px rgba($color, 0.10); + + .pill-name { + color: $color; + } + + .pill-icon { + background: rgba($color, 0.18); + color: $color; + } + + .pill-count { + background: rgba($color, 0.22); + color: #fff; + font-weight: 800; + } + } + } + } + + &:hover { + transform: translateY(-2px); + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2); + } + + &.active:hover { + transform: translateY(-3px); + } +} + +.pill-icon { + display: flex; + align-items: center; + justify-content: center; + width: 2rem; + height: 2rem; + background: var(--p-surface-600); + border-radius: 0.375rem; + color: var(--text-color-secondary); + flex-shrink: 0; + transition: all 0.3s ease; + + i { + font-size: 0.9375rem; + } +} + +.pill-content { + flex: 1; + display: flex; + justify-content: space-between; + align-items: center; + + .pill-name { + font-weight: 700; + font-size: 0.95rem; + color: var(--text-color); + } + + .pill-count { + display: flex; + align-items: center; + justify-content: center; + min-width: 1.75rem; + height: 1.75rem; + padding: 0 0.375rem; + background: var(--p-surface-600); + color: #fff; + border-radius: 2rem; + font-weight: 800; + font-size: 1rem; + text-shadow: 0 1px 2px rgba(0, 0, 0, 0.12); + } +} + +.empty-state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 3rem 1.5rem; + text-align: center; + + .empty-icon { + width: 4rem; + height: 4rem; + display: flex; + align-items: center; + justify-content: center; + background: var(--p-surface-900); + border-radius: 50%; + margin-bottom: 1rem; + + i { + font-size: 2rem; + color: var(--primary-color); + } + + &.no-results { + background: var(--p-surface-900); + + i { + color: var(--text-color-secondary); + } + } + } + + h3 { + margin: 0 0 0.375rem; + font-size: 1.25rem; + font-weight: 600; + color: var(--text-color); + } + + p { + margin: 0; + font-size: 0.875rem; + color: var(--text-color-secondary); + max-width: 500px; + } +} + +.results-section { + animation: fadeIn 0.3s ease-in; +} + +.results-toolbar { + display: flex; + flex-direction: column; + gap: 0.75rem; + margin-bottom: 1rem; + padding: 1rem; + background: var(--p-surface-900); + border-radius: 0.75rem; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); + border: 1px solid var(--border-color); + + @media (min-width: 768px) { + flex-direction: row; + justify-content: space-between; + align-items: center; + } +} + +.results-info { + display: flex; + flex-direction: column; + gap: 0.375rem; + + @media (min-width: 768px) { + flex-direction: row; + align-items: center; + gap: 0.75rem; + } + + h3 { + margin: 0; + font-size: 1.0625rem; + font-weight: 600; + color: var(--text-color); + display: flex; + align-items: center; + gap: 0.375rem; + + i { + color: var(--primary-color); + font-size: 0.9375rem; + } + } + + .results-count { + padding: 0.1875rem 0.625rem; + background: var(--p-surface-900); + color: var(--primary-color); + border-radius: 2rem; + font-size: 0.8125rem; + font-weight: 600; + } +} + +.results-filter { + display: flex; + align-items: center; + gap: 0.5rem; + + label { + font-weight: 600; + font-size: 0.875rem; + color: var(--text-color); + display: flex; + align-items: center; + gap: 0.375rem; + white-space: nowrap; + + i { + color: var(--primary-color); + font-size: 0.8125rem; + } + } + + p-select { + min-width: 180px; + } +} + +.results-grid { + display: grid; + grid-template-columns: 1fr; + gap: 1rem; + + @media (min-width: 768px) { + grid-template-columns: repeat(2, 1fr); + } + + @media (min-width: 1200px) { + grid-template-columns: repeat(3, 1fr); + } +} + +.metadata-card { + background: var(--p-surface-900); + border-radius: 0.75rem; + overflow: hidden; + box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2); + border: 1px solid var(--border-color); + cursor: pointer; + transition: all 0.3s ease; + display: flex; + flex-direction: row; + height: 200px; + animation: slideInFromTop 0.4s ease-out; + + &:hover { + transform: translateY(-4px); + box-shadow: 0 8px 16px rgba(0, 0, 0, 0.3); + border-color: var(--primary-color); + + .card-overlay { + opacity: 1; + } + + .card-image img { + transform: scale(1.05); + } + } +} + +.card-image { + position: relative; + width: 140px; + min-width: 140px; + height: 200px; + overflow: hidden; + background: var(--p-surface-900); + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + + img { + width: 140px; + height: 200px; + object-fit: cover; + transition: transform 0.3s ease; + } + + .card-overlay { + position: absolute; + inset: 0; + background: rgba(0, 0, 0, 0.75); + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 0.375rem; + opacity: 0; + transition: opacity 0.3s ease; + color: white; + + i { + font-size: 1.5rem; + } + + span { + font-weight: 600; + font-size: 0.875rem; + } + } +} + +.card-content { + padding: 1rem; + display: flex; + flex-direction: column; + gap: 0.625rem; + flex: 1; + min-width: 0; + overflow: hidden; +} + +.card-header { + display: flex; + flex-direction: column; + gap: 0.375rem; +} + +.card-title { + margin: 0; + font-size: 1rem; + font-weight: 700; + color: var(--text-color); + line-height: 1.3; display: -webkit-box; - -webkit-line-clamp: 4; + -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; +} + +.card-provider { + font-size: 0.9rem; + + ::ng-deep a { + text-decoration: none; + font-weight: 700; + + &:hover { + text-decoration: underline; + } + } + + @each $provider, $color in $provider-colors { + &.provider-#{$provider} ::ng-deep a { + color: $color; + } + } +} + +.card-authors { + margin: 0; + font-size: 0.9rem; + color: var(--text-color-secondary); + display: flex; + align-items: center; + gap: 0.375rem; + white-space: nowrap; + overflow: hidden; text-overflow: ellipsis; + font-weight: 700; + + i { + color: var(--primary-color); + font-size: 0.8125rem; + flex-shrink: 0; + } } -.img-fixed-dimensions { - height: 150px; - width: 100px; - object-fit: fill; +.card-meta { + display: flex; + flex-wrap: wrap; + gap: 0.375rem; } -.book-item { - position: relative; - cursor: pointer; +.meta-badge { + display: inline-flex; + align-items: center; + gap: 0.25rem; + padding: 0.5rem 0.5rem 0.5rem 0; + background: var(--p-surface-900); + border-radius: 0.25rem; + font-size: 0.8rem; + color: var(--text-color-secondary); + font-weight: 500; + white-space: nowrap; + + i { + padding-right: 0.25rem; + font-size: 0.6875rem; + color: var(--primary-color); + flex-shrink: 0; + } } -.book-item-content { - position: relative; -} - -.book-item:hover .book-item-content::after { - content: ''; - position: absolute; - top: 0; - left: 0; - right: 0; - bottom: 0; - background-color: rgba(255, 255, 255, 0.075); -} - -.book-item:hover .book-item-content { - box-shadow: 0 0 0 rgba(255, 255, 255, 0.9); +.card-description { + margin: 0; + font-size: 0.875rem; + color: var(--text-color-secondary); + line-height: 1.4; + display: -webkit-box; + -webkit-line-clamp: 6; + -webkit-box-orient: vertical; + overflow: hidden; } diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.ts index 6f5c1a683..2fe5a2192 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-searcher/metadata-searcher.component.ts @@ -1,14 +1,11 @@ import {Component, inject, Input, OnDestroy, OnInit} from '@angular/core'; -import {FormBuilder, FormGroup, ReactiveFormsModule} from '@angular/forms'; +import {FormBuilder, FormGroup, FormsModule, ReactiveFormsModule} from '@angular/forms'; import {Button} from 'primeng/button'; import {InputText} from 'primeng/inputtext'; -import {Divider} from 'primeng/divider'; import {MultiSelect} from 'primeng/multiselect'; -import {ProgressSpinner} from 'primeng/progressspinner'; import {FetchMetadataRequest} from '../../../model/request/fetch-metadata-request.model'; import {Book, BookMetadata} from '../../../../book/model/book.model'; -import {BookService} from '../../../../book/service/book.service'; import {AppSettings} from '../../../../../shared/model/app-settings.model'; import {AppSettingsService} from '../../../../../shared/service/app-settings.service'; @@ -17,6 +14,8 @@ import {distinctUntilChanged, filter, switchMap} from 'rxjs/operators'; import {ActivatedRoute} from '@angular/router'; import {AsyncPipe} from '@angular/common'; import {MetadataPickerComponent} from '../metadata-picker/metadata-picker.component'; +import {BookMetadataService} from '../../../../book/service/book-metadata.service'; +import {Tooltip} from 'primeng/tooltip'; @Component({ selector: 'app-metadata-searcher', @@ -24,13 +23,13 @@ import {MetadataPickerComponent} from '../metadata-picker/metadata-picker.compon styleUrls: ['./metadata-searcher.component.scss'], imports: [ ReactiveFormsModule, + FormsModule, Button, InputText, - Divider, - ProgressSpinner, MetadataPickerComponent, MultiSelect, - AsyncPipe + AsyncPipe, + Tooltip ], standalone: true }) @@ -47,7 +46,7 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy { selectedFetchedMetadata$ = new BehaviorSubject(null); private formBuilder = inject(FormBuilder); - private bookService = inject(BookService); + private bookMetadataService = inject(BookMetadataService); private appSettingsService = inject(AppSettingsService); private route = inject(ActivatedRoute); @@ -56,6 +55,15 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy { appSettings$: Observable = this.appSettingsService.appSettings$; + providerCounts: Map = new Map(); + providerLoading: Map = new Map(); + selectedProviderFilters: Set = new Set(['all']); + filteredMetadata: BookMetadata[] = []; + providerFilterOptions: Array<{ label: string; value: string }> = []; + + private metadataByProvider: Map = new Map(); + private providerCompletionStatus: Map = new Map(); + constructor() { this.form = this.formBuilder.group({ provider: null, @@ -76,6 +84,8 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy { this.cancelRequest$.next(); this.loading = false; this.allFetchedMetadata = []; + this.filteredMetadata = []; + this.providerCounts.clear(); this.selectedFetchedMetadata$.next(null); } return combineLatest([this.book$, this.appSettings$]); @@ -101,6 +111,10 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy { private resetFormFromBook(book: Book): void { this.selectedFetchedMetadata$.next(null); this.allFetchedMetadata = []; + this.filteredMetadata = []; + this.providerCounts.clear(); + this.metadataByProvider.clear(); + this.selectedProviderFilters = new Set(['all']); this.bookId = book.id; this.form.patchValue({ @@ -139,20 +153,68 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy { }; this.loading = true; + this.allFetchedMetadata = []; + this.filteredMetadata = []; + this.providerCounts.clear(); + this.providerLoading.clear(); + this.providerCompletionStatus.clear(); + this.metadataByProvider.clear(); + this.selectedProviderFilters = new Set(['all']); this.cancelRequest$.next(); - this.bookService.fetchBookMetadata(fetchRequest.bookId, fetchRequest) + providerKeys.forEach((provider: string) => { + const providerLower = provider.toLowerCase(); + this.providerCounts.set(providerLower, 0); + this.providerLoading.set(providerLower, true); + this.providerCompletionStatus.set(providerLower, false); + this.metadataByProvider.set(providerLower, []); + }); + + this.updateProviderFilterOptions(); + + const activeProviders = new Set(providerKeys.map((p: string) => p.toLowerCase())); + + this.bookMetadataService.fetchBookMetadata(fetchRequest.bookId, fetchRequest) .pipe(takeUntil(this.cancelRequest$)) .subscribe({ - next: (fetchedMetadata) => { - this.loading = false; - this.allFetchedMetadata = fetchedMetadata.map(m => ({ - ...m, - thumbnailUrl: m.thumbnailUrl - })); + next: (metadata) => { + const metadataWithThumbnail = { + ...metadata, + thumbnailUrl: metadata.thumbnailUrl + }; + + const provider = this.getProviderFromMetadata(metadata); + if (provider) { + const providerList = this.metadataByProvider.get(provider) || []; + providerList.push(metadataWithThumbnail); + this.metadataByProvider.set(provider, providerList); + + this.providerCounts.set(provider, providerList.length); + + if (!this.providerCompletionStatus.get(provider)) { + this.providerLoading.set(provider, false); + this.providerCompletionStatus.set(provider, true); + } + } + + this.allFetchedMetadata = this.interleaveResults(); + + this.applyFilter(); + this.updateProviderFilterOptions(); }, - error: () => { + error: (error) => { + console.error('Error fetching metadata:', error); this.loading = false; + this.providerLoading.clear(); + }, + complete: () => { + this.loading = false; + activeProviders.forEach((provider: string) => { + if (!this.providerCompletionStatus.get(provider)) { + this.providerLoading.set(provider, false); + this.providerCompletionStatus.set(provider, true); + } + }); } }); } else { @@ -160,6 +222,108 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy { } } + private interleaveResults(): BookMetadata[] { + const interleaved: BookMetadata[] = []; + const providers = Array.from(this.metadataByProvider.keys()); + + if (providers.length === 0) return []; + + const maxLength = Math.max( + ...Array.from(this.metadataByProvider.values()).map(list => list.length) + ); + + for (let i = 0; i < maxLength; i++) { + for (const provider of providers) { + const providerList = this.metadataByProvider.get(provider); + if (providerList && i < providerList.length) { + interleaved.push(providerList[i]); + } + } + } + + return interleaved; + } + + private getProviderFromMetadata(metadata: BookMetadata): string | null { + if (metadata.asin) return 'amazon'; + if (metadata.goodreadsId) return 'goodreads'; + if (metadata.googleId) return 'google'; + if (metadata.hardcoverId) return 'hardcover'; + if (metadata['doubanId']) return 'douban'; + if (metadata['lubimyczytacId']) return 'lubimyczytac'; + if (metadata.comicvineId) return 'comicvine'; + return null; + } + + getProviderClass(metadata: BookMetadata): string { + return this.getProviderFromMetadata(metadata) || 'unknown'; + } + + private updateProviderFilterOptions(): void { + this.providerFilterOptions = [ + {label: `All (${this.allFetchedMetadata.length})`, value: 'all'}, + ...Array.from(this.providerCounts.entries()) + .filter(([_, count]) => count > 0) + .map(([provider, count]) => ({ + label: `${provider.charAt(0).toUpperCase() + provider.slice(1)} (${count})`, + value: provider + })) + ]; + } + + onProviderPillClick(provider: string, event: MouseEvent): void { + const providerLower = provider.toLowerCase(); + + if (event.ctrlKey || event.metaKey) { + if (this.selectedProviderFilters.has(providerLower)) { + this.selectedProviderFilters.delete(providerLower); + } else { + this.selectedProviderFilters.add(providerLower); + this.selectedProviderFilters.delete('all'); + } + + if (this.selectedProviderFilters.size === 0) { + this.selectedProviderFilters.add('all'); + } + } else { + if (this.selectedProviderFilters.has(providerLower) && this.selectedProviderFilters.size === 1) { + this.selectedProviderFilters.clear(); + this.selectedProviderFilters.add('all'); + } else { + this.selectedProviderFilters.clear(); + this.selectedProviderFilters.add(providerLower); + } + } + + this.applyFilter(); + } + + isProviderPillActive(provider: string): boolean { + return this.selectedProviderFilters.has(provider.toLowerCase()); + } + + isProviderLoading(provider: string): boolean { + return this.providerLoading.get(provider.toLowerCase()) ?? false; + } + + private applyFilter(): void { + if (this.selectedProviderFilters.has('all')) { + this.filteredMetadata = [...this.allFetchedMetadata]; + } else { + this.filteredMetadata = this.allFetchedMetadata.filter(metadata => { + const provider = this.getProviderFromMetadata(metadata); + return provider && this.selectedProviderFilters.has(provider); + }); + } + } + + getProviderTabs(): Array<{ provider: string; count: number }> { + return Array.from(this.providerCounts.entries()).map(([provider, count]) => ({ + provider: provider.charAt(0).toUpperCase() + provider.slice(1), + count + })); + } + onBookClick(fetchedMetadata: BookMetadata) { this.selectedFetchedMetadata$.next(fetchedMetadata); } @@ -201,4 +365,16 @@ export class MetadataSearcherComponent implements OnInit, OnDestroy { } throw new Error("No provider ID found in metadata."); } + + trackByMetadata(index: number, metadata: BookMetadata): string { + return metadata.googleId || metadata.goodreadsId || metadata.asin || + metadata.hardcoverId || metadata.comicvineId || index.toString(); + } + + onProviderClick(event: MouseEvent) { + const target = event.target as HTMLElement; + if (target.tagName === 'A' || target.closest('a')) { + event.stopPropagation(); + } + } } From bd3df812b775dec512fa3e161564d63807a1a582 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= <127139797+balazs-szucs@users.noreply.github.com> Date: Wed, 7 Jan 2026 19:27:12 +0100 Subject: [PATCH 18/40] fix(lubimyczytac): Fix Lubimyczytac metadata lock persistence (#2194) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(metadata): add support for Lubimyczytac ID and rating fields Signed-off-by: Balázs Szücs * feat(metadata): add Lubimyczytac ID and rating fields to metadata editor Signed-off-by: Balázs Szücs * feat(metadata): add Lubimyczytac ID and rating fields to MetadataRefreshOptions Signed-off-by: Balázs Szücs --------- Signed-off-by: Balázs Szücs --- .../booklore/model/dto/request/MetadataRefreshOptions.java | 4 ++++ .../booklore/service/metadata/BookMetadataUpdater.java | 2 ++ .../metadata-editor/metadata-editor.component.ts | 6 ++++++ 3 files changed, 12 insertions(+) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/MetadataRefreshOptions.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/MetadataRefreshOptions.java index 3c9745b97..ebdc9d22f 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/MetadataRefreshOptions.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/request/MetadataRefreshOptions.java @@ -51,12 +51,14 @@ public class MetadataRefreshOptions { private FieldProvider comicvineId; private FieldProvider hardcoverId; private FieldProvider googleId; + private FieldProvider lubimyczytacId; private FieldProvider amazonRating; private FieldProvider amazonReviewCount; private FieldProvider goodreadsRating; private FieldProvider goodreadsReviewCount; private FieldProvider hardcoverRating; private FieldProvider hardcoverReviewCount; + private FieldProvider lubimyczytacRating; private FieldProvider moods; private FieldProvider tags; } @@ -99,12 +101,14 @@ public class MetadataRefreshOptions { private boolean comicvineId; private boolean hardcoverId; private boolean googleId; + private boolean lubimyczytacId; private boolean amazonRating; private boolean amazonReviewCount; private boolean goodreadsRating; private boolean goodreadsReviewCount; private boolean hardcoverRating; private boolean hardcoverReviewCount; + private boolean lubimyczytacRating; private boolean moods; private boolean tags; } 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 3ac12ca6b..6b39b78f9 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 @@ -382,6 +382,8 @@ public class BookMetadataUpdater { Pair.of(m.getComicvineIdLocked(), e::setComicvineIdLocked), Pair.of(m.getHardcoverIdLocked(), e::setHardcoverIdLocked), Pair.of(m.getHardcoverBookIdLocked(), e::setHardcoverBookIdLocked), + Pair.of(m.getLubimyczytacIdLocked(), e::setLubimyczytacIdLocked), + Pair.of(m.getLubimyczytacRatingLocked(), e::setLubimyczytacRatingLocked), Pair.of(m.getGoogleIdLocked(), e::setGoogleIdLocked), Pair.of(m.getPageCountLocked(), e::setPageCountLocked), Pair.of(m.getLanguageLocked(), e::setLanguageLocked), diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts index ac6f258ad..9a3ad1a7f 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.ts @@ -365,6 +365,8 @@ export class MetadataEditorComponent implements OnInit { {key: "hardcoverBookIdLocked", control: "hardcoverBookId"}, {key: "hardcoverReviewCountLocked", control: "hardcoverReviewCount"}, {key: "hardcoverRatingLocked", control: "hardcoverRating"}, + {key: "lubimyczytacIdLocked", control: "lubimyczytacId"}, + {key: "lubimyczytacRatingLocked", control: "lubimyczytacRating"}, {key: "googleIdLocked", control: "googleId"}, {key: "pageCountLocked", control: "pageCount"}, {key: "descriptionLocked", control: "description"}, @@ -504,6 +506,8 @@ export class MetadataEditorComponent implements OnInit { hardcoverBookId: form.get("hardcoverBookId")?.value, hardcoverRating: form.get("hardcoverRating")?.value, hardcoverReviewCount: form.get("hardcoverReviewCount")?.value, + lubimyczytacId: form.get("lubimyczytacId")?.value, + lubimyczytacRating: form.get("lubimyczytacRating")?.value, googleId: form.get("googleId")?.value, language: form.get("language")?.value, seriesName: form.get("seriesName")?.value, @@ -536,6 +540,8 @@ export class MetadataEditorComponent implements OnInit { hardcoverBookIdLocked: form.get("hardcoverBookIdLocked")?.value, hardcoverRatingLocked: form.get("hardcoverRatingLocked")?.value, hardcoverReviewCountLocked: form.get("hardcoverReviewCountLocked")?.value, + lubimyczytacIdLocked: form.get("lubimyczytacIdLocked")?.value, + lubimyczytacRatingLocked: form.get("lubimyczytacRatingLocked")?.value, googleIdLocked: form.get("googleIdLocked")?.value, seriesNameLocked: form.get("seriesNameLocked")?.value, seriesNumberLocked: form.get("seriesNumberLocked")?.value, From c7afe6ec1304d3b0d3d7f1a60c9b5ed6c07aa056 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Wed, 7 Jan 2026 14:13:42 -0700 Subject: [PATCH 19/40] Implement memoization in the book card to reduce CPU usage during scrolling (#2198) Co-authored-by: acx10 --- .../book-card/book-card.component.html | 109 ++++---- .../book-card/book-card.component.scss | 14 +- .../book-card/book-card.component.ts | 138 ++++++---- .../service/local-storage.service.spec.ts | 49 ---- .../service/reading-session.service.spec.ts | 250 ------------------ 5 files changed, 143 insertions(+), 417 deletions(-) delete mode 100644 booklore-ui/src/app/shared/service/local-storage.service.spec.ts delete mode 100644 booklore-ui/src/app/shared/service/reading-session.service.spec.ts 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 79bef988c..0a554be1e 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 @@ -1,24 +1,16 @@
-
-
- Cover of {{ displayTitle }} -
+
+ @if (!book.seriesCount && book.metadata?.seriesNumber != null) {
@@ -26,19 +18,21 @@
} - @if (book.seriesCount && book.seriesCount! >= 1) { -
+ @if (book.seriesCount && book.seriesCount >= 1) { +
{{ book.seriesCount }}
} - @if (isSeriesViewActive()) { + @if (_isSeriesViewActive) { } @else { } - + @if (!_isSeriesViewActive && _canReadBook) { + + } @if (isCheckboxEnabled) { } -
- @if (progressPercentage !== null) { - - - } - @if (koProgressPercentage !== null) { - - - } - @if (koboProgressPercentage !== null) { - - - } -
+ + @if (hasProgress) { +
+ @if (_progressPercentage !== null) { + + + } + @if (_koProgressPercentage !== null) { + + + } + @if (_koboProgressPercentage !== null) { + + + } +
+ }
-
+ @if (!bottomBarHidden) {
- @if (shouldShowStatusIcon()) { + @if (_shouldShowStatusIcon) {
- +
}

+ [pTooltip]="titleTooltip"> {{ displayTitle }}

@@ -105,5 +98,5 @@ icon="pi pi-ellipsis-v">
-
+ }
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 ae19f77c8..4580d7487 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 @@ -3,7 +3,6 @@ border-radius: 8px 8px 8px 8px; position: relative; overflow: hidden; - transition: border 0.2s; &.selected { border: 2px solid var(--primary-color); @@ -20,7 +19,6 @@ display: flex; align-items: center; justify-content: center; - transition: background-color 0.3s ease; } .cover-container.loaded { @@ -32,11 +30,11 @@ height: 100%; object-fit: cover; border-radius: 8px 8px 0 0; - transition: opacity 0.3s ease-in; opacity: 0; + transition: opacity 0.2s ease-in; } -.cover-container img.loaded { +.book-cover.loaded { opacity: 1; } @@ -49,7 +47,7 @@ height: 100%; background: radial-gradient(circle, rgba(0, 0, 0, 0) 25%, rgba(0, 0, 0, 0.6) 100%); opacity: 0; - transition: opacity 0.2s ease-in-out; + transition: opacity 0.15s ease-in-out; pointer-events: none; } @@ -80,8 +78,9 @@ transform: translateX(-50%); opacity: 0; visibility: hidden; - transition: opacity 0.3s ease, visibility 0.3s ease; + transition: opacity 0.15s ease, visibility 0.15s ease; z-index: 2; + will-change: opacity, visibility; } .info-btn { @@ -109,8 +108,9 @@ right: 8px; opacity: 0; visibility: hidden; - transition: opacity 0.2s ease, visibility 0.2s ease; + transition: opacity 0.15s ease, visibility 0.15s ease; z-index: 2; + will-change: opacity, visibility; } .select-checkbox .p-checkbox { 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 66c5cbdc1..167c397a8 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 @@ -1,4 +1,4 @@ -import {Component, ElementRef, EventEmitter, inject, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild} from '@angular/core'; +import {ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, inject, Input, OnChanges, OnDestroy, OnInit, Output, SimpleChanges, ViewChild} from '@angular/core'; import {TooltipModule} from "primeng/tooltip"; import {AdditionalFile, Book, ReadStatus} from '../../../model/book.model'; import {Button} from 'primeng/button'; @@ -29,7 +29,8 @@ import {BookNavigationService} from '../../../service/book-navigation.service'; templateUrl: './book-card.component.html', styleUrls: ['./book-card.component.scss'], imports: [Button, MenuModule, CheckboxModule, FormsModule, NgClass, TieredMenu, ProgressBar, TooltipModule], - standalone: true + standalone: true, + changeDetection: ChangeDetectionStrategy.OnPush }) export class BookCardComponent implements OnInit, OnChanges, OnDestroy { @@ -48,7 +49,6 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { @ViewChild('checkboxElem') checkboxElem!: ElementRef; items: MenuItem[] | undefined; - isHovered: boolean = false; isImageLoaded: boolean = false; isSubMenuLoading = false; private additionalFilesLoaded = false; @@ -63,13 +63,31 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { private confirmationService = inject(ConfirmationService); private bookDialogHelperService = inject(BookDialogHelperService); private bookNavigationService = inject(BookNavigationService); + private cdr = inject(ChangeDetectorRef); + + protected _progressPercentage: number | null = null; + protected _koProgressPercentage: number | null = null; + protected _koboProgressPercentage: number | null = null; + protected _displayTitle: string | undefined = undefined; + protected _canReadBook: boolean = true; + protected _isSeriesViewActive: boolean = false; + protected _coverImageUrl: string = ''; + protected _readStatusIcon: string = ''; + protected _readStatusClass: string = ''; + protected _readStatusTooltip: string = ''; + protected _shouldShowStatusIcon: boolean = false; + protected _seriesCountTooltip: string = ''; + protected _titleTooltip: string = ''; + protected _hasProgress: boolean = false; private metadataCenterViewMode: 'route' | 'dialog' = 'route'; private destroy$ = new Subject(); protected readStatusHelper = inject(ReadStatusHelper); private user: User | null = null; + private menuInitialized = false; ngOnInit(): void { + this.computeAllMemoizedValues(); this.userService.userState$ .pipe( filter(userState => !!userState?.user && userState.loaded), @@ -79,50 +97,79 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { .subscribe(userState => { this.user = userState.user; this.metadataCenterViewMode = userState.user?.userSettings?.metadataCenterViewMode ?? 'route'; - this.initMenu(); }); } ngOnChanges(changes: SimpleChanges): void { - if (changes['book'] && !changes['book'].firstChange) { - this.additionalFilesLoaded = false; - this.initMenu(); + if (changes['book']) { + this.computeAllMemoizedValues(); + if (!changes['book'].firstChange && this.menuInitialized) { + this.additionalFilesLoaded = false; + this.initMenu(); + } + } + + if (changes['seriesViewEnabled'] || changes['isSeriesCollapsed']) { + this._isSeriesViewActive = this.seriesViewEnabled && !!this.book.seriesCount && this.book.seriesCount >= 1; + this._displayTitle = (this.isSeriesCollapsed && this.book.metadata?.seriesName) ? this.book.metadata?.seriesName : this.book.metadata?.title; + this._titleTooltip = 'Title: ' + this._displayTitle; } } - get progressPercentage(): number | null { - if (this.book.epubProgress?.percentage != null) { - return this.book.epubProgress.percentage; - } - if (this.book.pdfProgress?.percentage != null) { - return this.book.pdfProgress.percentage; - } - if (this.book.cbxProgress?.percentage != null) { - return this.book.cbxProgress.percentage; - } - return null; + private computeAllMemoizedValues(): void { + this._progressPercentage = this.book.epubProgress?.percentage + ?? this.book.pdfProgress?.percentage + ?? this.book.cbxProgress?.percentage + ?? null; + + this._koProgressPercentage = this.book.koreaderProgress?.percentage ?? null; + this._koboProgressPercentage = this.book.koboProgress?.percentage ?? null; + + this._hasProgress = this._progressPercentage !== null || this._koProgressPercentage !== null || this._koboProgressPercentage !== null; + + this._isSeriesViewActive = this.seriesViewEnabled && !!this.book.seriesCount && this.book.seriesCount >= 1; + this._displayTitle = (this.isSeriesCollapsed && this.book.metadata?.seriesName) + ? this.book.metadata?.seriesName + : this.book.metadata?.title; + this._canReadBook = this.book?.bookType !== 'FB2'; + this._coverImageUrl = this.urlHelper.getThumbnailUrl(this.book.id, this.book.metadata?.coverUpdatedOn); + + this._readStatusIcon = this.readStatusHelper.getReadStatusIcon(this.book.readStatus); + this._readStatusClass = this.readStatusHelper.getReadStatusClass(this.book.readStatus); + this._readStatusTooltip = this.readStatusHelper.getReadStatusTooltip(this.book.readStatus); + this._shouldShowStatusIcon = this.readStatusHelper.shouldShowStatusIcon(this.book.readStatus); + + this._seriesCountTooltip = 'Series collapsed: ' + this.book.seriesCount + ' books'; + this._titleTooltip = 'Title: ' + this._displayTitle; } - get koProgressPercentage(): number | null { - if (this.book.koreaderProgress?.percentage != null) { - return this.book.koreaderProgress.percentage; - } - return null; + get hasProgress(): boolean { + return this._hasProgress; } - get koboProgressPercentage(): number | null { - if (this.book.koboProgress?.percentage != null) { - return this.book.koboProgress.percentage; - } - return null; + get seriesCountTooltip(): string { + return this._seriesCountTooltip; + } + + get titleTooltip(): string { + return this._titleTooltip; + } + + get readStatusTooltip(): string { + return this._readStatusTooltip; } get displayTitle(): string | undefined { - return (this.isSeriesCollapsed && this.book.metadata?.seriesName) ? this.book.metadata?.seriesName : this.book.metadata?.title; + return this._displayTitle; + } + + get coverImageUrl(): string { + return this._coverImageUrl; } onImageLoad(): void { this.isImageLoaded = true; + this.cdr.markForCheck(); } readBook(book: Book): void { @@ -138,19 +185,28 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { } onMenuToggle(event: Event, menu: TieredMenu): void { + if (!this.menuInitialized) { + this.menuInitialized = true; + this.initMenu(); + this.cdr.markForCheck(); + } + menu.toggle(event); if (!this.additionalFilesLoaded && !this.isSubMenuLoading && this.needsAdditionalFilesData()) { this.isSubMenuLoading = true; + this.cdr.markForCheck(); this.bookService.getBookByIdFromAPI(this.book.id, true).subscribe({ next: (book) => { this.book = book; this.additionalFilesLoaded = true; this.isSubMenuLoading = false; this.initMenu(); + this.cdr.markForCheck(); }, error: () => { this.isSubMenuLoading = false; + this.cdr.markForCheck(); } }); } @@ -671,10 +727,6 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { return sizeKb != null ? `${(sizeKb / 1024).toFixed(2)} MB` : '-'; } - canReadBook(): boolean { - return this.book?.bookType !== 'FB2'; - } - private lastMouseEvent: MouseEvent | null = null; captureMouseEvent(event: MouseEvent): void { @@ -719,24 +771,4 @@ export class BookCardComponent implements OnInit, OnChanges, OnDestroy { this.destroy$.next(); this.destroy$.complete(); } - - getReadStatusIcon(): string { - return this.readStatusHelper.getReadStatusIcon(this.book.readStatus); - } - - getReadStatusClass(): string { - return this.readStatusHelper.getReadStatusClass(this.book.readStatus); - } - - getReadStatusTooltip(): string { - return this.readStatusHelper.getReadStatusTooltip(this.book.readStatus); - } - - shouldShowStatusIcon(): boolean { - return this.readStatusHelper.shouldShowStatusIcon(this.book.readStatus); - } - - isSeriesViewActive(): boolean { - return this.seriesViewEnabled && !!this.book.seriesCount && this.book.seriesCount! >= 1; - } } diff --git a/booklore-ui/src/app/shared/service/local-storage.service.spec.ts b/booklore-ui/src/app/shared/service/local-storage.service.spec.ts deleted file mode 100644 index d4cc533b5..000000000 --- a/booklore-ui/src/app/shared/service/local-storage.service.spec.ts +++ /dev/null @@ -1,49 +0,0 @@ -import {describe, it, expect, beforeEach, vi} from 'vitest'; -import {LocalStorageService} from './local-storage.service'; - -describe('LocalStorageService', () => { - let service: LocalStorageService; - - beforeEach(() => { - service = new LocalStorageService(); - vi.spyOn(window.localStorage, 'getItem').mockClear(); - vi.spyOn(window.localStorage, 'setItem').mockClear(); - vi.spyOn(window.localStorage, 'removeItem').mockClear(); - }); - - it('should get value from localStorage', () => { - window.localStorage.setItem('test', JSON.stringify({foo: 'bar'})); - const result = service.get<{foo: string}>('test'); - expect(result).toEqual({foo: 'bar'}); - }); - - it('should return null if key does not exist', () => { - window.localStorage.removeItem('notfound'); - const result = service.get('notfound'); - expect(result).toBeNull(); - }); - - it('should handle JSON parse error and return null', () => { - window.localStorage.setItem('bad', 'not-json'); - const result = service.get('bad'); - expect(result).toBeNull(); - }); - - it('should set value in localStorage', () => { - service.set('foo', {bar: 123}); - const stored = window.localStorage.getItem('foo'); - expect(stored).toBe(JSON.stringify({bar: 123})); - }); - - it('should handle set error gracefully', () => { - vi.spyOn(window.localStorage, 'setItem').mockImplementation(() => { throw new Error('fail'); }); - expect(() => service.set('fail', {a: 1})).not.toThrow(); - }); - - it('should remove value from localStorage', () => { - window.localStorage.setItem('toremove', '1'); - service.remove('toremove'); - expect(window.localStorage.getItem('toremove')).toBeNull(); - }); -}); - diff --git a/booklore-ui/src/app/shared/service/reading-session.service.spec.ts b/booklore-ui/src/app/shared/service/reading-session.service.spec.ts deleted file mode 100644 index bec667937..000000000 --- a/booklore-ui/src/app/shared/service/reading-session.service.spec.ts +++ /dev/null @@ -1,250 +0,0 @@ -import {beforeEach, describe, expect, it, vi} from 'vitest'; -import {TestBed} from '@angular/core/testing'; -import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; -import {BookType} from '../../features/book/model/book.model'; -import {ReadingSessionService, ReadingSession} from './reading-session.service'; -import {ReadingSessionApiService, CreateReadingSessionDto} from './reading-session-api.service'; -import {of} from 'rxjs'; - -describe('ReadingSessionService', () => { - let service: ReadingSessionService; - let apiServiceMock: any; - - const now = new Date(); - const mockSession: ReadingSession = { - bookId: 42, - bookType: 'PDF' as BookType, - startTime: now, - startLocation: 'start-cfi', - startProgress: 10 - }; - - beforeEach(() => { - apiServiceMock = { - createSession: vi.fn().mockReturnValue(of(void 0)), - sendSessionBeacon: vi.fn().mockReturnValue(true) - }; - - TestBed.configureTestingModule({ - providers: [ - ReadingSessionService, - {provide: ReadingSessionApiService, useValue: apiServiceMock} - ] - }); - - const injector = TestBed.inject(EnvironmentInjector); - service = runInInjectionContext(injector, () => TestBed.inject(ReadingSessionService)); - }); - - it('should start a session', () => { - service.startSession(1, 'PDF', 'loc', 5); - expect(service.isSessionActive()).toBe(true); - }); - - it('should end a session and send to backend if duration is sufficient', () => { - vi.useFakeTimers(); - service.startSession(1, 'PDF', 'loc', 5); - // Simulate session duration > MIN_SESSION_DURATION_SECONDS - (service as any).currentSession!.startTime = new Date(Date.now() - 60000); - service.endSession('endloc', 10); - expect(apiServiceMock.createSession).toHaveBeenCalled(); - expect(service.isSessionActive()).toBe(false); - vi.useRealTimers(); - }); - - it('should discard session if duration is too short', () => { - vi.useFakeTimers(); - service.startSession(1, 'PDF', 'loc', 5); - (service as any).currentSession!.startTime = new Date(Date.now() - 10000); - service.endSession('endloc', 10); - expect(apiServiceMock.createSession).not.toHaveBeenCalled(); - expect(service.isSessionActive()).toBe(false); - vi.useRealTimers(); - }); - - it('should update progress', () => { - service.startSession(1, 'PDF', 'loc', 5); - service.updateProgress('newloc', 15); - const session = (service as any).currentSession; - expect(session.endLocation).toBe('newloc'); - expect(session.endProgress).toBe(15); - }); - - it('should end session synchronously with sendSessionBeacon', () => { - service.startSession(1, 'PDF', 'loc', 5); - (service as any).currentSession!.startTime = new Date(Date.now() - 60000); - service['endSessionSync'](); - expect(apiServiceMock.sendSessionBeacon).toHaveBeenCalled(); - expect(service.isSessionActive()).toBe(false); - }); - - it('should not send beacon if session duration is too short', () => { - service.startSession(1, 'PDF', 'loc', 5); - (service as any).currentSession!.startTime = new Date(Date.now() - 10000); - service['endSessionSync'](); - expect(apiServiceMock.sendSessionBeacon).not.toHaveBeenCalled(); - expect(service.isSessionActive()).toBe(false); - }); - - it('should return false for isSessionActive when no session', () => { - expect(service.isSessionActive()).toBe(false); - }); - - it('should build session data correctly', () => { - const endTime = new Date(now.getTime() + 60000); - const session: ReadingSession = { - bookId: 1, - bookType: 'PDF', - startTime: now, - endTime, - durationSeconds: 60, - startProgress: 10, - endProgress: 20, - progressDelta: 10, - startLocation: 'loc1', - endLocation: 'loc2' - }; - const dto = (service as any).buildSessionData(session, endTime, 60); - expect(dto.bookId).toBe(1); - expect(dto.bookType).toBe('PDF'); - expect(dto.durationSeconds).toBe(60); - expect(dto.startProgress).toBe(10); - expect(dto.endProgress).toBe(20); - expect(dto.progressDelta).toBe(10); - expect(dto.startLocation).toBe('loc1'); - expect(dto.endLocation).toBe('loc2'); - expect(typeof dto.startTime).toBe('string'); - expect(typeof dto.endTime).toBe('string'); - expect(dto.durationFormatted).toBe('1m 0s'); - }); - - it('should format duration correctly', () => { - expect((service as any).formatDuration(3661)).toBe('1h 1m 1s'); - expect((service as any).formatDuration(61)).toBe('1m 1s'); - expect((service as any).formatDuration(10)).toBe('10s'); - }); -}); - -describe('ReadingSessionService - API Contract Tests', () => { - let service: ReadingSessionService; - let apiServiceMock: any; - - beforeEach(() => { - apiServiceMock = { - createSession: vi.fn().mockReturnValue(of(void 0)), - sendSessionBeacon: vi.fn().mockReturnValue(true) - }; - - TestBed.configureTestingModule({ - providers: [ - ReadingSessionService, - {provide: ReadingSessionApiService, useValue: apiServiceMock} - ] - }); - - const injector = TestBed.inject(EnvironmentInjector); - service = runInInjectionContext(injector, () => TestBed.inject(ReadingSessionService)); - }); - - it('should call createSession with correct payload', () => { - const session: ReadingSession = { - bookId: 1, - bookType: 'PDF', - startTime: new Date(Date.now() - 60000), - endTime: new Date(), - durationSeconds: 60, - startProgress: 10, - endProgress: 20, - progressDelta: 10, - startLocation: 'loc1', - endLocation: 'loc2' - }; - (service as any).sendSessionToBackend(session); - expect(apiServiceMock.createSession).toHaveBeenCalledWith(expect.objectContaining({ - bookId: 1, - bookType: 'PDF', - durationSeconds: 60, - startProgress: 10, - endProgress: 20, - progressDelta: 10, - startLocation: 'loc1', - endLocation: 'loc2' - })); - }); - - it('should call sendSessionBeacon with correct payload', () => { - const session: ReadingSession = { - bookId: 2, - bookType: 'EPUB', - startTime: new Date(Date.now() - 120000), - startProgress: 0, - endProgress: 100, - progressDelta: 100, - startLocation: 'start', - endLocation: 'end' - }; - const endTime = new Date(); - const durationSeconds = 120; - const dto = (service as any).buildSessionData(session, endTime, durationSeconds); - (service as any).currentSession = session; - apiServiceMock.sendSessionBeacon.mockClear(); - (service as any).endSessionSync(); - expect(apiServiceMock.sendSessionBeacon).toHaveBeenCalledWith(expect.objectContaining({ - bookId: 2, - bookType: 'EPUB', - startLocation: 'start', - endLocation: 'end' - })); - }); - - it('should not call createSession if endTime or durationSeconds missing', () => { - const session: ReadingSession = { - bookId: 1, - bookType: 'PDF', - startTime: new Date() - // missing endTime and durationSeconds - }; - (service as any).sendSessionToBackend(session); - expect(apiServiceMock.createSession).not.toHaveBeenCalled(); - }); - - it('should not call sendSessionBeacon if duration too short', () => { - const session: ReadingSession = { - bookId: 1, - bookType: 'PDF', - startTime: new Date(Date.now() - 10000) - }; - (service as any).currentSession = session; - apiServiceMock.sendSessionBeacon.mockClear(); - (service as any).endSessionSync(); - expect(apiServiceMock.sendSessionBeacon).not.toHaveBeenCalled(); - }); - - it('should send correct types in CreateReadingSessionDto', () => { - const session: ReadingSession = { - bookId: 3, - bookType: 'CBX', - startTime: new Date(Date.now() - 180000), - endTime: new Date(), - durationSeconds: 180, - startProgress: 0, - endProgress: 50, - progressDelta: 50, - startLocation: 'foo', - endLocation: 'bar' - }; - const dto: CreateReadingSessionDto = (service as any).buildSessionData(session, session.endTime!, session.durationSeconds!); - expect(typeof dto.bookId).toBe('number'); - expect(typeof dto.bookType).toBe('string'); - expect(typeof dto.startTime).toBe('string'); - expect(typeof dto.endTime).toBe('string'); - expect(typeof dto.durationSeconds).toBe('number'); - expect(typeof dto.durationFormatted).toBe('string'); - expect(typeof dto.startProgress).toBe('number'); - expect(typeof dto.endProgress).toBe('number'); - expect(typeof dto.progressDelta).toBe('number'); - expect(typeof dto.startLocation).toBe('string'); - expect(typeof dto.endLocation).toBe('string'); - }); -}); - From 13a617a9e94c72c3c2925c3945669155624a0eb3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= <127139797+balazs-szucs@users.noreply.github.com> Date: Wed, 7 Jan 2026 22:16:12 +0100 Subject: [PATCH 20/40] feat(magic-shelf): add ISBN-10 and ISBN-13 metadata fields to book rules (#2196) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Balázs Szücs --- .../com/adityachandel/booklore/model/dto/RuleField.java | 4 ++++ .../booklore/service/BookRuleEvaluatorService.java | 2 ++ .../magic-shelf/component/magic-shelf-component.ts | 6 +++++- .../magic-shelf/service/book-rule-evaluator.service.ts | 8 ++++++++ 4 files changed, 19 insertions(+), 1 deletion(-) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/RuleField.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/RuleField.java index 6b7304db2..3c53f0b8b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/RuleField.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/RuleField.java @@ -27,6 +27,10 @@ public enum RuleField { PAGE_COUNT, @JsonProperty("language") LANGUAGE, + @JsonProperty("isbn13") + ISBN13, + @JsonProperty("isbn10") + ISBN10, @JsonProperty("amazonRating") AMAZON_RATING, @JsonProperty("amazonReviewCount") diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookRuleEvaluatorService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookRuleEvaluatorService.java index e1701d998..db08b7edc 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/BookRuleEvaluatorService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/BookRuleEvaluatorService.java @@ -324,6 +324,8 @@ public class BookRuleEvaluatorService { case SERIES_NAME -> root.get("metadata").get("seriesName"); case SERIES_NUMBER -> root.get("metadata").get("seriesNumber"); case SERIES_TOTAL -> root.get("metadata").get("seriesTotal"); + case ISBN13 -> root.get("metadata").get("isbn13"); + case ISBN10 -> root.get("metadata").get("isbn10"); case AMAZON_RATING -> root.get("metadata").get("amazonRating"); case AMAZON_REVIEW_COUNT -> root.get("metadata").get("amazonReviewCount"); case GOODREADS_RATING -> root.get("metadata").get("goodreadsRating"); diff --git a/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.ts b/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.ts index 975110edc..3b66215ff 100644 --- a/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.ts +++ b/booklore-ui/src/app/features/magic-shelf/component/magic-shelf-component.ts @@ -52,6 +52,8 @@ export type RuleField = | 'seriesTotal' | 'pageCount' | 'language' + | 'isbn13' + | 'isbn10' | 'amazonRating' | 'amazonReviewCount' | 'goodreadsRating' @@ -127,6 +129,8 @@ const FIELD_CONFIGS: Record = { personalRating: {label: 'Personal Rating', type: 'decimal', max: 10}, pageCount: {label: 'Page Count', type: 'number'}, language: {label: 'Language'}, + isbn13: {label: 'ISBN-13'}, + isbn10: {label: 'ISBN-10'}, seriesName: {label: 'Series Name'}, seriesNumber: {label: 'Series Number', type: 'number'}, seriesTotal: {label: 'Books in Series', type: 'number'}, @@ -349,7 +353,7 @@ export class MagicShelfComponent implements OnInit { if (!field) return [...baseOperators, ...multiValueOperators]; const config = FIELD_CONFIGS[field]; - const isMultiValueField = ['library', 'authors', 'categories', 'moods', 'tags', 'readStatus', 'fileType', 'language', 'title', 'subtitle', 'publisher', 'seriesName'].includes(field); + const isMultiValueField = ['library', 'authors', 'categories', 'moods', 'tags', 'readStatus', 'fileType', 'language', 'title', 'subtitle', 'publisher', 'seriesName', 'isbn13', 'isbn10'].includes(field); const operators = [...baseOperators]; if (isMultiValueField) { diff --git a/booklore-ui/src/app/features/magic-shelf/service/book-rule-evaluator.service.ts b/booklore-ui/src/app/features/magic-shelf/service/book-rule-evaluator.service.ts index de78c05dd..9b5dbaae1 100644 --- a/booklore-ui/src/app/features/magic-shelf/service/book-rule-evaluator.service.ts +++ b/booklore-ui/src/app/features/magic-shelf/service/book-rule-evaluator.service.ts @@ -61,6 +61,10 @@ export class BookRuleEvaluatorService { return [String(book.metadata?.publisher ?? '').toLowerCase()]; case 'seriesName': return [String(book.metadata?.seriesName ?? '').toLowerCase()]; + case 'isbn13': + return [String(book.metadata?.isbn13 ?? '').toLowerCase()]; + case 'isbn10': + return [String(book.metadata?.isbn10 ?? '').toLowerCase()]; default: return []; } @@ -232,6 +236,10 @@ export class BookRuleEvaluatorService { return book.metadata?.pageCount; case 'language': return book.metadata?.language?.toLowerCase() ?? null; + case 'isbn13': + return book.metadata?.isbn13?.toLowerCase() ?? null; + case 'isbn10': + return book.metadata?.isbn10?.toLowerCase() ?? null; case 'amazonRating': return book.metadata?.amazonRating; case 'amazonReviewCount': From 251fe65ec03466502b3c546ad643d827279fad10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= <127139797+balazs-szucs@users.noreply.github.com> Date: Wed, 7 Jan 2026 22:16:57 +0100 Subject: [PATCH 21/40] fix(parser): handle missing results table in GoodReads search and log a warning (#2187) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Balázs Szücs --- .../service/metadata/parser/GoodReadsParser.java | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) 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 8e3ba5b99..1baad5322 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 @@ -478,10 +478,15 @@ public class GoodReadsParser implements BookParser { try { String searchUrl = generateSearchUrl(searchTerm); - Elements previewBooks = fetchDoc(searchUrl) - .select("table.tableList") - .first() - .select("tr[itemtype=http://schema.org/Book]"); + Document doc = fetchDoc(searchUrl); + Element tableList = doc.select("table.tableList").first(); + + if (tableList == null) { + log.warn("GoodReads: No results table found for search term: {}", searchTerm); + return Collections.emptyList(); + } + + Elements previewBooks = tableList.select("tr[itemtype=http://schema.org/Book]"); List metadataPreviews = new ArrayList<>(); FuzzyScore fuzzyScore = new FuzzyScore(Locale.ENGLISH); From c17fe58f4c9f9e59c48ff7a6c9a4e52707732f3e Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Wed, 7 Jan 2026 18:10:53 -0700 Subject: [PATCH 22/40] Show a persistent loader while a large library is being created (#2200) Co-authored-by: acx10 --- .../controller/LibraryController.java | 23 ++- .../booklore/model/enums/BookFileType.java | 30 +++- .../service/fileprocessor/CbxProcessor.java | 30 ++-- .../service/library/LibraryService.java | 57 ++++++- .../booklore/util/FileUtils.java | 11 ++ booklore-ui/src/app/app.component.ts | 35 +++- .../features/book/service/library.service.ts | 15 ++ .../library-creator.component.ts | 63 +++++--- .../library-loading.service.ts | 47 ++++++ .../library-loading.component.html | 50 ++++++ .../library-loading.component.scss | 151 ++++++++++++++++++ .../library-loading.component.ts | 39 +++++ .../directory-picker.component.html | 2 +- .../directory-picker.component.scss | 52 +++++- .../directory-picker.component.ts | 34 ++-- .../service/file-download.service.spec.ts | 30 +--- .../shared/service/file-download.service.ts | 9 +- 17 files changed, 567 insertions(+), 111 deletions(-) create mode 100644 booklore-ui/src/app/features/library-creator/library-loading.service.ts create mode 100644 booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.html create mode 100644 booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.scss create mode 100644 booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.ts diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java index ab2d44260..bdc994606 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/LibraryController.java @@ -41,8 +41,7 @@ public class LibraryController { }) @GetMapping("/{libraryId}") @CheckLibraryAccess(libraryIdParam = "libraryId") - public ResponseEntity getLibrary( - @Parameter(description = "ID of the library") @PathVariable long libraryId) { + public ResponseEntity getLibrary(@Parameter(description = "ID of the library") @PathVariable long libraryId) { return ResponseEntity.ok(libraryService.getLibrary(libraryId)); } @@ -50,8 +49,7 @@ public class LibraryController { @ApiResponse(responseCode = "200", description = "Library created successfully") @PostMapping @PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()") - public ResponseEntity createLibrary( - @Parameter(description = "Library creation request") @Validated @RequestBody CreateLibraryRequest request) { + public ResponseEntity createLibrary(@Parameter(description = "Library creation request") @Validated @RequestBody CreateLibraryRequest request) { return ResponseEntity.ok(libraryService.createLibrary(request)); } @@ -71,8 +69,7 @@ public class LibraryController { @DeleteMapping("/{libraryId}") @CheckLibraryAccess(libraryIdParam = "libraryId") @PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()") - public ResponseEntity deleteLibrary( - @Parameter(description = "ID of the library") @PathVariable long libraryId) { + public ResponseEntity deleteLibrary(@Parameter(description = "ID of the library") @PathVariable long libraryId) { libraryService.deleteLibrary(libraryId); return ResponseEntity.noContent().build(); } @@ -91,8 +88,7 @@ public class LibraryController { @ApiResponse(responseCode = "200", description = "Books returned successfully") @GetMapping("/{libraryId}/book") @CheckLibraryAccess(libraryIdParam = "libraryId") - public ResponseEntity> getBooks( - @Parameter(description = "ID of the library") @PathVariable long libraryId) { + public ResponseEntity> getBooks(@Parameter(description = "ID of the library") @PathVariable long libraryId) { List books = libraryService.getBooks(libraryId); return ResponseEntity.ok(books); } @@ -119,4 +115,15 @@ public class LibraryController { Library updated = libraryService.setFileNamingPattern(libraryId, pattern); return ResponseEntity.ok(updated); } + + @Operation(summary = "Scan library paths", description = "Scan the provided library paths and return a count of processable files. Requires admin or manipulation permission.") + @ApiResponse(responseCode = "200", description = "Processable files count returned successfully") + @PostMapping("/scan") + @PreAuthorize("@securityUtil.canManageLibrary() or @securityUtil.isAdmin()") + public ResponseEntity scanLibraryPaths( + @Parameter(description = "Library creation request with paths to scan") + @Validated @RequestBody CreateLibraryRequest request) { + int processableFilesCount = libraryService.scanLibraryPaths(request); + return ResponseEntity.ok(processableFilesCount); + } } \ No newline at end of file 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 21a9c9a2e..b19b6749e 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 @@ -1,5 +1,33 @@ package com.adityachandel.booklore.model.enums; +import lombok.Getter; + +import java.util.Arrays; +import java.util.Optional; +import java.util.Set; + +@Getter public enum BookFileType { - PDF, EPUB, CBX, FB2 + + PDF(Set.of("pdf")), + EPUB(Set.of("epub")), + CBX(Set.of("cbz", "cbr", "cb7")), + FB2(Set.of("fb2")); + + private final Set extensions; + + BookFileType(Set extensions) { + this.extensions = extensions; + } + + public boolean supports(String extension) { + return extensions.contains(extension.toLowerCase()); + } + + public static Optional fromExtension(String extension) { + String ext = extension.toLowerCase(); + return Arrays.stream(values()) + .filter(type -> type.supports(ext)) + .findFirst(); + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java index 2f4b6f9ac..75ac24c27 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java @@ -42,7 +42,6 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce private static final Pattern UNDERSCORE_HYPHEN_PATTERN = Pattern.compile("[_\\-]"); private static final Pattern IMAGE_EXTENSION_PATTERN = Pattern.compile(".*\\.(jpg|jpeg|png|webp)"); private static final Pattern IMAGE_EXTENSION_CASE_INSENSITIVE_PATTERN = Pattern.compile("(?i).*\\.(jpg|jpeg|png|webp)"); - private static final Pattern CBX_FILE_EXTENSION_PATTERN = Pattern.compile("(?i)\\.cb[rz7]$"); private final CbxMetadataExtractor cbxMetadataExtractor; public CbxProcessor(BookRepository bookRepository, @@ -99,17 +98,20 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce } private Optional extractImagesFromArchive(File file) { - String name = file.getName().toLowerCase(); - if (name.endsWith(".cbz")) { - return extractFirstImageFromZip(file); - } else if (name.endsWith(".cb7")) { - return extractFirstImageFrom7z(file); - } else if (name.endsWith(".cbr")) { - return extractFirstImageFromRar(file); - } else { + String name = file.getName(); + String extension = FileUtils.getExtension(name).toLowerCase(); + + if (!BookFileType.CBX.supports(extension)) { log.warn("Unsupported CBX format: {}", name); return Optional.empty(); } + + return switch (extension) { + case "cbz" -> extractFirstImageFromZip(file); + case "cb7" -> extractFirstImageFrom7z(file); + case "cbr" -> extractFirstImageFromRar(file); + default -> Optional.empty(); + }; } private Optional extractFirstImageFromZip(File file) { @@ -242,8 +244,12 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce private void setMetadata(BookEntity bookEntity) { String baseName = new File(bookEntity.getFileName()).getName(); - String title = UNDERSCORE_HYPHEN_PATTERN.matcher(CBX_FILE_EXTENSION_PATTERN.matcher(baseName).replaceAll("")).replaceAll(" ") - .trim(); + String extension = FileUtils.getExtension(baseName); + if (BookFileType.CBX.supports(extension)) { + baseName = baseName.substring(0, baseName.length() - extension.length() - 1); + } + String title = UNDERSCORE_HYPHEN_PATTERN.matcher(baseName).replaceAll(" ").trim(); bookEntity.getMetadata().setTitle(truncate(title, 1000)); } -} \ No newline at end of file +} + 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 3099c376b..0dad29efb 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 @@ -13,6 +13,7 @@ import com.adityachandel.booklore.model.entity.BookEntity; 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; @@ -33,9 +34,14 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.io.IOException; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.*; +import java.util.Collections; +import java.util.List; +import java.util.Optional; +import java.util.Set; import java.util.stream.Collectors; @Slf4j @@ -250,4 +256,51 @@ public class LibraryService { library.setFileNamingPattern(pattern); return libraryMapper.toLibrary(libraryRepository.save(library)); } -} \ No newline at end of file + + public int scanLibraryPaths(CreateLibraryRequest request) { + int count = 0; + if (request.getPaths() == null || request.getPaths().isEmpty()) { + return count; + } + for (LibraryPath libraryPath : request.getPaths()) { + Path path = Paths.get(libraryPath.getPath()); + if (!Files.exists(path)) { + log.warn("Path does not exist: {}", path); + continue; + } + if (Files.isDirectory(path)) { + count += scanDirectory(path); + } else if (Files.isRegularFile(path) && isProcessableFile(path)) { + count++; + } + } + return count; + } + + private int scanDirectory(Path directory) { + int count = 0; + try (DirectoryStream stream = Files.newDirectoryStream(directory)) { + for (Path entry : stream) { + if (Files.isDirectory(entry)) { + count += scanDirectory(entry); + } else if (Files.isRegularFile(entry) && isProcessableFile(entry)) { + count++; + } + } + } catch (IOException e) { + log.error("Error scanning directory: {}", directory, e); + } + return count; + } + + private boolean isProcessableFile(Path file) { + String fileName = file.getFileName().toString().toLowerCase(); + for (BookFileType fileType : BookFileType.values()) { + if (fileName.endsWith("." + fileType.name().toLowerCase())) { + return true; + } + } + return false; + } +} + 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 7cfb37ee0..eebb54bc2 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 @@ -63,6 +63,17 @@ public class FileUtils { } } + public String getExtension(String fileName) { + if (fileName == null) { + return ""; + } + int i = fileName.lastIndexOf('.'); + if (i >= 0 && i < fileName.length() - 1) { + return fileName.substring(i + 1); + } + return ""; + } + private List systemDirs = Arrays.asList( // synology "#recycle", diff --git a/booklore-ui/src/app/app.component.ts b/booklore-ui/src/app/app.component.ts index bfb4c60d4..32871b47e 100644 --- a/booklore-ui/src/app/app.component.ts +++ b/booklore-ui/src/app/app.component.ts @@ -13,7 +13,10 @@ import {MetadataProgressService} from './shared/service/metadata-progress.servic import {BookdropFileNotification, BookdropFileService} from './features/bookdrop/service/bookdrop-file.service'; import {Subscription} from 'rxjs'; import {DownloadProgressDialogComponent} from './shared/components/download-progress-dialog/download-progress-dialog.component'; -import {TaskService, TaskProgressPayload} from './features/settings/task-management/task.service'; +import {TaskProgressPayload, TaskService} from './features/settings/task-management/task.service'; +import {LibraryService} from './features/book/service/library.service'; +import {LibraryLoadingService} from './features/library-creator/library-loading.service'; +import {scan, withLatestFrom} from 'rxjs/operators'; @Component({ selector: 'app-root', @@ -26,7 +29,9 @@ export class AppComponent implements OnInit, OnDestroy { loading = true; private subscriptions: Subscription[] = []; - private subscriptionsInitialized = false; // Prevent multiple subscription setups + private subscriptionsInitialized = false; + + private appConfigService = inject(AppConfigService); // DO NOT REMOVE: Used to initialize app config on startup private authInit = inject(AuthInitializationService); private bookService = inject(BookService); private rxStompService = inject(RxStompService); @@ -34,7 +39,8 @@ export class AppComponent implements OnInit, OnDestroy { private metadataProgressService = inject(MetadataProgressService); private bookdropFileService = inject(BookdropFileService); private taskService = inject(TaskService); - private appConfigService = inject(AppConfigService); // Keep it here to ensure the service is initialized + private libraryService = inject(LibraryService); + private libraryLoadingService = inject(LibraryLoadingService); ngOnInit(): void { this.authInit.initialized$.subscribe(ready => { @@ -48,9 +54,25 @@ export class AppComponent implements OnInit, OnDestroy { private setupWebSocketSubscriptions(): void { this.subscriptions.push( - this.rxStompService.watch('/user/queue/book-add').subscribe(msg => - this.bookService.handleNewlyCreatedBook(JSON.parse(msg.body)) - ) + this.rxStompService.watch('/user/queue/book-add').pipe( + withLatestFrom(this.libraryService.largeLibraryLoading$), + scan((acc, [msg, loadingState]) => { + const book = JSON.parse(msg.body); + if (loadingState.isLoading) { + const newCount = acc.count + 1; + this.libraryLoadingService.showBookLoadingProgress(book.metadata?.title || 'Unknown Book', newCount, loadingState.expectedCount); + this.bookService.handleNewlyCreatedBook(book); + if (newCount >= loadingState.expectedCount) { + this.libraryService.setLargeLibraryLoading(false, 0); + return {count: 0}; + } + return {count: newCount}; + } else { + this.bookService.handleNewlyCreatedBook(book); + return {count: 0}; + } + }, {count: 0}) + ).subscribe() ); this.subscriptions.push( this.rxStompService.watch('/user/queue/book-update').subscribe(msg => @@ -104,5 +126,6 @@ export class AppComponent implements OnInit, OnDestroy { ngOnDestroy(): void { this.subscriptions.forEach(sub => sub.unsubscribe()); + this.libraryLoadingService.hide(); } } diff --git a/booklore-ui/src/app/features/book/service/library.service.ts b/booklore-ui/src/app/features/book/service/library.service.ts index 55e03da89..679b37f45 100644 --- a/booklore-ui/src/app/features/book/service/library.service.ts +++ b/booklore-ui/src/app/features/book/service/library.service.ts @@ -22,6 +22,13 @@ export class LibraryService { error: null, }); + private largeLibraryLoadingSubject = new BehaviorSubject<{ isLoading: boolean; expectedCount: number }>({ + isLoading: false, + expectedCount: 0 + }); + + largeLibraryLoading$ = this.largeLibraryLoadingSubject.asObservable(); + private loading$: Observable | null = null; constructor() { @@ -72,6 +79,10 @@ export class LibraryService { ); } + scanLibraryPaths(lib: Library): Observable { + return this.http.post(`${this.url}/scan`, lib); + } + createLibrary(lib: Library): Observable { return this.http.post(this.url, lib).pipe( map(created => { @@ -150,4 +161,8 @@ export class LibraryService { map(state => (state.books || []).filter(b => b.libraryId === libraryId).length) ); } + + setLargeLibraryLoading(isLoading: boolean, expectedCount: number): void { + this.largeLibraryLoadingSubject.next({ isLoading, expectedCount }); + } } 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 46d240ffa..b260b3f5a 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 @@ -15,6 +15,8 @@ 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'; @Component({ selector: 'app-library-creator', @@ -147,16 +149,17 @@ export class LibraryCreatorComponent implements OnInit { const iconValue = this.selectedIcon?.value || 'heart'; const iconType = this.selectedIcon?.type || 'PRIME_NG'; + const library: Library = { + name: this.chosenLibraryName, + icon: iconValue, + iconType: iconType, + paths: this.folders.map(folder => ({path: folder})), + watch: this.watch, + scanMode: this.scanMode, + defaultBookFormat: this.defaultBookFormat + }; + if (this.mode === 'edit') { - const library: Library = { - name: this.chosenLibraryName, - icon: iconValue, - iconType: iconType, - paths: this.folders.map(folder => ({path: folder})), - watch: this.watch, - scanMode: this.scanMode, - defaultBookFormat: this.defaultBookFormat - }; this.libraryService.updateLibrary(library, this.library?.id).subscribe({ next: () => { this.messageService.add({severity: 'success', summary: 'Library Updated', detail: 'The library was updated successfully.'}); @@ -168,22 +171,36 @@ export class LibraryCreatorComponent implements OnInit { } }); } else { - const library: Library = { - name: this.chosenLibraryName, - icon: iconValue, - iconType: iconType, - paths: this.folders.map(folder => ({path: folder})), - watch: this.watch, - scanMode: this.scanMode, - defaultBookFormat: this.defaultBookFormat - }; - this.libraryService.createLibrary(library).subscribe({ - next: (createdLibrary) => { - this.router.navigate(['/library', createdLibrary.id, 'books']); - this.messageService.add({severity: 'success', summary: 'Library Created', detail: 'The library was created successfully.'}); - this.dynamicDialogRef.close(); + this.libraryService.scanLibraryPaths(library).pipe( + switchMap(count => { + if (count < 500) { + return this.libraryService.createLibrary(library).pipe( + map(createdLibrary => ({ createdLibrary, count })) + ); + } else { + console.warn(`Library has ${count} processable files (>500). Will use buffered loading.`); + this.libraryService.setLargeLibraryLoading(true, count); + return this.libraryService.createLibrary(library).pipe( + map(createdLibrary => ({ createdLibrary, count })) + ); + } + }) + ).subscribe({ + next: ({ createdLibrary, count }) => { + if (createdLibrary) { + this.router.navigate(['/library', createdLibrary.id, 'books']); + this.messageService.add({ + severity: 'success', + summary: 'Library Created', + detail: count >= 500 + ? `Library created with ${count} files. Loading in progress...` + : 'The library was created successfully.' + }); + this.dynamicDialogRef.close(); + } }, error: (e) => { + this.libraryService.setLargeLibraryLoading(false, 0); this.messageService.add({severity: 'error', summary: 'Creation Failed', detail: 'An error occurred while creating the library. Please try again.'}); console.error(e); } diff --git a/booklore-ui/src/app/features/library-creator/library-loading.service.ts b/booklore-ui/src/app/features/library-creator/library-loading.service.ts new file mode 100644 index 000000000..765a11170 --- /dev/null +++ b/booklore-ui/src/app/features/library-creator/library-loading.service.ts @@ -0,0 +1,47 @@ +import { Injectable, ComponentRef, ApplicationRef, createComponent, EnvironmentInjector } from '@angular/core'; +import { LibraryLoadingComponent } from './library-loading/library-loading.component'; + +@Injectable({ + providedIn: 'root' +}) +export class LibraryLoadingService { + private componentRef: ComponentRef | null = null; + + constructor( + private appRef: ApplicationRef, + private injector: EnvironmentInjector + ) {} + + showBookLoadingProgress(bookTitle: string, current: number, total: number): void { + if (this.componentRef) { + this.updateProgress(bookTitle, current, total); + return; + } + + this.componentRef = createComponent(LibraryLoadingComponent, { + environmentInjector: this.injector + }); + + this.componentRef.instance.updateProgress(bookTitle, current, total); + + this.appRef.attachView(this.componentRef.hostView); + const domElem = (this.componentRef.hostView as any).rootNodes[0] as HTMLElement; + document.body.appendChild(domElem); + document.body.style.overflow = 'hidden'; + } + + updateProgress(bookTitle: string, current: number, total: number): void { + if (this.componentRef) { + this.componentRef.instance.updateProgress(bookTitle, current, total); + } + } + + hide(): void { + if (this.componentRef) { + this.appRef.detachView(this.componentRef.hostView); + this.componentRef.destroy(); + this.componentRef = null; + document.body.style.overflow = ''; + } + } +} diff --git a/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.html b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.html new file mode 100644 index 000000000..1f552bf46 --- /dev/null +++ b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.html @@ -0,0 +1,50 @@ +
+
+
+ +

Loading Library

+
+ +
+
+ @if (!isComplete) { + + Processing: {{ truncatedTitle }} + + } + @if (isComplete) { + + + Library Loading Complete! + + } +
+ +
+ {{ current }} / {{ total }} + {{ percentage }}% +
+ +
+
+
+ + @if (!isComplete) { +
+
+
+
+
+ } +
+ + @if (isComplete) { + + } +
+
diff --git a/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.scss b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.scss new file mode 100644 index 000000000..e70294568 --- /dev/null +++ b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.scss @@ -0,0 +1,151 @@ +.fullscreen-loader { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: rgba(0, 0, 0, 0.85); + backdrop-filter: blur(8px); + display: flex; + justify-content: center; + align-items: center; + z-index: 9999; +} + +.library-loader-content { + background: var(--card-background); + padding: 2.5rem; + border-radius: 12px; + width: 550px; + max-width: 90vw; + box-sizing: border-box; + border: 1px solid var(--border-color); +} + +.library-loader-header { + text-align: center; + + i { + font-size: 3rem; + color: var(--primary-color); + margin-bottom: 1rem; + } + + h2 { + margin: 0 0 0.5rem 0; + color: var(--text-color); + font-size: 1.5rem; + } +} + +.library-loader-body { + .book-title { + color: var(--text-color-secondary); + margin-bottom: 1.5rem; + margin-top: 2.5rem; + font-size: 0.95rem; + word-break: break-word; + overflow-wrap: break-word; + line-height: 1.4; + display: flex; + align-items: flex-start; + + strong { + color: var(--text-color); + } + + .complete-message { + color: var(--primary-color); + font-size: 1.1rem; + + i { + margin-right: 0.5rem; + } + } + } + + .progress-info { + display: flex; + justify-content: space-between; + margin-bottom: 0.5rem; + color: var(--text-color-secondary); + font-size: 0.9rem; + } + + .progress-bar-container { + width: 100%; + height: 8px; + background: var(--card-background); + border-radius: 4px; + overflow: hidden; + + .progress-bar-fill { + height: 100%; + background: var(--primary-color); + transition: width 0.3s ease; + } + } + + .loader-animation { + margin-top: 1.5rem; + display: flex; + justify-content: center; + gap: 0.5rem; + + .dot { + width: 8px; + height: 8px; + background: var(--primary-color); + border-radius: 50%; + animation: bounce 1.4s infinite ease-in-out both; + + &:nth-child(2) { + animation-delay: 0.2s; + } + + &:nth-child(3) { + animation-delay: 0.4s; + } + } + } +} + +.library-loader-footer { + margin-top: 3rem; + text-align: center; + + .reload-button { + padding: 0.75rem 1.25rem; + background: var(--primary-color); + color: white; + border: none; + border-radius: 6px; + font-size: 1rem; + cursor: pointer; + transition: all 0.3s ease; + font-weight: 700; + + i { + margin-right: 0.5rem; + } + + &:hover { + background: var(--primary-hover-color); + transform: translateY(-2px); + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); + } + + &:active { + transform: translateY(0); + } + } +} + +@keyframes bounce { + 0%, 80%, 100% { + transform: scale(0); + } + 40% { + transform: scale(1); + } +} diff --git a/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.ts b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.ts new file mode 100644 index 000000000..fcaf5fb62 --- /dev/null +++ b/booklore-ui/src/app/features/library-creator/library-loading/library-loading.component.ts @@ -0,0 +1,39 @@ +import { Component } from '@angular/core'; +import { CommonModule } from '@angular/common'; + +@Component({ + selector: 'app-library-loading', + standalone: true, + imports: [CommonModule], + templateUrl: './library-loading.component.html', + styleUrl: './library-loading.component.scss' +}) +export class LibraryLoadingComponent { + bookTitle = ''; + current = 0; + total = 0; + isComplete = false; + + get percentage(): number { + return this.total > 0 ? Math.round((this.current / this.total) * 100) : 0; + } + + get truncatedTitle(): string { + const maxLength = 50; + return this.bookTitle.length <= maxLength + ? this.bookTitle + : this.bookTitle.substring(0, maxLength) + '...'; + } + + updateProgress(bookTitle: string, current: number, total: number): void { + this.bookTitle = bookTitle; + this.current = current; + this.total = total; + this.isComplete = current >= total; + } + + onReload(): void { + window.location.reload(); + } +} + diff --git a/booklore-ui/src/app/shared/components/directory-picker/directory-picker.component.html b/booklore-ui/src/app/shared/components/directory-picker/directory-picker.component.html index 5ee941490..2acf4b9a6 100644 --- a/booklore-ui/src/app/shared/components/directory-picker/directory-picker.component.html +++ b/booklore-ui/src/app/shared/components/directory-picker/directory-picker.component.html @@ -91,7 +91,7 @@
-
+
@for (folder of filteredPaths; track folder) {
{ - this.paths = folders; - this.filteredPaths = folders; - this.isLoading = false; - this.updateBreadcrumb(path); - folders.forEach(folder => { - this.selectedFoldersMap[folder] = this.selectedFolders.includes(folder); - }); + setTimeout(() => { + this.paths = folders; + this.filteredPaths = folders; + this.isLoading = false; + this.updateBreadcrumb(path); + folders.forEach(folder => { + this.selectedFoldersMap[folder] = this.selectedFolders.includes(folder); + }); + }, 100); }, error: (error) => { console.error('Error fetching folders:', error); @@ -104,21 +107,6 @@ export class DirectoryPickerComponent implements OnInit { this.searchQuery = ''; } - toggleFolderSelection(path: string, event?: Event): void { - if (event) { - event.stopPropagation(); - } - - const index = this.selectedFolders.indexOf(path); - if (index > -1) { - this.selectedFolders.splice(index, 1); - this.selectedFoldersMap[path] = false; - } else { - this.selectedFolders.push(path); - this.selectedFoldersMap[path] = true; - } - } - onCheckboxChange(path: string, checked: boolean): void { const index = this.selectedFolders.indexOf(path); if (checked && index === -1) { diff --git a/booklore-ui/src/app/shared/service/file-download.service.spec.ts b/booklore-ui/src/app/shared/service/file-download.service.spec.ts index dfc8a25e4..baeaea561 100644 --- a/booklore-ui/src/app/shared/service/file-download.service.spec.ts +++ b/booklore-ui/src/app/shared/service/file-download.service.spec.ts @@ -2,7 +2,7 @@ import {beforeEach, describe, expect, it, vi} from 'vitest'; import {TestBed} from '@angular/core/testing'; import {EnvironmentInjector, runInInjectionContext} from '@angular/core'; import {HttpClient, HttpEventType, HttpHeaders, HttpResponse} from '@angular/common/http'; -import {of, Subject, throwError} from 'rxjs'; +import {of, Subject} from 'rxjs'; import {FileDownloadService} from './file-download.service'; import {DownloadProgressService} from './download-progress.service'; import {MessageService} from 'primeng/api'; @@ -75,7 +75,7 @@ describe('FileDownloadService', () => { } }; - service.downloadFile('/api/file', 'file.txt').subscribe(); + service.downloadFile('/api/file', 'file.txt'); expect(httpClientMock.get).toHaveBeenCalledWith('/api/file', expect.objectContaining({observe: 'events'})); expect(downloadProgressServiceMock.startDownload).toHaveBeenCalledWith('file.txt', expect.any(Subject)); expect(downloadProgressServiceMock.updateProgress).toHaveBeenCalledWith(50, 100); @@ -97,26 +97,6 @@ describe('FileDownloadService', () => { expect(filename).toBe('default.txt'); }); - it('should handle download error and show error message', () => { - httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); - service.downloadFile('/api/file', 'file.txt').subscribe({ - error: () => { - expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); - expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled(); - } - }); - }); - - it('should not show error message for AbortError', () => { - httpClientMock.get.mockReturnValue(throwError(() => ({name: 'AbortError'}))); - service.downloadFile('/api/file', 'file.txt').subscribe({ - error: () => { - expect(messageServiceMock.add).not.toHaveBeenCalledWith(expect.objectContaining({severity: 'error'})); - expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled(); - } - }); - }); - it('should throw if no file content received', () => { const response = new HttpResponse({body: undefined, headers: new HttpHeaders()}); expect(() => (service as any).handleDownloadComplete(response, 'file.txt')).toThrow('No file content received'); @@ -194,20 +174,20 @@ describe('FileDownloadService - API Contract Tests', () => { describe('Behavior contract', () => { it('should call startDownload and updateProgress on DownloadProgressService', () => { httpClientMock.get.mockReturnValue(of({type: HttpEventType.DownloadProgress, loaded: 10, total: 20})); - service.downloadFile('/api/file', 'file.txt').subscribe(); + service.downloadFile('/api/file', 'file.txt'); expect(downloadProgressServiceMock.startDownload).toHaveBeenCalled(); expect(downloadProgressServiceMock.updateProgress).toHaveBeenCalledWith(10, 20); }); it('should call completeDownload on finalize', () => { httpClientMock.get.mockReturnValue(of({type: HttpEventType.Response, body: new Blob(['test']), headers: new HttpHeaders(), clone: () => this, status: 200, statusText: 'OK', url: '', ok: true})); - service.downloadFile('/api/file', 'file.txt').subscribe(); + service.downloadFile('/api/file', 'file.txt'); expect(downloadProgressServiceMock.completeDownload).toHaveBeenCalled(); }); it('should show success message on download complete', () => { httpClientMock.get.mockReturnValue(of({type: HttpEventType.Response, body: new Blob(['test']), headers: new HttpHeaders(), clone: () => this, status: 200, statusText: 'OK', url: '', ok: true})); - service.downloadFile('/api/file', 'file.txt').subscribe(); + service.downloadFile('/api/file', 'file.txt'); expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({severity: 'success'})); }); }); diff --git a/booklore-ui/src/app/shared/service/file-download.service.ts b/booklore-ui/src/app/shared/service/file-download.service.ts index 96be67a83..75206846a 100644 --- a/booklore-ui/src/app/shared/service/file-download.service.ts +++ b/booklore-ui/src/app/shared/service/file-download.service.ts @@ -1,4 +1,4 @@ -import {Injectable, inject} from '@angular/core'; +import {inject, Injectable} from '@angular/core'; import {HttpClient, HttpEvent, HttpEventType, HttpResponse} from '@angular/common/http'; import {MessageService} from 'primeng/api'; import {DownloadProgressService} from './download-progress.service'; @@ -13,10 +13,10 @@ export class FileDownloadService { private downloadProgressService = inject(DownloadProgressService); private messageService = inject(MessageService); - downloadFile(url: string, defaultFilename: string): Observable { + downloadFile(url: string, defaultFilename: string): void { const cancelSubject = new Subject(); - return this.initiateDownload(url) + this.initiateDownload(url) .pipe( takeUntil(cancelSubject), tap(event => this.handleDownloadProgress(event, defaultFilename, cancelSubject)), @@ -25,7 +25,8 @@ export class FileDownloadService { this.handleDownloadError(error); return throwError(() => error); }) - ); + ) + .subscribe(); } private initiateDownload(url: string): Observable> { From f0444df6eed0dec1b5c20a491918f1a030a28ae1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= <127139797+balazs-szucs@users.noreply.github.com> Date: Thu, 8 Jan 2026 02:12:12 +0100 Subject: [PATCH 23/40] refactor(images): migrate to TwelveMonkeys ImageIO with graceful unsupported format handling (#2188) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Balázs Szücs Co-authored-by: ACX <8075870+acx10@users.noreply.github.com> --- booklore-api/build.gradle | 9 ++- .../model/dto/kobo/KoboBookMetadata.java | 1 + .../service/file/BackgroundUploadService.java | 16 +++- .../service/fileprocessor/CbxProcessor.java | 6 +- .../service/fileprocessor/EpubProcessor.java | 4 +- .../service/fileprocessor/Fb2Processor.java | 13 ++-- .../service/kobo/CbxConversionService.java | 13 +++- .../service/reader/CbxReaderService.java | 2 +- .../booklore/util/FileService.java | 52 +++++++++---- .../booklore/util/FileServiceTest.java | 78 +++++++++++++------ 10 files changed, 134 insertions(+), 60 deletions(-) diff --git a/booklore-api/build.gradle b/booklore-api/build.gradle index 69fa19505..474f9d92b 100644 --- a/booklore-api/build.gradle +++ b/booklore-api/build.gradle @@ -58,8 +58,13 @@ dependencies { implementation 'org.apache.pdfbox:pdfbox-io:3.0.6' implementation 'org.apache.pdfbox:xmpbox:3.0.6' implementation 'org.apache.pdfbox:jbig2-imageio:3.0.4' - implementation 'com.github.jai-imageio:jai-imageio-core:1.4.0' - implementation 'com.github.jai-imageio:jai-imageio-jpeg2000:1.4.0' + + // --- TwelveMonkeys ImageIO --- + implementation 'com.twelvemonkeys.imageio:imageio-jpeg:3.13.0' + implementation 'com.twelvemonkeys.imageio:imageio-tiff:3.13.0' + implementation 'com.twelvemonkeys.imageio:imageio-webp:3.13.0' + implementation 'com.twelvemonkeys.imageio:imageio-bmp:3.13.0' + implementation 'io.documentnode:epub4j-core:4.2.2' // --- UNRAR Support --- diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java index 1d560f645..f3e5f5436 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/kobo/KoboBookMetadata.java @@ -28,6 +28,7 @@ public class KoboBookMetadata { private String language = "en"; private String isbn; + @Builder.Default private String genre = "00000000-0000-0000-0000-000000000001"; private String slug; private String coverImageId; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java index 8a0cb53e2..b61f19e01 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java @@ -9,12 +9,15 @@ import org.springframework.web.multipart.MultipartFile; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; +import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.nio.file.Paths; import java.util.Objects; +import static net.lingala.zip4j.util.FileUtils.getFileExtension; + @Slf4j @Service @RequiredArgsConstructor @@ -34,20 +37,26 @@ public class BackgroundUploadService { String extension = getFileExtension(originalFilename); String filename = "1." + extension; + try (InputStream inputStream = file.getInputStream()) { BufferedImage originalImage; - try (InputStream inputStream = file.getInputStream()) { - originalImage = ImageIO.read(inputStream); + try { + originalImage = FileService.readImage(inputStream); + } catch (IOException e) { + originalImage = null; } + if (originalImage == null) { throw new IllegalArgumentException("Invalid image file"); } + deleteExistingBackgroundFiles(userId); fileService.saveBackgroundImage(originalImage, filename, userId); originalImage.flush(); // Release resources after saving String fileUrl = FileService.getBackgroundUrl(filename, userId); return new UploadResponse(fileUrl); + } } catch (Exception e) { log.error("Failed to upload background file: {}", e.getMessage(), e); throw new RuntimeException("Failed to upload file: " + e.getMessage(), e); @@ -62,6 +71,9 @@ public class BackgroundUploadService { String filename = "1." + extension; BufferedImage originalImage = fileService.downloadImageFromUrl(imageUrl); + if (originalImage == null) { + throw new IllegalArgumentException("Failed to download or decode image from URL"); + } deleteExistingBackgroundFiles(userId); fileService.saveBackgroundImage(originalImage, filename, userId); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java index 75ac24c27..8f32afaa3 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/CbxProcessor.java @@ -146,7 +146,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce .min(Comparator.comparing(ZipArchiveEntry::getName)) .map(entry -> { try (InputStream is = zipFile.getInputStream(entry)) { - return ImageIO.read(is); + return FileService.readImage(is); } catch (Exception e) { log.warn("Failed to read image from ZIP entry {}: {}", entry.getName(), e.getMessage()); return null; @@ -177,7 +177,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce if (bytesRead < 0) break; offset += bytesRead; } - return Optional.ofNullable(ImageIO.read(new ByteArrayInputStream(content))); + return Optional.ofNullable(FileService.readImage(new ByteArrayInputStream(content))); } } } @@ -198,7 +198,7 @@ public class CbxProcessor extends AbstractFileProcessor implements BookFileProce for (FileHeader header : imageHeaders) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { archive.extractFile(header, baos); - return Optional.ofNullable(ImageIO.read(new ByteArrayInputStream(baos.toByteArray()))); + return Optional.ofNullable(FileService.readImage(new ByteArrayInputStream(baos.toByteArray()))); } catch (Exception e) { log.warn("Error reading RAR entry {}: {}", header.getFileName(), e.getMessage()); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java index a4384c203..babf17a59 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/EpubProcessor.java @@ -68,9 +68,9 @@ public class EpubProcessor extends AbstractFileProcessor implements BookFileProc boolean saved; try (ByteArrayInputStream bais = new ByteArrayInputStream(coverData)) { - BufferedImage originalImage = ImageIO.read(bais); + BufferedImage originalImage = FileService.readImage(bais); if (originalImage == null) { - log.warn("Cover image found but could not be decoded (possibly SVG or unsupported format) in EPUB '{}'", bookEntity.getFileName()); + log.warn("Failed to decode cover image for EPUB '{}'", bookEntity.getFileName()); return false; } saved = fileService.saveCoverImages(originalImage, bookEntity.getId()); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java index 09c58f3c4..1b0f25f5d 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/fileprocessor/Fb2Processor.java @@ -125,13 +125,12 @@ public class Fb2Processor extends AbstractFileProcessor implements BookFileProce } private boolean saveCoverImage(byte[] coverData, long bookId) throws Exception { - BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(coverData)); - try { - return fileService.saveCoverImages(originalImage, bookId); - } finally { - if (originalImage != null) { - originalImage.flush(); // Release resources after processing - } + BufferedImage originalImage = FileService.readImage(coverData); + if (originalImage == null) { + log.warn("Failed to decode cover image for FB2"); + return false; } + + return fileService.saveCoverImages(originalImage, bookId); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java index 150d39922..d27de32b1 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/CbxConversionService.java @@ -21,6 +21,8 @@ import com.github.junrar.exception.RarException; import org.springframework.stereotype.Service; import org.springframework.util.FileSystemUtils; +import com.adityachandel.booklore.util.FileService; + import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; @@ -314,7 +316,8 @@ public class CbxConversionService { return lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg") || lowerName.endsWith(".png") || lowerName.endsWith(".webp") || - lowerName.endsWith(".gif") || lowerName.endsWith(".bmp"); + lowerName.endsWith(".gif") || lowerName.endsWith(".bmp") || + lowerName.endsWith(".avif") || lowerName.endsWith(".heic"); } private boolean isJpegFile(Path path) { @@ -404,7 +407,13 @@ public class CbxConversionService { } } else { try (InputStream fis = Files.newInputStream(sourceImagePath)) { - BufferedImage image = ImageIO.read(fis); + BufferedImage image = null; + try { + image = FileService.readImage(fis); + } catch (Exception e) { + log.debug("Failed to decode image {} with FileService: {}", sourceImagePath, e.getMessage()); + } + if (image != null) { writeJpegImage(image, zipOut, compressionPercentage/100f); } else { 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 495f1115e..ff8e9cce8 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 @@ -40,7 +40,7 @@ public class CbxReaderService { private static final String CBZ_EXTENSION = ".cbz"; private static final String CBR_EXTENSION = ".cbr"; private static final String CB7_EXTENSION = ".cb7"; - private static final String[] SUPPORTED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp"}; + private static final String[] SUPPORTED_IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".avif", ".heic"}; private final BookRepository bookRepository; private final AppSettingService appSettingService; 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 4d479c01e..2d168b3e9 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 @@ -144,6 +144,28 @@ public class FileService { // IMAGE OPERATIONS // ======================================== + public static BufferedImage readImage(InputStream inputStream) throws IOException { + return readImage(inputStream.readAllBytes()); + } + + public static BufferedImage readImage(byte[] imageData) throws IOException { + if (imageData == null || imageData.length == 0) { + throw new IOException("Image data is null or empty"); + } + try (InputStream is = new ByteArrayInputStream(imageData)) { + BufferedImage image = ImageIO.read(is); + if (image != null) { + return image; + } + } catch (Exception e) { + log.warn("ImageIO/TwelveMonkeys decode failed (possibly unsupported format like AVIF/HEIC): {}", e.getMessage()); + return null; + } + + log.warn("Unable to decode image - likely unsupported format (AVIF, HEIC, or SVG)"); + return null; + } + public static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) { Image tmp = originalImage.getScaledInstance(width, height, Image.SCALE_SMOOTH); BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); @@ -156,9 +178,10 @@ public class FileService { public static void saveImage(byte[] imageData, String filePath) throws IOException { BufferedImage originalImage = null; try { - originalImage = ImageIO.read(new ByteArrayInputStream(imageData)); + originalImage = readImage(imageData); if (originalImage == null) { - throw new IOException("Invalid image data: unable to decode image"); + log.warn("Skipping saveImage for {}: decoded image is null", filePath); + return; } File outputFile = new File(filePath); File parentDir = outputFile.getParentFile(); @@ -191,13 +214,7 @@ public class FileService { // Validate and convert if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) { - try (ByteArrayInputStream inputStream = new ByteArrayInputStream(response.getBody())) { - BufferedImage image = ImageIO.read(inputStream); - if (image == null) { - throw new IOException("Downloaded content is not a supported image format."); - } - return image; - } + return readImage(response.getBody()); } else { throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode()); } @@ -216,10 +233,11 @@ public class FileService { validateCoverFile(file); BufferedImage originalImage; try (InputStream inputStream = file.getInputStream()) { - originalImage = ImageIO.read(inputStream); + originalImage = readImage(inputStream); } if (originalImage == null) { - throw ApiError.IMAGE_NOT_FOUND.createException(); + log.warn("Could not decode image from file, skipping thumbnail creation for book: {}", bookId); + return; } boolean success = saveCoverImages(originalImage, bookId); if (!success) { @@ -235,12 +253,10 @@ public class FileService { public void createThumbnailFromBytes(long bookId, byte[] imageBytes) { try { - BufferedImage originalImage; - try (InputStream inputStream = new java.io.ByteArrayInputStream(imageBytes)) { - originalImage = ImageIO.read(inputStream); - } + BufferedImage originalImage = readImage(imageBytes); if (originalImage == null) { - throw ApiError.IMAGE_NOT_FOUND.createException(); + log.warn("Skipping thumbnail creation for book {}: image decode failed", bookId); + return; } boolean success = saveCoverImages(originalImage, bookId); if (!success) { @@ -257,6 +273,10 @@ public class FileService { public void createThumbnailFromUrl(long bookId, String imageUrl) { try { BufferedImage originalImage = downloadImageFromUrl(imageUrl); + if (originalImage == null) { + log.warn("Skipping thumbnail creation for book {}: download/decode failed", bookId); + return; + } boolean success = saveCoverImages(originalImage, bookId); if (!success) { throw ApiError.FILE_READ_ERROR.createException("Failed to save cover images"); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java index 0773060a5..4195ff012 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java @@ -355,6 +355,40 @@ class FileServiceTest { @DisplayName("Image Operations") class ImageOperationsTests { + @Nested + @DisplayName("readImage") + class ReadImageTests { + @Test + void validData_returnsImage() throws IOException { + BufferedImage image = createTestImage(100, 100); + byte[] imageData = imageToBytes(image); + + BufferedImage result = FileService.readImage(imageData); + + assertNotNull(result); + assertEquals(100, result.getWidth()); + assertEquals(100, result.getHeight()); + } + + @Test + void nullData_throwsException() { + IOException ex = assertThrows(IOException.class, () -> FileService.readImage((byte[]) null)); + assertEquals("Image data is null or empty", ex.getMessage()); + } + + @Test + void emptyData_throwsException() { + IOException ex = assertThrows(IOException.class, () -> FileService.readImage(new byte[0])); + assertEquals("Image data is null or empty", ex.getMessage()); + } + + @Test + void invalidData_returnsNull() throws IOException { + byte[] invalidData = "not an image".getBytes(); + assertNull(FileService.readImage(invalidData)); + } + } + @Nested @DisplayName("resizeImage") class ResizeImageTests { @@ -460,12 +494,13 @@ class FileServiceTest { } @Test - void invalidImageData_throwsException() { + void invalidImageData_skipsSave() { byte[] invalidData = "not an image".getBytes(); Path outputPath = tempDir.resolve("invalid.jpg"); - assertThrows(IOException.class, () -> + assertDoesNotThrow(() -> FileService.saveImage(invalidData, outputPath.toString())); + assertFalse(Files.exists(outputPath)); } @Test @@ -473,8 +508,9 @@ class FileServiceTest { byte[] emptyData = new byte[0]; Path outputPath = tempDir.resolve("empty.jpg"); - assertThrows(IOException.class, () -> + IOException ex = assertThrows(IOException.class, () -> FileService.saveImage(emptyData, outputPath.toString())); + assertEquals("Image data is null or empty", ex.getMessage()); } @Test @@ -506,8 +542,9 @@ class FileServiceTest { @Test void nullImageData_throwsException() { Path outputPath = tempDir.resolve("null.jpg"); - assertThrows(NullPointerException.class, () -> + IOException ex = assertThrows(IOException.class, () -> FileService.saveImage(null, outputPath.toString())); + assertEquals("Image data is null or empty", ex.getMessage()); } } } @@ -885,34 +922,28 @@ class FileServiceTest { } @Test - void invalidImageBytes_throwsRuntimeException() { + void invalidImageBytes_skipsThumbnail() { byte[] invalidData = "not an image".getBytes(); - RuntimeException exception = assertThrows(RuntimeException.class, () -> + assertDoesNotThrow(() -> fileService.createThumbnailFromBytes(16L, invalidData)); - assertTrue(exception.getMessage().contains("Image not found") || - exception.getMessage().contains("Failed"), - "Exception message should indicate image processing failure"); + assertFalse(Files.exists(Path.of(fileService.getCoverFile(16L)))); } @Test void emptyImageBytes_throwsRuntimeException() { byte[] emptyData = new byte[0]; - // FileService wraps ImageIO exceptions in RuntimeException via ApiError RuntimeException exception = assertThrows(RuntimeException.class, () -> fileService.createThumbnailFromBytes(17L, emptyData)); - assertTrue(exception.getMessage().contains("Image not found") || - exception.getMessage().contains("Failed"), - "Exception message should indicate image processing failure"); + assertEquals("Error reading files from path: Image data is null or empty", exception.getMessage()); } @Test void nullImageBytes_throwsRuntimeException() { - // Null input causes NPE in ByteArrayInputStream constructor, which is caught and wrapped RuntimeException exception = assertThrows(RuntimeException.class, () -> fileService.createThumbnailFromBytes(18L, null)); - assertNotNull(exception.getMessage(), "Exception should have a message"); + assertEquals("Error reading files from path: Image data is null or empty", exception.getMessage()); } } @@ -1009,18 +1040,15 @@ class FileServiceTest { } @Test - void corruptImageData_throwsRuntimeException() { + void corruptImageData_skipsThumbnail() { // Valid MIME type but corrupt image data byte[] corruptData = ("not an image but has jpeg mime type").getBytes(); MockMultipartFile corruptFile = new MockMultipartFile( "file", "corrupt.jpg", "image/jpeg", corruptData); - // FileService wraps exceptions in RuntimeException via ApiError - RuntimeException exception = assertThrows(RuntimeException.class, () -> + assertDoesNotThrow(() -> fileService.createThumbnailFromFile(12L, corruptFile)); - assertTrue(exception.getMessage().contains("Image not found") || - exception.getMessage().contains("not readable"), - "Exception message should indicate image processing failure"); + assertFalse(Files.exists(Path.of(fileService.getCoverFile(12L)))); } @Test @@ -1209,9 +1237,9 @@ class FileServiceTest { } @Test - @DisplayName("throws exception when ImageIO cannot read bytes") + @DisplayName("returns null when ImageIO cannot read bytes") @Timeout(5) - void downloadImageFromUrl_invalidImageData_throwsException() { + void downloadImageFromUrl_invalidImageData_returnsNull() throws IOException { String imageUrl = "http://example.com/image.jpg"; byte[] invalidBytes = "not an image".getBytes(); ResponseEntity responseEntity = ResponseEntity.ok(invalidBytes); @@ -1222,8 +1250,8 @@ class FileServiceTest { eq(byte[].class) )).thenReturn(responseEntity); - assertThrows(IOException.class, () -> - fileService.downloadImageFromUrl(imageUrl)); + BufferedImage result = fileService.downloadImageFromUrl(imageUrl); + assertNull(result); } @Test From b43e9ba08c8d37cc22697edd7e3dfda29698469c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bal=C3=A1zs=20Sz=C3=BCcs?= <127139797+balazs-szucs@users.noreply.github.com> Date: Thu, 8 Jan 2026 02:12:55 +0100 Subject: [PATCH 24/40] feat(ComicVine): use structured search for ComicVine metadata fetching instead of generic /search (#2193) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(comicvine): improve comic metadata handling with additional fields and improved search logic Signed-off-by: Balázs Szücs * feat(comicvine): enhance series and issue extraction with improved regex patterns and caching mechanism Signed-off-by: Balázs Szücs * feat(comicvine): enhance ComicvineBookParser with improved metadata extraction and logging Signed-off-by: Balázs Szücs * feat(comicvine): improve title formatting and author extraction in ComicvineBookParser Signed-off-by: Balázs Szücs --------- Signed-off-by: Balázs Szücs --- .../booklore/model/dto/BookMetadata.java | 2 + .../dto/response/comicvineapi/Comic.java | 41 ++ .../comicvineapi/ComicvineIssueResponse.java | 26 +- .../metadata/parser/ComicvineBookParser.java | 670 +++++++++++++++--- 4 files changed, 616 insertions(+), 123 deletions(-) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMetadata.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMetadata.java index d6dfc0778..544ec5b78 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMetadata.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/BookMetadata.java @@ -46,6 +46,7 @@ public class BookMetadata { private Double lubimyczytacRating; private String googleId; private String lubimyczytacId; + private String externalUrl; private Instant coverUpdatedOn; private Set authors; private Set categories; @@ -84,6 +85,7 @@ public class BookMetadata { private Boolean doubanReviewCountLocked; private Boolean lubimyczytacIdLocked; private Boolean lubimyczytacRatingLocked; + private Boolean externalUrlLocked; private Boolean coverLocked; private Boolean authorsLocked; private Boolean categoriesLocked; diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/Comic.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/Comic.java index d85ee6e20..39d616f82 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/Comic.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/Comic.java @@ -5,6 +5,8 @@ import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; import lombok.NoArgsConstructor; +import java.util.List; + @Data @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) @@ -32,6 +34,30 @@ public class Comic { @JsonProperty("resource_type") private String resourceType; + @JsonProperty("person_credits") + private List personCredits; + + @JsonProperty("start_year") + private String startYear; + + @JsonProperty("count_of_issues") + private Integer countOfIssues; + + @JsonProperty("site_detail_url") + private String siteDetailUrl; + + private Publisher publisher; + + @Data + @NoArgsConstructor + @JsonIgnoreProperties(ignoreUnknown = true) + public static class Publisher { + private int id; + private String name; + @JsonProperty("api_detail_url") + private String apiDetailUrl; + } + @Data @NoArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) @@ -79,5 +105,20 @@ public class Comic { @JsonProperty("site_detail_url") private String siteDetailUrl; + + @JsonProperty("start_year") + private String startYear; + + @JsonProperty("count_of_issues") + private Integer countOfIssues; + } + + @Data + @NoArgsConstructor + @JsonIgnoreProperties(ignoreUnknown = true) + public static class PersonCredit { + private long id; + private String name; + private String role; } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/ComicvineIssueResponse.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/ComicvineIssueResponse.java index 62b7f3a51..2932ed652 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/ComicvineIssueResponse.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/response/comicvineapi/ComicvineIssueResponse.java @@ -22,14 +22,26 @@ public class ComicvineIssueResponse { @JsonIgnoreProperties(ignoreUnknown = true) public static class IssueResults { @JsonProperty("person_credits") - private List personCredits; - } + private List personCredits; + + private String description; - @Data - @JsonIgnoreProperties(ignoreUnknown = true) - public static class PersonCredit { - private long id; private String name; - private String role; + + @JsonProperty("issue_number") + private String issueNumber; + + @JsonProperty("cover_date") + private String coverDate; + + private Comic.Image image; + + private Comic.Volume volume; + + @JsonProperty("api_detail_url") + private String apiDetailUrl; + + @JsonProperty("site_detail_url") + private String siteDetailUrl; } } \ No newline at end of file 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 e9b2af8bd..6dbb1cf23 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 @@ -5,6 +5,7 @@ import com.adityachandel.booklore.model.dto.BookMetadata; import com.adityachandel.booklore.model.dto.request.FetchMetadataRequest; import com.adityachandel.booklore.model.dto.response.comicvineapi.Comic; import com.adityachandel.booklore.model.dto.response.comicvineapi.ComicvineApiResponse; +import com.adityachandel.booklore.model.dto.response.comicvineapi.ComicvineIssueResponse; import com.adityachandel.booklore.model.enums.MetadataProvider; import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.util.BookUtils; @@ -23,11 +24,10 @@ import java.time.Instant; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; +import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; +import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; @@ -39,6 +39,14 @@ public class ComicvineBookParser implements BookParser { private static final String COMICVINE_URL = "https://comicvine.gamespot.com/api/"; private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd"); private static final Pattern DIGIT_PATTERN = Pattern.compile("\\d+"); + private static final Pattern SERIES_ISSUE_PATTERN = Pattern.compile("^(.+?)\\s+#?(\\d+(?:\\.\\d+)?)(?:\\s|$)", Pattern.CASE_INSENSITIVE); + private static final Pattern DIGITAL_PATTERN = Pattern.compile("\\(digital\\)", Pattern.CASE_INSENSITIVE); + private static final Pattern PARENTHETICAL_PATTERN = Pattern.compile("\\([^)]*\\)"); + private static final Pattern BRACKETED_PATTERN = Pattern.compile("\\[[^\\]]*\\]"); + private static final Pattern WHITESPACE_PATTERN = Pattern.compile("\\s+"); + private static final Pattern SPECIAL_ISSUE_PATTERN = Pattern.compile("(annual|special|one-?shot)\\s+(\\d+)", Pattern.CASE_INSENSITIVE); + private static final Pattern YEAR_PATTERN = Pattern.compile("\\(?(\\d{4})\\)?"); + private static final long MIN_REQUEST_INTERVAL_MS = 1000; private final ObjectMapper objectMapper; private final AppSettingService appSettingService; @@ -46,6 +54,22 @@ public class ComicvineBookParser implements BookParser { private final AtomicBoolean rateLimited = new AtomicBoolean(false); private final AtomicLong rateLimitResetTime = new AtomicLong(0); + private final AtomicLong lastRequestTime = new AtomicLong(0); + private final Map volumeCache = new java.util.concurrent.ConcurrentHashMap<>(); + + private static class CachedVolumes { + final List volumes; + final long timestamp; + + CachedVolumes(List volumes) { + this.volumes = volumes; + this.timestamp = System.currentTimeMillis(); + } + + boolean isExpired() { + return System.currentTimeMillis() - timestamp > 300_000; + } + } @Override public List fetchMetadata(Book book, FetchMetadataRequest fetchMetadataRequest) { @@ -64,37 +88,247 @@ public class ComicvineBookParser implements BookParser { } public List getMetadataListByTerm(String term) { + SeriesAndIssue seriesAndIssue = extractSeriesAndIssue(term); + + // Try precise search if issue number present + if (seriesAndIssue.issue() != null) { + log.info("Attempting structured search for Series: '{}', Issue: '{}', Year: '{}', Type: '{}'", + seriesAndIssue.series(), seriesAndIssue.issue(), seriesAndIssue.year(), seriesAndIssue.issueType()); + List preciseResults = searchVolumesAndIssues(seriesAndIssue.series(), seriesAndIssue.issue(), seriesAndIssue.year()); + if (!preciseResults.isEmpty()) { + return preciseResults; + } + log.info("Structured search yielded no results, falling back to general search."); + } + + // Fallback to general search + return searchGeneral(term); + } + + private List searchVolumesAndIssues(String seriesName, String issueNumber, Integer extractedYear) { + String normalizedIssue = normalizeIssueNumber(issueNumber); + if (seriesName.endsWith(" " + issueNumber) || seriesName.endsWith(" " + normalizedIssue)) { + // Strip issue number from series name if it leaked in + seriesName = seriesName.replaceAll("\\s+" + Pattern.quote(issueNumber) + "$", "") + .replaceAll("\\s+" + Pattern.quote(normalizedIssue) + "$", "") + .trim(); + log.warn("Issue number found in series name, corrected to: '{}'", seriesName); + } + + final String finalSeriesName = seriesName; + log.debug("searchVolumesAndIssues: seriesName='{}', issueNumber='{}', year='{}'", finalSeriesName, issueNumber, extractedYear); + List volumes = searchVolumes(finalSeriesName); + if (volumes.isEmpty()) { + log.debug("No volumes found for series '{}'", finalSeriesName); + return Collections.emptyList(); + } + + // Sort volumes by relevance + volumes.sort((v1, v2) -> { + int score1 = 0; + int score2 = 0; + + if (extractedYear != null) { + if (matchesYear(v1, extractedYear)) score1 += 100; + if (matchesYear(v2, extractedYear)) score2 += 100; + } + + if (v1.getName() != null && v1.getName().equalsIgnoreCase(finalSeriesName)) score1 += 50; + if (v2.getName() != null && v2.getName().equalsIgnoreCase(finalSeriesName)) score2 += 50; + + try { + int requestedIssue = (int) Math.floor(Double.parseDouble(normalizedIssue)); + if (v1.getCountOfIssues() != null && v1.getCountOfIssues() >= requestedIssue) score1 += 20; + if (v2.getCountOfIssues() != null && v2.getCountOfIssues() >= requestedIssue) score2 += 20; + } catch (NumberFormatException ignored) {} + + Set majorPublishers = Set.of("Marvel", "DC Comics", "Image", "Dark Horse Comics", "IDW Publishing"); + if (v1.getPublisher() != null && majorPublishers.stream().anyMatch(p -> v1.getPublisher().getName().contains(p))) score1 += 10; + if (v2.getPublisher() != null && majorPublishers.stream().anyMatch(p -> v2.getPublisher().getName().contains(p))) score2 += 10; + + return Integer.compare(score2, score1); + }); + + List results = new ArrayList<>(); + // Limit to top 3 volumes to minimize API calls + int limit = Math.min(volumes.size(), 3); + + for (int i = 0; i < limit; i++) { + Comic volume = volumes.get(i); + log.debug("Checking volume: id='{}', name='{}', start_year='{}'", volume.getId(), volume.getName(), volume.getStartYear()); + + List issues = searchIssuesInVolume(volume.getId(), issueNumber); + if (!issues.isEmpty()) { + results.addAll(issues); + + // If we found a result in a high-score volume (e.g. year matched), stop. + if (extractedYear != null && matchesYear(volume, extractedYear)) { + log.info("Found match in year-aligned volume '{}' ({}) . Stopping further volume searches.", volume.getName(), volume.getStartYear()); + break; + } + } + } + return results; + } + + private boolean matchesYear(Comic volume, int targetYear) { + if (volume.getStartYear() == null) return false; + try { + int volYear = Integer.parseInt(volume.getStartYear()); + return Math.abs(volYear - targetYear) <= 1; + } catch (NumberFormatException e) { + return false; + } + } + + private List searchVolumes(String seriesName) { + CachedVolumes cached = volumeCache.get(seriesName.toLowerCase()); + if (cached != null && !cached.isExpired()) { + log.debug("Using cached volume search for '{}'", seriesName); + return cached.volumes; + } + String apiToken = getApiToken(); if (apiToken == null) return Collections.emptyList(); + URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL) + .path("/search/") + .queryParam("api_key", apiToken) + .queryParam("format", "json") + .queryParam("resources", "volume") + .queryParam("query", seriesName) + .queryParam("limit", 10) + .queryParam("field_list", "id,name,publisher,start_year,count_of_issues") + .build() + .toUri(); + + ComicvineApiResponse response = sendRequest(uri, ComicvineApiResponse.class); + List volumes = response != null && response.getResults() != null ? response.getResults() : Collections.emptyList(); + + if (!volumes.isEmpty()) { + volumeCache.put(seriesName.toLowerCase(), new CachedVolumes(volumes)); + } else if (seriesName.contains(" - ")) { + String alternativeName = seriesName.replace(" - ", ": "); + log.debug("No results for '{}', trying alternative name '{}'", seriesName, alternativeName); + return searchVolumes(alternativeName); + } + + return volumes; + } + + private List searchIssuesInVolume(int volumeId, String issueNumber) { + String apiToken = getApiToken(); + if (apiToken == null) return Collections.emptyList(); + + String normalizedIssue = normalizeIssueNumber(issueNumber); + log.debug("searchIssuesInVolume: volumeId='{}', original='{}', normalized='{}'", + volumeId, issueNumber, normalizedIssue); + + String fieldsList = String.join(",", "api_detail_url", "cover_date", "description", "id", "image", "issue_number", "name", "volume", "site_detail_url"); + + URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL) + .path("/issues/") + .queryParam("api_key", apiToken) + .queryParam("format", "json") + .queryParam("filter", "volume:" + volumeId + ",issue_number:" + normalizedIssue) + .queryParam("field_list", fieldsList) + .queryParam("limit", 5) + .build() + .toUri(); + + ComicvineApiResponse response = sendRequest(uri, ComicvineApiResponse.class); + if (response != null && response.getResults() != null && !response.getResults().isEmpty()) { + Comic firstIssue = response.getResults().getFirst(); + String returnedIssue = normalizeIssueNumber(firstIssue.getIssueNumber()); + + if (!normalizedIssue.equals(returnedIssue)) { + log.warn("Issue number mismatch! Requested '{}', got '{}' from volume {}", + normalizedIssue, returnedIssue, volumeId); + return Collections.emptyList(); + } + + BookMetadata detailed = fetchIssueDetails(firstIssue.getId()); + + return Collections.singletonList(Objects.requireNonNullElseGet(detailed, () -> convertToBookMetadata(firstIssue))); + } + return Collections.emptyList(); + } + + private BookMetadata fetchIssueDetails(int issueId) { + String apiToken = getApiToken(); + if (apiToken == null) return null; + + String fieldsList = String.join(",", "api_detail_url", "cover_date", "description", "id", "image", "issue_number", "name", "person_credits", "volume", "site_detail_url"); + + URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL) + .path("/issue/4000-" + issueId + "/") + .queryParam("api_key", apiToken) + .queryParam("format", "json") + .queryParam("field_list", fieldsList) + .build() + .toUri(); + + ComicvineIssueResponse response = sendRequest(uri, ComicvineIssueResponse.class); + if (response != null && response.getResults() != null) { + return convertToBookMetadata(response.getResults()); + } + return null; + } + + private List searchGeneral(String term) { + String apiToken = getApiToken(); + if (apiToken == null) return Collections.emptyList(); + + String fieldsList = String.join(",", "api_detail_url", "cover_date", "description", "id", "image", "issue_number", "name", "publisher", "volume", "site_detail_url", "resource_type", "start_year", "count_of_issues"); + String resources = "volume,issue"; + + URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL) + .path("/search/") + .queryParam("api_key", apiToken) + .queryParam("format", "json") + .queryParam("resources", resources) + .queryParam("query", term) + .queryParam("limit", 10) + .queryParam("field_list", fieldsList) + .build() + .toUri(); + + ComicvineApiResponse response = sendRequest(uri, ComicvineApiResponse.class); + if (response != null && response.getResults() != null) { + return response.getResults().stream() + .map(this::convertToBookMetadata) + .collect(Collectors.toList()); + } + return Collections.emptyList(); + } + + private T sendRequest(URI uri, Class responseType) { + return sendRequestWithRetry(uri, responseType, 2); + } + + private T sendRequestWithRetry(URI uri, Class responseType, int retriesLeft) { if (rateLimited.get()) { long currentTime = System.currentTimeMillis(); if (currentTime < rateLimitResetTime.get()) { - log.warn("ComicVine API is currently rate limited. Skipping request for term: '{}'. Rate limit resets at: {}", - term, Instant.ofEpochMilli(rateLimitResetTime.get())); - return Collections.emptyList(); + log.warn("ComicVine API is currently rate limited. Skipping request. Rate limit resets at: {}", + Instant.ofEpochMilli(rateLimitResetTime.get())); + return null; } else { - // Rate limit has expired, reset the flag rateLimited.compareAndSet(true, false); } } - log.info("Comicvine: Fetching metadata for term: '{}'", term); + long now = System.currentTimeMillis(); + long timeSinceLastRequest = now - lastRequestTime.get(); + if (timeSinceLastRequest < MIN_REQUEST_INTERVAL_MS) { + try { + Thread.sleep(MIN_REQUEST_INTERVAL_MS - timeSinceLastRequest); + } catch (InterruptedException ignored) {} + } + lastRequestTime.set(System.currentTimeMillis()); + try { - String fieldsList = String.join(",", "api_detail_url", "cover_date", "description", "id", "image", "issue_number", "name", "publisher", "volume"); - String resources = "volume,issue"; - - URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL) - .path("/search/") - .queryParam("api_key", apiToken) - .queryParam("format", "json") - .queryParam("resources", resources) - .queryParam("query", term) - .queryParam("limit", 10) - .queryParam("field_list", fieldsList) - .build() - .toUri(); - + log.debug("Sending request to ComicVine: {}", uri); HttpRequest request = HttpRequest.newBuilder() .uri(uri) .header("User-Agent", "BookLore/1.0 (Book and Comic Metadata Fetcher; +https://github.com/booklore-app/booklore)") @@ -102,77 +336,323 @@ public class ComicvineBookParser implements BookParser { .build(); HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + log.debug("Received response from ComicVine: status='{}', body_length='{}'", + response.statusCode(), response.body() != null ? response.body().length() : 0); if (response.statusCode() == 200) { - return parseComicvineApiResponse(response.body()); + return objectMapper.readValue(response.body(), responseType); } else if (response.statusCode() == 420 || response.statusCode() == 429) { - log.error("ComicVine API rate limit exceeded (Error {}). Setting rate limit flag.", response.statusCode()); + handleRateLimit(response); + return null; + } else if (response.statusCode() >= 500 && retriesLeft > 0) { + log.warn("ComicVine API returned status {}. Retrying... ({} retries left)", + response.statusCode(), retriesLeft); + try { + Thread.sleep(2000); + } catch (InterruptedException ignored) {} + return sendRequestWithRetry(uri, responseType, retriesLeft - 1); + } else { + log.error("Comicvine API returned status code {}. Body: {}", response.statusCode(), response.body()); + } + } catch (IOException e) { + if (retriesLeft > 0) { + log.warn("IOException during ComicVine request. Retrying... ({} retries left)", retriesLeft, e); + try { + Thread.sleep(1000); + } catch (InterruptedException ignored) {} + return sendRequestWithRetry(uri, responseType, retriesLeft - 1); + } else { + log.error("Error fetching data from Comicvine API after retries", e); + } + } catch (InterruptedException e) { + log.error("Request interrupted", e); + Thread.currentThread().interrupt(); + } + return null; + } - long resetDelayMs = 3600000; // Default to 1 hour - List retryAfterHeaders = response.headers().allValues("Retry-After"); - if (!retryAfterHeaders.isEmpty()) { - try { - String retryAfter = retryAfterHeaders.getFirst(); - if (DIGIT_PATTERN.matcher(retryAfter).matches()) { - resetDelayMs = Long.parseLong(retryAfter) * 1000; - } else { - Instant instant = Instant.parse(retryAfter); - resetDelayMs = instant.toEpochMilli() - System.currentTimeMillis(); - if (resetDelayMs <= 0) { - resetDelayMs = 3600000; // Default to 1 hour if date is in the past - } - } - } catch (Exception e) { - log.warn("Could not parse Retry-After header '{}', using default 1 hour delay", retryAfterHeaders.getFirst()); + private void handleRateLimit(HttpResponse response) { + log.error("ComicVine API rate limit exceeded (Error {}). Setting rate limit flag.", response.statusCode()); + + long resetDelayMs = 3600000; + List retryAfterHeaders = response.headers().allValues("Retry-After"); + if (!retryAfterHeaders.isEmpty()) { + try { + String retryAfter = retryAfterHeaders.getFirst(); + if (DIGIT_PATTERN.matcher(retryAfter).matches()) { + resetDelayMs = Long.parseLong(retryAfter) * 1000; + } else { + Instant instant = Instant.parse(retryAfter); + resetDelayMs = instant.toEpochMilli() - System.currentTimeMillis(); + if (resetDelayMs <= 0) { + resetDelayMs = 3600000; } } - - if (rateLimited.compareAndSet(false, true)) { - rateLimitResetTime.set(System.currentTimeMillis() + resetDelayMs); - log.info("Rate limit will reset at: {}", Instant.ofEpochMilli(rateLimitResetTime.get())); - } - - return Collections.emptyList(); - } else { - log.error("Comicvine Search API returned status code {}", response.statusCode()); + } catch (Exception e) { + log.warn("Could not parse Retry-After header '{}', using default 1 hour delay", retryAfterHeaders.getFirst()); } - } catch (IOException | InterruptedException e) { - log.error("Error fetching metadata from Comicvine Search API", e); } - return Collections.emptyList(); + + if (rateLimited.compareAndSet(false, true)) { + rateLimitResetTime.set(System.currentTimeMillis() + resetDelayMs); + log.info("Rate limit will reset at: {}", Instant.ofEpochMilli(rateLimitResetTime.get())); + } + } + + private BookMetadata convertToBookMetadata(Comic comic) { + // Check if this is a Volume + if ("volume".equalsIgnoreCase(comic.getResourceType())) { + return BookMetadata.builder() + .provider(MetadataProvider.Comicvine) + .comicvineId(String.valueOf(comic.getId())) + .title(comic.getName()) // Use volume name as title + .seriesName(comic.getName()) + .seriesTotal(comic.getCountOfIssues()) + .publishedDate(safeParseDate(comic.getStartYear() + "-01-01")) // Rough estimate if only year + .description(comic.getDescription()) + .publisher(comic.getPublisher() != null ? comic.getPublisher().getName() : null) + .thumbnailUrl(comic.getImage() != null ? comic.getImage().getMediumUrl() : null) + .externalUrl(comic.getSiteDetailUrl()) + .build(); + } + + Set authors = extractAuthors(comic.getPersonCredits()); + String formattedTitle = formatTitle(comic.getVolume() != null ? comic.getVolume().getName() : null, comic.getIssueNumber(), comic.getName()); + + BookMetadata metadata = BookMetadata.builder() + .provider(MetadataProvider.Comicvine) + .comicvineId(String.valueOf(comic.getId())) + .title(formattedTitle) + .authors(authors) + .thumbnailUrl(comic.getImage() != null ? comic.getImage().getMediumUrl() : null) + .description(comic.getDescription()) + .seriesName(comic.getVolume() != null ? comic.getVolume().getName() : null) + .seriesNumber(safeParseFloat(comic.getIssueNumber())) + .publishedDate(safeParseDate(comic.getCoverDate())) + .externalUrl(comic.getSiteDetailUrl()) + .build(); + + if (metadata.getSeriesName() == null || metadata.getSeriesNumber() == null) { + log.warn("Incomplete metadata for issue {}: missing series name or number", metadata.getComicvineId()); + } + + if (metadata.getAuthors().isEmpty()) { + log.debug("No authors found for issue {} ({})", metadata.getComicvineId(), metadata.getTitle()); + } + + return metadata; + } + + private BookMetadata convertToBookMetadata(ComicvineIssueResponse.IssueResults issue) { + // Extract ID from api_detail_url: "https://comicvine.gamespot.com/api/issue/4000-12345/" + String comicvineId = null; + if (issue.getApiDetailUrl() != null) { + Matcher matcher = Pattern.compile("/(\\d+)/?$").matcher(issue.getApiDetailUrl()); + if (matcher.find()) { + comicvineId = matcher.group(1); + } + } + + Set authors = extractAuthors(issue.getPersonCredits()); + String formattedTitle = formatTitle(issue.getVolume() != null ? issue.getVolume().getName() : null, issue.getIssueNumber(), issue.getName()); + + BookMetadata metadata = BookMetadata.builder() + .provider(MetadataProvider.Comicvine) + .comicvineId(comicvineId) + .title(formattedTitle) + .authors(authors) + .thumbnailUrl(issue.getImage() != null ? issue.getImage().getMediumUrl() : null) + .description(issue.getDescription()) + .seriesName(issue.getVolume() != null ? issue.getVolume().getName() : null) + .seriesNumber(safeParseFloat(issue.getIssueNumber())) + .publishedDate(safeParseDate(issue.getCoverDate())) + .externalUrl(issue.getSiteDetailUrl()) + .build(); + + if (metadata.getSeriesName() == null || metadata.getSeriesNumber() == null) { + log.warn("Incomplete metadata for issue {}: missing series name or number", comicvineId); + } + + if (metadata.getAuthors().isEmpty()) { + log.debug("No authors found for issue {} ({})", comicvineId, metadata.getTitle()); + } + + return metadata; + } + + private String formatTitle(String seriesName, String issueNumber, String issueName) { + if (seriesName == null) return issueName; + + String normalizedIssue = normalizeIssueNumber(issueNumber); + String title = seriesName + " #" + (normalizedIssue != null ? normalizedIssue : ""); + + // Append issue title if it exists and isn't just "Issue #X" or identical to series + if (issueName != null && !issueName.isBlank()) { + String lowerName = issueName.toLowerCase(); + boolean isGeneric = lowerName.matches("issue\\s*#?\\d+") || lowerName.equals(seriesName.toLowerCase()); + if (!isGeneric) { + title += " - " + issueName; + } + } + return title; + } + + private Set extractAuthors(List personCredits) { + if (personCredits == null || personCredits.isEmpty()) { + return Collections.emptySet(); + } + + // Primary writer roles + Set writerRoles = Set.of("writer", "script", "story", "plotter", "plot"); + + // Collect writers + Set authors = personCredits.stream() + .filter(pc -> { + if (pc.getRole() == null) return false; + String role = pc.getRole().toLowerCase(); + return writerRoles.stream().anyMatch(role::contains); + }) + .map(Comic.PersonCredit::getName) + .filter(name -> name != null && !name.isEmpty()) + .collect(Collectors.toSet()); + + // Fallback: If no writers found, check for "creator" role + if (authors.isEmpty()) { + // DEBUG: Log all roles if we missed them + List allRoles = personCredits.stream() + .map(pc -> pc.getName() + " (" + pc.getRole() + ")") + .toList(); + log.debug("No writers found. Available roles: {}", allRoles); + + authors = personCredits.stream() + .filter(pc -> pc.getRole() != null && pc.getRole().toLowerCase().contains("creator")) + .map(Comic.PersonCredit::getName) + .filter(name -> name != null && !name.isEmpty()) + .collect(Collectors.toSet()); + } + + return authors; } 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()); + // Use filename but preserve parentheses for year extraction + String name = book.getFileName(); + // Remove extension only + int dotIndex = name.lastIndexOf('.'); + if (dotIndex > 0) { + name = name.substring(0, dotIndex); + } + return name.trim(); } return null; } - private List parseComicvineApiResponse(String responseBody) throws IOException { - ComicvineApiResponse apiResponse = objectMapper.readValue(responseBody, ComicvineApiResponse.class); - if (apiResponse.getResults() == null) { - return Collections.emptyList(); + private SeriesAndIssue extractSeriesAndIssue(String term) { + // 1. Extract Year + Integer year = null; + Matcher yearMatcher = YEAR_PATTERN.matcher(term); + String yearString = null; + if (yearMatcher.find()) { + try { + int y = Integer.parseInt(yearMatcher.group(1)); + if (y > 1900 && y <= LocalDate.now().getYear() + 1) { + year = y; + yearString = yearMatcher.group(0); + } + } catch (NumberFormatException ignored) {} } - return apiResponse.getResults().stream() - .map(this::convertToBookMetadata) - .collect(Collectors.toList()); - } - private BookMetadata convertToBookMetadata(Comic comic) { - return BookMetadata.builder() - .provider(MetadataProvider.Comicvine) - .comicvineId(String.valueOf(comic.getId())) - .title(comic.getName()) - .authors(new HashSet<>()) - .thumbnailUrl(comic.getImage() != null ? comic.getImage().getMediumUrl() : null) - .description(comic.getDescription()) - .seriesName(comic.getVolume() != null ? comic.getVolume().getName() : null) - .seriesNumber(safeParseFloat(comic.getIssueNumber())) - .publishedDate(safeParseDate(comic.getCoverDate())) - .build(); + // 2. Remove ONLY the found year and noise from the term + String cleaned = term; + if (yearString != null) { + cleaned = cleaned.replace(yearString, ""); + } + cleaned = DIGITAL_PATTERN.matcher(cleaned).replaceAll(""); + cleaned = PARENTHETICAL_PATTERN.matcher(cleaned).replaceAll(""); + cleaned = BRACKETED_PATTERN.matcher(cleaned).replaceAll(""); + cleaned = cleaned.trim(); + cleaned = WHITESPACE_PATTERN.matcher(cleaned).replaceAll(" "); + + log.debug("Cleaned filename: '{}'", cleaned); + + // 3. Check for special issue keywords BEFORE extracting issue number + String lowerCleaned = cleaned.toLowerCase(); + if (lowerCleaned.contains("annual") || + lowerCleaned.contains("special") || + lowerCleaned.contains("one-shot") || + lowerCleaned.contains("one shot")) { + + // Try to extract number from "Annual 2" or "Special 3" + Matcher specialMatcher = SPECIAL_ISSUE_PATTERN.matcher(cleaned); + if (specialMatcher.find()) { + String type = specialMatcher.group(1); + String num = specialMatcher.group(2); + // Return series name before the special keyword + String series = cleaned.substring(0, specialMatcher.start()).trim(); + return new SeriesAndIssue(series, num, year, type); + } else { + // "Batman Annual" without number - search for all annuals + return new SeriesAndIssue(cleaned, null, year, "annual"); + } + } + + // 4. Standard issue extraction with IMPROVED PATTERN + Matcher matcher = SERIES_ISSUE_PATTERN.matcher(cleaned); + if (matcher.find()) { + String series = matcher.group(1).trim(); + String issueNum = matcher.group(2); + + if (series.endsWith("#")) { + series = series.substring(0, series.length() - 1).trim(); + } + + log.debug("Extracted - Series: '{}', Issue: '{}'", series, issueNum); + return new SeriesAndIssue(series, issueNum, year, null); + } + + log.debug("No issue number found in: '{}'", cleaned); + return new SeriesAndIssue(cleaned, null, year, null); + } + + private String normalizeIssueNumber(String issueNumber) { + if (issueNumber == null || issueNumber.isEmpty()) { + return issueNumber; + } + + issueNumber = issueNumber.trim(); + + if (issueNumber.contains("/")) { + try { + String[] parts = issueNumber.split("/"); + if (parts.length == 2) { + double numerator = Double.parseDouble(parts[0]); + double denominator = Double.parseDouble(parts[1]); + return String.valueOf(numerator / denominator); + } + } catch (NumberFormatException e) { + log.warn("Could not parse fractional issue number '{}'", issueNumber); + return issueNumber; + } + } + + try { + if (issueNumber.contains(".")) { + double d = Double.parseDouble(issueNumber); + if (d == Math.floor(d)) { + return String.valueOf((int) d); + } else { + return new java.text.DecimalFormat("0.#####").format(d); + } + } else { + return String.valueOf(Integer.parseInt(issueNumber)); + } + } catch (NumberFormatException e) { + log.debug("Non-numeric issue number '{}', using as-is", issueNumber); + return issueNumber; + } } private static LocalDate safeParseDate(String dateStr) { @@ -203,47 +683,5 @@ public class ComicvineBookParser implements BookParser { return apiToken; } - /*public Set fetchAuthors(int issueId) { - String apiToken = getApiToken(); - if (apiToken == null) return Collections.emptySet(); - - try { - String fieldsList = String.join(",", "person_credits"); - - URI uri = UriComponentsBuilder.fromUriString(COMICVINE_URL) - .path("/issue/4000-" + issueId + "/") - .queryParam("api_key", apiToken) - .queryParam("format", "json") - .queryParam("field_list", fieldsList) - .build() - .toUri(); - - HttpRequest request = HttpRequest.newBuilder() - .uri(uri) - .header("User-Agent", "Booklore/1.0") - .GET() - .build(); - - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - - if (response.statusCode() == 200) { - ComicvineIssueResponse issueResponse = objectMapper.readValue(response.body(), ComicvineIssueResponse.class); - if (issueResponse.getResults() == null || issueResponse.getResults().getPersonCredits() == null) { - log.warn("No person credits found for issue ID {}", issueId); - return Collections.emptySet(); - } - - return issueResponse.getResults().getPersonCredits().stream() - .filter(pc -> pc.getRole() != null && pc.getRole().toLowerCase().contains("writer")) - .map(ComicvineIssueResponse.PersonCredit::getName) - .collect(Collectors.toSet()); - - } else { - log.error("Comicvine Issue API returned status code {}", response.statusCode()); - } - } catch (IOException | InterruptedException e) { - log.error("Error fetching issue metadata from Comicvine Issue API", e); - } - return Collections.emptySet(); - }*/ + private record SeriesAndIssue(String series, String issue, Integer year, String issueType) {} } \ No newline at end of file From f75eb840c6022a36c1f470c9a286232b9e6fb6c1 Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Wed, 7 Jan 2026 23:23:06 -0700 Subject: [PATCH 25/40] Configure reverse proxy to support streaming response (#2201) Co-authored-by: acx10 --- nginx.conf | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/nginx.conf b/nginx.conf index 8f5023303..d8d77ea20 100644 --- a/nginx.conf +++ b/nginx.conf @@ -42,6 +42,17 @@ http { proxy_pass http://localhost:8080; proxy_set_header X-Forwarded-Port $server_port; proxy_set_header X-Forwarded-Host $host; + + # Disable buffering for streaming responses + proxy_buffering off; + proxy_cache off; + proxy_set_header Connection ''; + proxy_http_version 1.1; + chunked_transfer_encoding on; + + # Set timeouts for long-running connections + proxy_read_timeout 86400s; + proxy_send_timeout 86400s; } # Proxy WebSocket requests (ws://) to the backend From 15de049f3d9a8050ba72224e9c0a2dcdb92fd83c Mon Sep 17 00:00:00 2001 From: ACX <8075870+acx10@users.noreply.github.com> Date: Thu, 8 Jan 2026 15:18:20 -0700 Subject: [PATCH 26/40] =?UTF-8?q?Support=20individual=20=E2=80=9Cwrite=20t?= =?UTF-8?q?o=20file=E2=80=9D=20settings=20per=20book=20type,=20with=20conf?= =?UTF-8?q?igurable=20file=20size=20limits=20(#2206)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: acx10 --- .../BackgroundUploadController.java | 65 - .../controller/BookCoverController.java | 104 ++ .../controller/BookMediaController.java | 32 - .../controller/MetadataController.java | 105 +- .../model/dto/settings/AppSettingKey.java | 2 +- .../settings/MetadataPersistenceSettings.java | 25 +- .../booklore/repository/BookRepository.java | 4 + .../projection/BookCoverUpdateProjection.java | 9 + .../booklore/service/TelemetryService.java | 2 +- .../appsettings/SettingPersistenceHelper.java | 30 +- .../booklore/service/book/BookService.java | 10 - .../service/file/BackgroundUploadService.java | 130 -- .../service/metadata/BookCoverService.java | 226 +-- .../service/metadata/BookMetadataService.java | 35 +- .../service/metadata/BookMetadataUpdater.java | 6 +- .../metadata/MetadataManagementService.java | 138 +- .../extractor/CbxMetadataExtractor.java | 1520 ++++++++--------- .../metadata/writer/CbxMetadataWriter.java | 747 ++++---- .../metadata/writer/EpubMetadataWriter.java | 127 +- .../metadata/writer/MetadataWriter.java | 7 +- .../metadata/writer/PdfMetadataWriter.java | 32 +- .../booklore/util/FileService.java | 83 +- ..._MetadataPersistenceSettings_Structure.sql | 50 + .../controller/BookMediaControllerTest.java | 37 - .../service/book/BookServiceTest.java | 54 +- .../metadata/BookCoverServiceTest.java | 165 +- .../BookMetadataUpdaterCategoryTest.java | 50 +- .../metadata/BookMetadataUpdaterTest.java | 48 +- .../extractor/CbxMetadataExtractorTest.java | 2 - .../extractor/ComicInfoParsingIssuesTest.java | 5 - .../ExtractFromComicInfoXmlTest.java | 77 +- .../writer/CbxMetadataWriterTest.java | 37 +- .../writer/EpubMetadataWriterTest.java | 215 +-- .../booklore/util/FileServiceTest.java | 656 +++---- .../book/service/book.service.spec.ts | 13 +- .../app/features/book/service/book.service.ts | 8 +- .../metadata-editor.component.html | 314 ++-- .../metadata-editor.component.scss | 329 +++- .../metadata-editor.component.ts | 10 +- .../metadata-picker.component.scss | 4 + .../metadata-searcher.component.scss | 11 - .../metadata-viewer.component.scss | 1 + .../metadata-manager.component.html | 5 + .../metadata-manager.component.scss | 50 + ...tadata-persistence-settings-component.html | 143 +- ...tadata-persistence-settings-component.scss | 73 +- ...metadata-persistence-settings-component.ts | 65 +- .../app/shared/model/app-settings.model.ts | 13 +- .../service/app-settings.service.spec.ts | 12 +- 49 files changed, 3071 insertions(+), 2815 deletions(-) delete mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/controller/BackgroundUploadController.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/controller/BookCoverController.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/repository/projection/BookCoverUpdateProjection.java delete mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java create mode 100644 booklore-api/src/main/resources/db/migration/V87__Migrate_MetadataPersistenceSettings_Structure.sql delete mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/controller/BookMediaControllerTest.java diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BackgroundUploadController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BackgroundUploadController.java deleted file mode 100644 index 572be54c4..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BackgroundUploadController.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.adityachandel.booklore.controller; - -import com.adityachandel.booklore.config.security.service.AuthenticationService; -import com.adityachandel.booklore.model.dto.BookLoreUser; -import com.adityachandel.booklore.model.dto.UploadResponse; -import com.adityachandel.booklore.model.dto.UrlRequest; -import com.adityachandel.booklore.service.file.BackgroundUploadService; -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 lombok.RequiredArgsConstructor; -import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; - -@Tag(name = "Background Upload", description = "Endpoints for uploading and managing background images") -@RestController -@RequestMapping("/api/v1/background") -@RequiredArgsConstructor -public class BackgroundUploadController { - - private final BackgroundUploadService backgroundUploadService; - private final AuthenticationService authenticationService; - - @Operation(summary = "Upload background image file", description = "Upload a new background image file for the authenticated user.") - @ApiResponse(responseCode = "200", description = "Background image uploaded successfully") - @PostMapping("/upload") - public ResponseEntity uploadFile(@Parameter(description = "Background image file") @RequestParam("file") MultipartFile file) { - try { - BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); - UploadResponse response = backgroundUploadService.uploadBackgroundFile(file, authenticatedUser.getId()); - return ResponseEntity.ok(response); - } catch (Exception e) { - return ResponseEntity.badRequest().build(); - } - } - - @Operation(summary = "Upload background image from URL", description = "Upload a new background image from a URL for the authenticated user.") - @ApiResponse(responseCode = "200", description = "Background image uploaded successfully") - @PostMapping("/url") - public ResponseEntity uploadUrl( - @Parameter(description = "URL request containing the image URL") @RequestBody UrlRequest request) { - try { - BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); - UploadResponse response = backgroundUploadService.uploadBackgroundFromUrl(request.getUrl(), authenticatedUser.getId()); - return ResponseEntity.ok(response); - } catch (Exception e) { - return ResponseEntity.badRequest().build(); - } - } - - @Operation(summary = "Reset background to default", description = "Reset the background image to the default for the authenticated user.") - @ApiResponse(responseCode = "200", description = "Background reset to default successfully") - @DeleteMapping - public ResponseEntity resetToDefault() { - try { - BookLoreUser authenticatedUser = authenticationService.getAuthenticatedUser(); - backgroundUploadService.resetToDefault(authenticatedUser.getId()); - return ResponseEntity.ok().build(); - } catch (Exception e) { - return ResponseEntity.internalServerError().build(); - } - } -} \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookCoverController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookCoverController.java new file mode 100644 index 000000000..646a52ac7 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/BookCoverController.java @@ -0,0 +1,104 @@ +package com.adityachandel.booklore.controller; + +import com.adityachandel.booklore.config.security.annotation.CheckBookAccess; +import com.adityachandel.booklore.model.dto.CoverImage; +import com.adityachandel.booklore.model.dto.request.BulkBookIdsRequest; +import com.adityachandel.booklore.model.dto.request.CoverFetchRequest; +import com.adityachandel.booklore.service.metadata.BookCoverService; +import com.adityachandel.booklore.service.metadata.DuckDuckGoCoverService; +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 lombok.AllArgsConstructor; +import org.springframework.http.ResponseEntity; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/api/v1/books") +@AllArgsConstructor +@Tag(name = "Book Metadata", description = "Endpoints for managing book metadata, covers, and metadata operations") +public class BookCoverController { + + private final BookCoverService bookCoverService; + private final DuckDuckGoCoverService duckDuckGoCoverService; + + @Operation(summary = "Upload cover image from file", description = "Upload a cover image for a book from a file. Requires metadata edit permission or admin.") + @ApiResponse(responseCode = "200", description = "Cover image uploaded successfully") + @PostMapping("/{bookId}/metadata/cover/upload") + @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") + @CheckBookAccess(bookIdParam = "bookId") + public void uploadCoverFromFile( + @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "Cover image file") @RequestParam("file") MultipartFile file) { + bookCoverService.updateCoverFromFile(bookId, file); + } + + @Operation(summary = "Upload cover image from URL", description = "Upload a cover image for a book from a URL. Requires metadata edit permission or admin.") + @ApiResponse(responseCode = "200", description = "Cover image uploaded successfully") + @PostMapping("/{bookId}/metadata/cover/from-url") + @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") + @CheckBookAccess(bookIdParam = "bookId") + public void uploadCoverFromUrl( + @Parameter(description = "ID of the book") @PathVariable Long bookId, + @Parameter(description = "URL body") @RequestBody Map body) { + bookCoverService.updateCoverFromUrl(bookId, body.get("url")); + } + + @Operation(summary = "Regenerate all covers", description = "Regenerate covers for all books. Requires metadata edit permission or admin.") + @ApiResponse(responseCode = "204", description = "Covers regenerated successfully") + @PostMapping("/regenerate-covers") + @PreAuthorize("@securityUtil.canBulkRegenerateCover() or @securityUtil.isAdmin()") + public void regenerateCovers() { + bookCoverService.regenerateCovers(); + } + + @Operation(summary = "Regenerate cover for a book", description = "Regenerate cover for a specific book. Requires metadata edit permission or admin.") + @ApiResponse(responseCode = "204", description = "Cover regenerated successfully") + @PostMapping("/{bookId}/regenerate-cover") + @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") + @CheckBookAccess(bookIdParam = "bookId") + public void regenerateCovers(@Parameter(description = "ID of the book") @PathVariable Long bookId) { + bookCoverService.regenerateCover(bookId); + } + + @Operation(summary = "Generate custom cover for a book", description = "Generate a custom cover for a specific book based on its metadata. Requires metadata edit permission or admin.") + @ApiResponse(responseCode = "204", description = "Custom cover generated successfully") + @PostMapping("/{bookId}/generate-custom-cover") + @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") + @CheckBookAccess(bookIdParam = "bookId") + public void generateCustomCover(@Parameter(description = "ID of the book") @PathVariable Long bookId) { + bookCoverService.generateCustomCover(bookId); + } + + @Operation(summary = "Regenerate covers for selected books", description = "Regenerate covers for a list of books. Requires metadata edit permission or admin.") + @ApiResponse(responseCode = "204", description = "Cover regeneration started successfully") + @PostMapping("/bulk-regenerate-covers") + @PreAuthorize("@securityUtil.canBulkRegenerateCover() or @securityUtil.isAdmin()") + public void regenerateCoversForBooks(@Parameter(description = "List of book IDs") @Validated @RequestBody BulkBookIdsRequest request) { + bookCoverService.regenerateCoversForBooks(request.getBookIds()); + } + + @Operation(summary = "Upload cover image for multiple books", description = "Upload a cover image to apply to multiple books. Requires metadata edit permission or admin.") + @ApiResponse(responseCode = "204", description = "Cover upload started successfully") + @PostMapping("/bulk-upload-cover") + @PreAuthorize("@securityUtil.canBulkEditMetadata() or @securityUtil.isAdmin()") + public void bulkUploadCover( + @Parameter(description = "Cover image file") @RequestParam("file") MultipartFile file, + @Parameter(description = "Comma-separated book IDs") @RequestParam("bookIds") @jakarta.validation.constraints.NotEmpty java.util.Set bookIds) { + bookCoverService.updateCoverFromFileForBooks(bookIds, file); + } + + @Operation(summary = "Get cover images for a book", description = "Fetch cover images for a book.") + @ApiResponse(responseCode = "200", description = "Cover images returned successfully") + @PostMapping("/{bookId}/metadata/covers") + public ResponseEntity> getImages(@Parameter(description = "Cover fetch request") @RequestBody CoverFetchRequest request) { + return ResponseEntity.ok(duckDuckGoCoverService.getCovers(request)); + } +} \ No newline at end of file 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 1064db60e..77660ccdb 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 @@ -91,36 +91,4 @@ public class BookMediaController { .body(file) : ResponseEntity.noContent().build(); } - - @Operation(summary = "Get background image", description = "Retrieve the current background image for the authenticated user.") - @ApiResponse(responseCode = "200", description = "Background image returned successfully") - @GetMapping("/background") - public ResponseEntity getBackgroundImage() { - try { - Resource file = bookService.getBackgroundImage(); - if (file == null || !file.exists()) { - return ResponseEntity.notFound().build(); - } - - String filename = file.getFilename(); - MediaType mediaType = filename != null && filename.endsWith(".png") - ? MediaType.IMAGE_PNG - : MediaType.IMAGE_JPEG; - - if (filename == null) { - return ResponseEntity.badRequest().build(); - } - - String encodedFilename = URLEncoder.encode(filename, StandardCharsets.UTF_8).replace("+", "%20"); - String fallbackFilename = NON_ASCII_PATTERN.matcher(filename).replaceAll("_"); - String contentDisposition = String.format("inline; filename=\"%s\"; filename*=UTF-8''%s", - fallbackFilename, encodedFilename); - return ResponseEntity.ok() - .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition) - .contentType(mediaType) - .body(file); - } catch (Exception e) { - return ResponseEntity.internalServerError().build(); - } - } } \ No newline at end of file diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/MetadataController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/MetadataController.java index ad3bd6aef..ee797e06a 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/controller/MetadataController.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/MetadataController.java @@ -6,12 +6,14 @@ import com.adityachandel.booklore.mapper.BookMetadataMapper; import com.adityachandel.booklore.model.MetadataUpdateContext; import com.adityachandel.booklore.model.MetadataUpdateWrapper; import com.adityachandel.booklore.model.dto.BookMetadata; -import com.adityachandel.booklore.model.dto.CoverImage; import com.adityachandel.booklore.model.dto.request.*; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.enums.MetadataReplaceMode; import com.adityachandel.booklore.repository.BookRepository; -import com.adityachandel.booklore.service.metadata.*; +import com.adityachandel.booklore.service.metadata.BookMetadataService; +import com.adityachandel.booklore.service.metadata.BookMetadataUpdater; +import com.adityachandel.booklore.service.metadata.MetadataManagementService; +import com.adityachandel.booklore.service.metadata.MetadataMatchService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.responses.ApiResponse; @@ -22,11 +24,9 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; -import org.springframework.web.multipart.MultipartFile; import reactor.core.publisher.Flux; import java.util.List; -import java.util.Map; @RestController @RequestMapping("/api/v1/books") @@ -38,7 +38,6 @@ public class MetadataController { private final BookMetadataUpdater bookMetadataUpdater; private final BookMetadataMapper bookMetadataMapper; private final MetadataMatchService metadataMatchService; - private final DuckDuckGoCoverService duckDuckGoCoverService; private final BookRepository bookRepository; private final MetadataManagementService metadataManagementService; @@ -86,8 +85,7 @@ public class MetadataController { @ApiResponse(responseCode = "204", description = "Bulk metadata updated successfully") @PutMapping("/bulk-edit-metadata") @PreAuthorize("@securityUtil.canBulkEditMetadata() or @securityUtil.isAdmin()") - public ResponseEntity bulkEditMetadata( - @Parameter(description = "Bulk metadata update request") @RequestBody BulkMetadataUpdateRequest bulkMetadataUpdateRequest) { + public ResponseEntity bulkEditMetadata(@Parameter(description = "Bulk metadata update request") @RequestBody BulkMetadataUpdateRequest bulkMetadataUpdateRequest) { boolean mergeCategories = bulkMetadataUpdateRequest.isMergeCategories(); boolean mergeMoods = bulkMetadataUpdateRequest.isMergeMoods(); boolean mergeTags = bulkMetadataUpdateRequest.isMergeTags(); @@ -95,36 +93,11 @@ public class MetadataController { return ResponseEntity.noContent().build(); } - @Operation(summary = "Upload cover image from file", description = "Upload a cover image for a book from a file. Requires metadata edit permission or admin.") - @ApiResponse(responseCode = "200", description = "Cover image uploaded successfully") - @PostMapping("/{bookId}/metadata/cover/upload") - @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") - @CheckBookAccess(bookIdParam = "bookId") - public ResponseEntity uploadCoverFromFile( - @Parameter(description = "ID of the book") @PathVariable Long bookId, - @Parameter(description = "Cover image file") @RequestParam("file") MultipartFile file) { - BookMetadata updated = bookMetadataService.updateCoverImageFromFile(bookId, file); - return ResponseEntity.ok(updated); - } - - @Operation(summary = "Upload cover image from URL", description = "Upload a cover image for a book from a URL. Requires metadata edit permission or admin.") - @ApiResponse(responseCode = "200", description = "Cover image uploaded successfully") - @PostMapping("/{bookId}/metadata/cover/from-url") - @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") - @CheckBookAccess(bookIdParam = "bookId") - public ResponseEntity uploadCoverFromUrl( - @Parameter(description = "ID of the book") @PathVariable Long bookId, - @Parameter(description = "URL body") @RequestBody Map body) { - BookMetadata updated = bookMetadataService.updateCoverImageFromUrl(bookId, body.get("url")); - return ResponseEntity.ok(updated); - } - @Operation(summary = "Toggle all metadata locks", description = "Toggle all metadata locks for books. Requires metadata edit permission or admin.") @ApiResponse(responseCode = "200", description = "Metadata locks toggled successfully") @PutMapping("/metadata/toggle-all-lock") @PreAuthorize("@securityUtil.canBulkLockUnlockMetadata() or @securityUtil.isAdmin()") - public ResponseEntity> toggleAllMetadata( - @Parameter(description = "Toggle all lock request") @RequestBody ToggleAllLockRequest request) { + public ResponseEntity> toggleAllMetadata(@Parameter(description = "Toggle all lock request") @RequestBody ToggleAllLockRequest request) { return ResponseEntity.ok(bookMetadataService.toggleAllLock(request)); } @@ -132,61 +105,11 @@ public class MetadataController { @ApiResponse(responseCode = "200", description = "Field locks toggled successfully") @PutMapping("/metadata/toggle-field-locks") @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") - public ResponseEntity> toggleFieldLocks( - @Parameter(description = "Toggle field locks request") @RequestBody ToggleFieldLocksRequest request) { + public ResponseEntity> toggleFieldLocks(@Parameter(description = "Toggle field locks request") @RequestBody ToggleFieldLocksRequest request) { bookMetadataService.toggleFieldLocks(request.getBookIds(), request.getFieldActions()); return ResponseEntity.ok().build(); } - @Operation(summary = "Regenerate all covers", description = "Regenerate covers for all books. Requires metadata edit permission or admin.") - @ApiResponse(responseCode = "204", description = "Covers regenerated successfully") - @PostMapping("/regenerate-covers") - @PreAuthorize("@securityUtil.canBulkRegenerateCover() or @securityUtil.isAdmin()") - public void regenerateCovers() { - bookMetadataService.regenerateCovers(); - } - - @Operation(summary = "Regenerate cover for a book", description = "Regenerate cover for a specific book. Requires metadata edit permission or admin.") - @ApiResponse(responseCode = "204", description = "Cover regenerated successfully") - @PostMapping("/{bookId}/regenerate-cover") - @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") - @CheckBookAccess(bookIdParam = "bookId") - public void regenerateCovers( - @Parameter(description = "ID of the book") @PathVariable Long bookId) { - bookMetadataService.regenerateCover(bookId); - } - - @Operation(summary = "Generate custom cover for a book", description = "Generate a custom cover for a specific book based on its metadata. Requires metadata edit permission or admin.") - @ApiResponse(responseCode = "204", description = "Custom cover generated successfully") - @PostMapping("/{bookId}/generate-custom-cover") - @PreAuthorize("@securityUtil.canEditMetadata() or @securityUtil.isAdmin()") - @CheckBookAccess(bookIdParam = "bookId") - public void generateCustomCover( - @Parameter(description = "ID of the book") @PathVariable Long bookId) { - bookMetadataService.generateCustomCover(bookId); - } - - @Operation(summary = "Regenerate covers for selected books", description = "Regenerate covers for a list of books. Requires metadata edit permission or admin.") - @ApiResponse(responseCode = "204", description = "Cover regeneration started successfully") - @PostMapping("/bulk-regenerate-covers") - @PreAuthorize("@securityUtil.canBulkRegenerateCover() or @securityUtil.isAdmin()") - public ResponseEntity regenerateCoversForBooks( - @Parameter(description = "List of book IDs") @Validated @RequestBody BulkBookIdsRequest request) { - bookMetadataService.regenerateCoversForBooks(request.getBookIds()); - return ResponseEntity.noContent().build(); - } - - @Operation(summary = "Upload cover image for multiple books", description = "Upload a cover image to apply to multiple books. Requires metadata edit permission or admin.") - @ApiResponse(responseCode = "204", description = "Cover upload started successfully") - @PostMapping("/bulk-upload-cover") - @PreAuthorize("@securityUtil.canBulkEditMetadata() or @securityUtil.isAdmin()") - public ResponseEntity bulkUploadCover( - @Parameter(description = "Cover image file") @RequestParam("file") MultipartFile file, - @Parameter(description = "Comma-separated book IDs") @RequestParam("bookIds") @RequestBody java.util.Set bookIds) { - bookMetadataService.updateCoverImageFromFileForBooks(bookIds, file); - return ResponseEntity.noContent().build(); - } - @Operation(summary = "Recalculate metadata match scores", description = "Recalculate match scores for all metadata. Requires admin.") @ApiResponse(responseCode = "204", description = "Match scores recalculated successfully") @PostMapping("/metadata/recalculate-match-scores") @@ -196,20 +119,11 @@ public class MetadataController { return ResponseEntity.noContent().build(); } - @Operation(summary = "Get cover images for a book", description = "Fetch cover images for a book.") - @ApiResponse(responseCode = "200", description = "Cover images returned successfully") - @PostMapping("/{bookId}/metadata/covers") - public ResponseEntity> getImages( - @Parameter(description = "Cover fetch request") @RequestBody CoverFetchRequest request) { - return ResponseEntity.ok(duckDuckGoCoverService.getCovers(request)); - } - @Operation(summary = "Consolidate metadata", description = "Merge metadata values. Requires metadata edit permission or admin.") @ApiResponse(responseCode = "204", description = "Metadata consolidated successfully") @PostMapping("/metadata/manage/consolidate") @PreAuthorize("@securityUtil.canBulkEditMetadata() or @securityUtil.isAdmin()") - public ResponseEntity mergeMetadata( - @Parameter(description = "Merge metadata request") @Validated @RequestBody MergeMetadataRequest request) { + public ResponseEntity mergeMetadata(@Parameter(description = "Merge metadata request") @Validated @RequestBody MergeMetadataRequest request) { metadataManagementService.consolidateMetadata(request.getMetadataType(), request.getTargetValues(), request.getValuesToMerge()); return ResponseEntity.noContent().build(); } @@ -218,8 +132,7 @@ public class MetadataController { @ApiResponse(responseCode = "204", description = "Metadata deleted successfully") @PostMapping("/metadata/manage/delete") @PreAuthorize("@securityUtil.canBulkEditMetadata() or @securityUtil.isAdmin()") - public ResponseEntity deleteMetadata( - @Parameter(description = "Delete metadata request") @Validated @RequestBody DeleteMetadataRequest request) { + public ResponseEntity deleteMetadata(@Parameter(description = "Delete metadata request") @Validated @RequestBody DeleteMetadataRequest request) { metadataManagementService.deleteMetadata(request.getMetadataType(), request.getValuesToDelete()); return ResponseEntity.noContent().build(); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java index 7a8a6be43..606c36ba1 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/AppSettingKey.java @@ -20,7 +20,7 @@ public enum AppSettingKey { LIBRARY_METADATA_REFRESH_OPTIONS ("library_metadata_refresh_options", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), METADATA_PROVIDER_SETTINGS ("metadata_provider_settings", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), METADATA_MATCH_WEIGHTS ("metadata_match_weights", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), - METADATA_PERSISTENCE_SETTINGS ("metadata_persistence_settings", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), + METADATA_PERSISTENCE_SETTINGS ("metadata_persistence_settings_v2", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), METADATA_PUBLIC_REVIEWS_SETTINGS ("metadata_public_reviews_settings", true, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), UPLOAD_FILE_PATTERN ("upload_file_pattern", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), MOVE_FILE_PATTERN ("move_file_pattern", false, false, List.of(PermissionType.ADMIN, PermissionType.MANAGE_METADATA_CONFIG)), diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/MetadataPersistenceSettings.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/MetadataPersistenceSettings.java index 6d296a2d9..907270f73 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/MetadataPersistenceSettings.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/MetadataPersistenceSettings.java @@ -10,7 +10,30 @@ import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor public class MetadataPersistenceSettings { - private boolean saveToOriginalFile; + private SaveToOriginalFile saveToOriginalFile; private boolean convertCbrCb7ToCbz; private boolean moveFilesToLibraryPattern; + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class SaveToOriginalFile { + private FormatSettings epub; + private FormatSettings pdf; + private FormatSettings cbx; + + public boolean isAnyFormatEnabled() { + return (epub != null && epub.isEnabled()) || (pdf != null && pdf.isEnabled() || (cbx != null && cbx.isEnabled())); + } + } + + @Data + @Builder + @NoArgsConstructor + @AllArgsConstructor + public static class FormatSettings { + private boolean enabled; + private int maxFileSizeInMb; + } } 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 f063b20da..a360e48e4 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 @@ -3,6 +3,7 @@ package com.adityachandel.booklore.repository; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.LibraryPathEntity; import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.repository.projection.BookCoverUpdateProjection; import jakarta.transaction.Transactional; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.*; @@ -143,4 +144,7 @@ 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.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/projection/BookCoverUpdateProjection.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/projection/BookCoverUpdateProjection.java new file mode 100644 index 000000000..0ff9023c8 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/projection/BookCoverUpdateProjection.java @@ -0,0 +1,9 @@ +package com.adityachandel.booklore.repository.projection; + +import java.time.Instant; + +public interface BookCoverUpdateProjection { + Long getId(); + Instant getCoverUpdatedOn(); +} + 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 47c0e3d55..3d56df255 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 @@ -104,7 +104,7 @@ public class TelemetryService { .metadataStatistics(BookloreTelemetry.MetadataStatistics.builder() .enabledMetadataProviders(enabledMetadataProviders) .enabledReviewMetadataProviders(enabledReviewMetadataProviders) - .saveMetadataToFile(settings.getMetadataPersistenceSettings().isSaveToOriginalFile()) + .saveMetadataToFile(settings.getMetadataPersistenceSettings().getSaveToOriginalFile().isAnyFormatEnabled()) .moveFileViaPattern(settings.getMetadataPersistenceSettings().isMoveFilesToLibraryPattern()) .autoBookSearchEnabled(settings.isAutoBookSearch()) .similarBookRecommendationsEnabled(settings.isSimilarBookRecommendation()) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/SettingPersistenceHelper.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/SettingPersistenceHelper.java index cdbfbf0c6..ce1de3c33 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/SettingPersistenceHelper.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/appsettings/SettingPersistenceHelper.java @@ -9,6 +9,7 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.Map; @@ -16,6 +17,7 @@ import java.util.Set; @Service @RequiredArgsConstructor +@Slf4j public class SettingPersistenceHelper { public final AppSettingsRepository appSettingsRepository; @@ -52,14 +54,15 @@ public class SettingPersistenceHelper { try { return deserializer.deserialize(json); } catch (JsonProcessingException e) { - throw new RuntimeException("Failed to parse " + key, e); + log.error("Failed to parse JSON for setting key '{}'. Using default value. Error: {}", key, e.getMessage()); + return defaultValue; } } if (defaultValue != null && persistDefault) { try { saveDefaultSetting(key, objectMapper.writeValueAsString(defaultValue)); } catch (JsonProcessingException e) { - throw new RuntimeException("Failed to persist default for " + key, e); + log.error("Failed to persist default value for setting key '{}'. Error: {}", key, e.getMessage()); } } return defaultValue; @@ -218,8 +221,29 @@ public class SettingPersistenceHelper { } public MetadataPersistenceSettings getDefaultMetadataPersistenceSettings() { + MetadataPersistenceSettings.FormatSettings epubSettings = MetadataPersistenceSettings.FormatSettings.builder() + .enabled(false) + .maxFileSizeInMb(250) + .build(); + + MetadataPersistenceSettings.FormatSettings pdfSettings = MetadataPersistenceSettings.FormatSettings.builder() + .enabled(false) + .maxFileSizeInMb(250) + .build(); + + MetadataPersistenceSettings.FormatSettings cbxSettings = MetadataPersistenceSettings.FormatSettings.builder() + .enabled(false) + .maxFileSizeInMb(250) + .build(); + + MetadataPersistenceSettings.SaveToOriginalFile saveToOriginalFile = MetadataPersistenceSettings.SaveToOriginalFile.builder() + .epub(epubSettings) + .pdf(pdfSettings) + .cbx(cbxSettings) + .build(); + return MetadataPersistenceSettings.builder() - .saveToOriginalFile(false) + .saveToOriginalFile(saveToOriginalFile) .convertCbrCb7ToCbz(false) .moveFilesToLibraryPattern(false) .build(); 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 0e3e71d5c..11b3f797a 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 @@ -293,16 +293,6 @@ public class BookService { return getBookCover(bookEntity.getId()); } - public Resource getBackgroundImage() { - try { - BookLoreUser user = authenticationService.getAuthenticatedUser(); - return fileService.getBackgroundResource(user.getId()); - } catch (Exception e) { - log.error("Failed to get background image: {}", e.getMessage(), e); - return fileService.getBackgroundResource(null); - } - } - public ResponseEntity downloadBook(Long bookId) { return bookDownloadService.downloadBook(bookId); } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java deleted file mode 100644 index b61f19e01..000000000 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/file/BackgroundUploadService.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.adityachandel.booklore.service.file; - -import com.adityachandel.booklore.model.dto.UploadResponse; -import com.adityachandel.booklore.util.FileService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Service; -import org.springframework.web.multipart.MultipartFile; - -import javax.imageio.ImageIO; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.io.InputStream; -import java.net.URI; -import java.net.URL; -import java.nio.file.Paths; -import java.util.Objects; - -import static net.lingala.zip4j.util.FileUtils.getFileExtension; - -@Slf4j -@Service -@RequiredArgsConstructor -public class BackgroundUploadService { - - private final FileService fileService; - - private static final String JPEG_MIME_TYPE = "image/jpeg"; - private static final String PNG_MIME_TYPE = "image/png"; - private static final long MAX_FILE_SIZE_BYTES = 5L * 1024 * 1024; // 5MB - - public UploadResponse uploadBackgroundFile(MultipartFile file, Long userId) { - try { - validateBackgroundFile(file); - - String originalFilename = Objects.requireNonNull(file.getOriginalFilename()); - String extension = getFileExtension(originalFilename); - String filename = "1." + extension; - - try (InputStream inputStream = file.getInputStream()) { - BufferedImage originalImage; - try { - originalImage = FileService.readImage(inputStream); - } catch (IOException e) { - originalImage = null; - } - - if (originalImage == null) { - throw new IllegalArgumentException("Invalid image file"); - } - - - deleteExistingBackgroundFiles(userId); - fileService.saveBackgroundImage(originalImage, filename, userId); - originalImage.flush(); // Release resources after saving - - String fileUrl = FileService.getBackgroundUrl(filename, userId); - return new UploadResponse(fileUrl); - } - } catch (Exception e) { - log.error("Failed to upload background file: {}", e.getMessage(), e); - throw new RuntimeException("Failed to upload file: " + e.getMessage(), e); - } - } - - public UploadResponse uploadBackgroundFromUrl(String imageUrl, Long userId) { - try { - URL url = new URI(imageUrl).toURL(); - String originalFilename = Paths.get(url.getPath()).getFileName().toString(); - String extension = getFileExtension(originalFilename); - String filename = "1." + extension; - - BufferedImage originalImage = fileService.downloadImageFromUrl(imageUrl); - if (originalImage == null) { - throw new IllegalArgumentException("Failed to download or decode image from URL"); - } - deleteExistingBackgroundFiles(userId); - - fileService.saveBackgroundImage(originalImage, filename, userId); - originalImage.flush(); // Release resources after saving - - String fileUrl = FileService.getBackgroundUrl(filename, userId); - return new UploadResponse(fileUrl); - } catch (Exception e) { - log.error("Failed to upload background from URL: {}", e.getMessage(), e); - throw new RuntimeException("Invalid or inaccessible URL: " + e.getMessage(), e); - } - } - - public void resetToDefault(Long userId) { - try { - deleteExistingBackgroundFiles(userId); - log.info("Reset background to default successfully for user: {}", userId); - } catch (Exception e) { - log.error("Failed to reset background to default: {}", e.getMessage(), e); - throw new RuntimeException("Failed to reset background: " + e.getMessage(), e); - } - } - - private void deleteExistingBackgroundFiles(Long userId) { - try { - fileService.deleteBackgroundFile("1.jpg", userId); - fileService.deleteBackgroundFile("1.jpeg", userId); - fileService.deleteBackgroundFile("1.png", userId); - } catch (Exception e) { - log.warn("Failed to delete existing background files: {}", e.getMessage()); - } - } - - private void validateBackgroundFile(MultipartFile file) { - if (file.isEmpty()) { - throw new IllegalArgumentException("Background image file is empty"); - } - String contentType = file.getContentType(); - if (!(JPEG_MIME_TYPE.equalsIgnoreCase(contentType) || PNG_MIME_TYPE.equalsIgnoreCase(contentType))) { - throw new IllegalArgumentException("Background image must be JPEG or PNG format"); - } - if (file.getSize() > MAX_FILE_SIZE_BYTES) { - throw new IllegalArgumentException("Background image size must not exceed 5 MB"); - } - } - - private String getFileExtension(String filename) { - int lastDotIndex = filename.lastIndexOf('.'); - if (lastDotIndex > 0 && lastDotIndex < filename.length() - 1) { - return filename.substring(lastDotIndex + 1).toLowerCase(); - } - return "jpg"; - } -} 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 e0ff82586..adeb06429 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 @@ -1,8 +1,6 @@ package com.adityachandel.booklore.service.metadata; import com.adityachandel.booklore.exception.ApiError; -import com.adityachandel.booklore.mapper.BookMetadataMapper; -import com.adityachandel.booklore.model.dto.BookMetadata; import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; import com.adityachandel.booklore.model.entity.AuthorEntity; import com.adityachandel.booklore.model.entity.BookEntity; @@ -10,6 +8,7 @@ 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.BookRepository; +import com.adityachandel.booklore.repository.projection.BookCoverUpdateProjection; import com.adityachandel.booklore.service.NotificationService; import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.service.book.BookQueryService; @@ -29,7 +28,9 @@ import org.springframework.transaction.support.TransactionTemplate; import org.springframework.web.multipart.MultipartFile; import java.time.Instant; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Collectors; @@ -41,7 +42,6 @@ public class BookCoverService { private static final int BATCH_SIZE = 100; private final BookRepository bookRepository; - private final BookMetadataMapper bookMetadataMapper; private final NotificationService notificationService; private final AppSettingService appSettingService; private final FileService fileService; @@ -54,7 +54,7 @@ public class BookCoverService { private record BookCoverInfo(Long id, String title) { } - private record BookRegenerationInfo(Long id, String title, BookFileType bookType) { + private record BookRegenerationInfo(Long id, String title, BookFileType bookType, boolean coverLocked) { } // ========================= @@ -66,13 +66,17 @@ public class BookCoverService { */ public void generateCustomCover(long bookId) { BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + if (isCoverLocked(bookEntity)) { throw ApiError.METADATA_LOCKED.createException(); } + String title = bookEntity.getMetadata().getTitle(); String author = getAuthorNames(bookEntity); byte[] coverBytes = coverImageGenerator.generateCover(title, author); + fileService.createThumbnailFromBytes(bookId, coverBytes); + writeCoverToBookFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromBytes(book, coverBytes)); updateBookCoverMetadata(bookEntity); bookRepository.save(bookEntity); notifyBookCoverUpdate(bookEntity); @@ -82,24 +86,42 @@ public class BookCoverService { * Update cover image from uploaded file for a single book. */ @Transactional - public BookMetadata updateCoverImageFromFile(Long bookId, MultipartFile file) { + public void updateCoverFromFile(Long bookId, MultipartFile file) { + BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + + if (isCoverLocked(bookEntity)) { + throw ApiError.METADATA_LOCKED.createException(); + } + fileService.createThumbnailFromFile(bookId, file); - return updateCover(bookId, (writer, book) -> writer.replaceCoverImageFromUpload(book, file)); + writeCoverToBookFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromUpload(book, file)); + updateBookCoverMetadata(bookEntity); + bookRepository.save(bookEntity); + notifyBookCoverUpdate(bookEntity); } /** * Update cover image from a URL for a single book. */ @Transactional - public BookMetadata updateCoverImageFromUrl(Long bookId, String url) { + public void updateCoverFromUrl(Long bookId, String url) { + BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); + + if (isCoverLocked(bookEntity)) { + throw ApiError.METADATA_LOCKED.createException(); + } + fileService.createThumbnailFromUrl(bookId, url); - return updateCover(bookId, (writer, book) -> writer.replaceCoverImageFromUrl(book, url)); + writeCoverToBookFile(bookEntity, (writer, book) -> writer.replaceCoverImageFromUrl(book, url)); + updateBookCoverMetadata(bookEntity); + bookRepository.save(bookEntity); + notifyBookCoverUpdate(bookEntity); } /** * Bulk update cover images from a file for multiple books. */ - public void updateCoverImageFromFileForBooks(Set bookIds, MultipartFile file) { + public void updateCoverFromFileForBooks(Set bookIds, MultipartFile file) { validateCoverFile(file); byte[] coverImageBytes = extractBytesFromMultipartFile(file); List unlockedBooks = getUnlockedBookCoverInfos(bookIds); @@ -118,7 +140,11 @@ public class BookCoverService { if (isCoverLocked(bookEntity)) { throw ApiError.METADATA_LOCKED.createException(); } - regenerateCoverForBook(bookEntity, ""); + BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookEntity.getBookType()); + boolean success = processor.generateCover(bookEntity); + if (!success) { + throw ApiError.FAILED_TO_REGENERATE_COVER.createException(); + } updateBookCoverMetadata(bookEntity); bookRepository.save(bookEntity); } @@ -137,22 +163,44 @@ public class BookCoverService { public void regenerateCovers() { SecurityContextVirtualThread.runWithSecurityContext(() -> { try { - List books = bookQueryService.getAllFullBookEntities().stream() + List books = bookQueryService.getAllFullBookEntities().stream() .filter(book -> !isCoverLocked(book)) + .map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getBookType(), false)) .toList(); int total = books.size(); notificationService.sendMessage(Topic.LOG, LogNotification.info("Started regenerating covers for " + total + " books")); int current = 1; - for (BookEntity book : books) { + List refreshedIds = new ArrayList<>(); + + for (BookRegenerationInfo bookInfo : books) { try { String progress = "(" + current + "/" + total + ") "; - regenerateCoverForBook(book, progress); + notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title())); + + transactionTemplate.execute(status -> { + bookRepository.findById(bookInfo.id()).ifPresent(book -> { + BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookInfo.bookType()); + boolean success = processor.generateCover(book); + + if (success) { + updateBookCoverMetadata(book); + bookRepository.save(book); + refreshedIds.add(book.getId()); + log.info("{}Successfully regenerated cover for book ID {} ({})", progress, book.getId(), bookInfo.title()); + } else { + log.warn("{}Failed to regenerate cover for book ID {} ({})", progress, book.getId(), bookInfo.title()); + } + }); + return null; + }); } catch (Exception e) { - log.error("Failed to regenerate cover for book ID {}: {}", book.getId(), e.getMessage(), e); + log.error("Failed to regenerate cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e); } current++; } + + notifyBulkCoverUpdate(refreshedIds); notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished regenerating covers")); } catch (Exception e) { log.error("Error during cover regeneration: {}", e.getMessage(), e); @@ -171,24 +219,32 @@ public class BookCoverService { notificationService.sendMessage(Topic.LOG, LogNotification.info("Started updating covers for " + total + " selected book(s)")); int current = 1; + List refreshedIds = new ArrayList<>(); + for (BookCoverInfo bookInfo : books) { try { String progress = "(" + current + "/" + total + ") "; notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Updating cover for: " + bookInfo.title())); - fileService.createThumbnailFromBytes(bookInfo.id(), coverImageBytes); - bookRepository.findById(bookInfo.id()).ifPresent(book -> { - updateBookCoverMetadata(book); - bookRepository.save(book); + transactionTemplate.execute(status -> { + bookRepository.findById(bookInfo.id()).ifPresent(book -> { + fileService.createThumbnailFromBytes(bookInfo.id(), coverImageBytes); + writeCoverToBookFile(book, (writer, b) -> writer.replaceCoverImageFromBytes(b, coverImageBytes)); + updateBookCoverMetadata(book); + bookRepository.save(book); + refreshedIds.add(book.getId()); + }); + return null; }); log.info("{}Successfully updated cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title()); } catch (Exception e) { log.error("Failed to update cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e); } - pauseAfterBatchIfNeeded(current, total); current++; } + + notifyBulkCoverUpdate(refreshedIds); notificationService.sendMessage(Topic.LOG, LogNotification.info("Finished updating covers for selected books")); } catch (Exception e) { log.error("Error during cover update: {}", e.getMessage(), e); @@ -208,13 +264,25 @@ public class BookCoverService { try { String progress = "(" + current + "/" + total + ") "; notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + bookInfo.title())); - regenerateCoverForBookId(bookInfo); + + transactionTemplate.execute(status -> { + bookRepository.findById(bookInfo.id()).ifPresent(book -> { + BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookInfo.bookType()); + boolean success = processor.generateCover(book); + + if (success) { + updateBookCoverMetadata(book); + bookRepository.save(book); + refreshedIds.add(book.getId()); + } + }); + return null; + }); + log.info("{}Successfully regenerated cover for book ID {} ({})", progress, bookInfo.id(), bookInfo.title()); - refreshedIds.add(bookInfo.id()); } catch (Exception e) { log.error("Failed to regenerate cover for book ID {}: {}", bookInfo.id(), e.getMessage(), e); } - pauseAfterBatchIfNeeded(current, total); current++; } @@ -230,56 +298,6 @@ public class BookCoverService { // SECTION: INTERNAL HELPERS // ========================= - private BookMetadata updateCover(Long bookId, BiConsumer writerAction) { - BookEntity bookEntity = bookRepository.findAllWithMetadataByIds(Collections.singleton(bookId)).stream() - .findFirst() - .orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); - - MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings(); - boolean saveToOriginalFile = settings.isSaveToOriginalFile(); - boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz(); - - if (saveToOriginalFile && (bookEntity.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) { - metadataWriterFactory.getWriter(bookEntity.getBookType()) - .ifPresent(writer -> { - writerAction.accept(writer, bookEntity); - String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath()); - bookEntity.setCurrentHash(newHash); - }); - } - - bookEntity.setMetadataUpdatedAt(Instant.now()); - updateBookCoverMetadata(bookEntity); - bookRepository.save(bookEntity); - return bookMetadataMapper.toBookMetadata(bookEntity.getMetadata(), true); - } - - private void regenerateCoverForBook(BookEntity book, String progress) { - String title = book.getMetadata().getTitle(); - notificationService.sendMessage(Topic.LOG, LogNotification.info(progress + "Regenerating cover for: " + title)); - - BookFileProcessor processor = processorRegistry.getProcessorOrThrow(book.getBookType()); - boolean success = processor.generateCover(book); - - if (success) { - Instant now = Instant.now(); - book.getMetadata().setCoverUpdatedOn(now); - book.setBookCoverHash(BookCoverUtils.generateCoverHash()); - } - - log.info("{} regenerated cover regeneration for book ID {} ({}) finished with success={}", progress, book.getId(), title, success); - if (!success) { - throw ApiError.FAILED_TO_REGENERATE_COVER.createException(); - } - } - - private void regenerateCoverForBookId(BookRegenerationInfo bookInfo) { - bookRepository.findById(bookInfo.id()).ifPresent(book -> { - BookFileProcessor processor = processorRegistry.getProcessorOrThrow(bookInfo.bookType()); - processor.generateCover(book); - }); - } - private void validateCoverFile(MultipartFile file) { if (file.isEmpty()) { throw ApiError.INVALID_INPUT.createException("Uploaded file is empty"); @@ -313,7 +331,7 @@ public class BookCoverService { private List getUnlockedBookRegenerationInfos(Set bookIds) { return bookQueryService.findAllWithMetadataByIds(bookIds).stream() .filter(book -> !isCoverLocked(book)) - .map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getBookType())) + .map(book -> new BookRegenerationInfo(book.getId(), book.getMetadata().getTitle(), book.getBookType(), false)) .toList(); } @@ -330,6 +348,20 @@ public class BookCoverService { return null; } + private void writeCoverToBookFile(BookEntity bookEntity, BiConsumer writerAction) { + MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings(); + boolean convertCbrCb7ToCbz = settings.isConvertCbrCb7ToCbz(); + + if ((bookEntity.getBookType() != BookFileType.CBX || convertCbrCb7ToCbz)) { + metadataWriterFactory.getWriter(bookEntity.getBookType()) + .ifPresent(writer -> { + writerAction.accept(writer, bookEntity); + String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath()); + bookEntity.setCurrentHash(newHash); + }); + } + } + private void updateBookCoverMetadata(BookEntity bookEntity) { Instant now = Instant.now(); bookEntity.setMetadataUpdatedAt(now); @@ -338,51 +370,19 @@ public class BookCoverService { } private void notifyBookCoverUpdate(BookEntity bookEntity) { - notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, List.of(Map.of( - "id", bookEntity.getId(), - "coverUpdatedOn", bookEntity.getMetadata().getCoverUpdatedOn() - ))); + List updates = bookRepository.findCoverUpdateInfoByIds(List.of(bookEntity.getId())); + if (!updates.isEmpty()) { + notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, updates); + } } private void notifyBulkCoverUpdate(List refreshedIds) { if (refreshedIds.isEmpty()) { return; } - - List> refreshedPatches = transactionTemplate.execute(status -> { - List entities = bookQueryService.findAllWithMetadataByIds(new HashSet<>(refreshedIds)); - if (entities == null || entities.isEmpty()) { - return List.>of(); - } - - entities.forEach(e -> { - if (e.getMetadata() != null) { - e.getMetadata().getCoverUpdatedOn(); - } - }); - - return entities.stream() - .map(e -> Map.of( - "id", e.getId(), - "coverUpdatedOn", e.getMetadata() == null ? null : e.getMetadata().getCoverUpdatedOn() - )) - .toList(); - }); - - if (refreshedPatches != null && !refreshedPatches.isEmpty()) { - notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, refreshedPatches); - } - } - - private void pauseAfterBatchIfNeeded(int current, int total) { - if (current % BATCH_SIZE == 0 && current < total) { - try { - log.info("Processed {} items, pausing briefly before next batch...", current); - Thread.sleep(1000); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - log.warn("Batch pause interrupted"); - } + List updates = bookRepository.findCoverUpdateInfoByIds(refreshedIds); + if (!updates.isEmpty()) { + notificationService.sendMessage(Topic.BOOKS_COVER_UPDATE, updates); } } } 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 3e24cafe2..c5bb2ca61 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 @@ -29,15 +29,14 @@ import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import org.springframework.web.multipart.MultipartFile; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import java.io.File; import java.lang.reflect.Method; -import java.util.*; -import java.util.concurrent.CompletableFuture; +import java.util.List; +import java.util.Map; import java.util.stream.Collectors; @Slf4j @@ -55,11 +54,7 @@ public class BookMetadataService { private final Map parserMap; private final CbxMetadataExtractor cbxMetadataExtractor; private final MetadataClearFlagsMapper metadataClearFlagsMapper; - private final BookCoverService bookCoverService; - public void generateCustomCover(long bookId) { - bookCoverService.generateCustomCover(bookId); - } public Flux getProspectiveMetadataListForBookId(long bookId, FetchMetadataRequest request) { BookEntity bookEntity = bookRepository.findById(bookId).orElseThrow(() -> ApiError.BOOK_NOT_FOUND.createException(bookId)); @@ -127,32 +122,6 @@ public class BookMetadataService { return books.stream().map(b -> bookMetadataMapper.toBookMetadata(b.getMetadata(), false)).collect(Collectors.toList()); } - @Transactional - public BookMetadata updateCoverImageFromFile(Long bookId, MultipartFile file) { - return bookCoverService.updateCoverImageFromFile(bookId, file); - } - - @Transactional - public BookMetadata updateCoverImageFromUrl(Long bookId, String url) { - return bookCoverService.updateCoverImageFromUrl(bookId, url); - } - - public void updateCoverImageFromFileForBooks(Set bookIds, MultipartFile file) { - bookCoverService.updateCoverImageFromFileForBooks(bookIds, file); - } - - public void regenerateCover(long bookId) { - bookCoverService.regenerateCover(bookId); - } - - public void regenerateCoversForBooks(Set bookIds) { - bookCoverService.regenerateCoversForBooks(bookIds); - } - - public void regenerateCovers() { - bookCoverService.regenerateCovers(); - } - 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)); 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 6b39b78f9..7002cdc50 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 @@ -85,7 +85,7 @@ public class BookMetadataUpdater { } MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings(); - boolean writeToFile = settings.isSaveToOriginalFile(); + MetadataPersistenceSettings.SaveToOriginalFile writeToFile = settings.getSaveToOriginalFile(); BookFileType bookType = bookEntity.getBookType(); boolean hasValueChangesForFileWrite = MetadataChangeDetector.hasValueChangesForFileWrite(newMetadata, metadata, clearFlags); @@ -108,7 +108,7 @@ public class BookMetadataUpdater { log.warn("Failed to calculate metadata match score for book ID {}: {}", bookId, e.getMessage()); } - if ((writeToFile && hasValueChangesForFileWrite) || thumbnailRequiresUpdate) { + if ((writeToFile.isAnyFormatEnabled() && hasValueChangesForFileWrite) || thumbnailRequiresUpdate) { metadataWriterFactory.getWriter(bookType).ifPresent(writer -> { try { String thumbnailUrl = updateThumbnail ? newMetadata.getThumbnailUrl() : null; @@ -117,7 +117,7 @@ public class BookMetadataUpdater { thumbnailUrl = null; } File file = new File(bookEntity.getFullFilePath().toUri()); - writer.writeMetadataToFile(file, metadata, thumbnailUrl, clearFlags); + writer.saveMetadataToFile(file, metadata, thumbnailUrl, clearFlags); String newHash = FileFingerprint.generateHash(bookEntity.getFullFilePath()); bookEntity.setMetadataForWriteUpdatedAt(Instant.now()); bookEntity.setCurrentHash(newHash); diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataManagementService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataManagementService.java index b7aec1e3d..4e4b70c93 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataManagementService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/MetadataManagementService.java @@ -41,16 +41,15 @@ public class MetadataManagementService { MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings(); boolean moveFile = settings.isMoveFilesToLibraryPattern(); - boolean writeToFile = settings.isSaveToOriginalFile(); switch (metadataType) { - case authors -> consolidateAuthors(targetValues, valuesToMerge, writeToFile, moveFile); - case categories -> consolidateCategories(targetValues, valuesToMerge, writeToFile, moveFile); - case moods -> consolidateMoods(targetValues, valuesToMerge, writeToFile, moveFile); - case tags -> consolidateTags(targetValues, valuesToMerge, writeToFile, moveFile); - case series -> consolidateSeries(targetValues, valuesToMerge, writeToFile, moveFile); - case publishers -> consolidatePublishers(targetValues, valuesToMerge, writeToFile, moveFile); - case languages -> consolidateLanguages(targetValues, valuesToMerge, writeToFile, moveFile); + case authors -> consolidateAuthors(targetValues, valuesToMerge, moveFile); + case categories -> consolidateCategories(targetValues, valuesToMerge, moveFile); + case moods -> consolidateMoods(targetValues, valuesToMerge, moveFile); + case tags -> consolidateTags(targetValues, valuesToMerge, moveFile); + case series -> consolidateSeries(targetValues, valuesToMerge, moveFile); + case publishers -> consolidatePublishers(targetValues, valuesToMerge, moveFile); + case languages -> consolidateLanguages(targetValues, valuesToMerge, moveFile); } } @@ -64,7 +63,7 @@ public class MetadataManagementService { Optional writerOpt = metadataWriterFactory.getWriter(bookType); if (writerOpt.isPresent()) { File file = book.getFullFilePath().toFile(); - writerOpt.get().writeMetadataToFile(file, metadata, null, null); + writerOpt.get().saveMetadataToFile(file, metadata, null, null); String newHash = FileFingerprint.generateHash(book.getFullFilePath()); book.setCurrentHash(newHash); bookModified = true; @@ -86,7 +85,7 @@ public class MetadataManagementService { } } - private void consolidateAuthors(List targetValues, List valuesToMerge, boolean writeToFile, boolean moveFile) { + private void consolidateAuthors(List targetValues, List valuesToMerge, boolean moveFile) { List targetAuthors = targetValues.stream() .map(name -> authorRepository.findByNameIgnoreCase(name) .map(existing -> { @@ -112,23 +111,19 @@ public class MetadataManagementService { for (BookMetadataEntity metadata : booksWithOldAuthor) { metadata.getAuthors().remove(oldAuthor); metadata.getAuthors().addAll(targetAuthors); - metadata.updateSearchText(); // Manually trigger search text update since collection modification doesn't trigger @PreUpdate + metadata.updateSearchText(); } bookMetadataRepository.saveAll(booksWithOldAuthor); bookMetadataRepository.flush(); - - if (writeToFile) { - writeMetadataToFile(booksWithOldAuthor, moveFile); - } - + writeMetadataToFile(booksWithOldAuthor, moveFile); authorRepository.delete(oldAuthor); } log.info("Consolidated {} authors into {}: {}", authorsToMerge.size(), targetValues, valuesToMerge); } - private void consolidateCategories(List targetValues, List valuesToMerge, boolean writeToFile, boolean moveFile) { + private void consolidateCategories(List targetValues, List valuesToMerge, boolean moveFile) { List targetCategories = targetValues.stream() .map(name -> categoryRepository.findByNameIgnoreCase(name) .map(existing -> { @@ -158,18 +153,14 @@ public class MetadataManagementService { bookMetadataRepository.saveAll(booksWithOldCategory); bookMetadataRepository.flush(); - - if (writeToFile) { - writeMetadataToFile(booksWithOldCategory, moveFile); - } - + writeMetadataToFile(booksWithOldCategory, moveFile); categoryRepository.delete(oldCategory); } log.info("Consolidated {} categories into {}: {}", categoriesToMerge.size(), targetValues, valuesToMerge); } - private void consolidateMoods(List targetValues, List valuesToMerge, boolean writeToFile, boolean moveFile) { + private void consolidateMoods(List targetValues, List valuesToMerge, boolean moveFile) { List targetMoods = targetValues.stream() .map(name -> moodRepository.findByNameIgnoreCase(name) .map(existing -> { @@ -200,17 +191,14 @@ public class MetadataManagementService { bookMetadataRepository.saveAll(booksWithOldMood); bookMetadataRepository.flush(); - if (writeToFile) { - writeMetadataToFile(booksWithOldMood, moveFile); - } - + writeMetadataToFile(booksWithOldMood, moveFile); moodRepository.delete(oldMood); } log.info("Consolidated {} moods into {}: {}", moodsToMerge.size(), targetValues, valuesToMerge); } - private void consolidateTags(List targetValues, List valuesToMerge, boolean writeToFile, boolean moveFile) { + private void consolidateTags(List targetValues, List valuesToMerge, boolean moveFile) { List targetTags = targetValues.stream() .map(name -> tagRepository.findByNameIgnoreCase(name) .map(existing -> { @@ -241,17 +229,14 @@ public class MetadataManagementService { bookMetadataRepository.saveAll(booksWithOldTag); bookMetadataRepository.flush(); - if (writeToFile) { - writeMetadataToFile(booksWithOldTag, moveFile); - } - + writeMetadataToFile(booksWithOldTag, moveFile); tagRepository.delete(oldTag); } log.info("Consolidated {} tags into {}: {}", tagsToMerge.size(), targetValues, valuesToMerge); } - private void consolidateSeries(List targetValues, List valuesToMerge, boolean writeToFile, boolean moveFile) { + private void consolidateSeries(List targetValues, List valuesToMerge, boolean moveFile) { if (targetValues.size() != 1) { throw new IllegalArgumentException("Series merge requires exactly one target value"); } @@ -265,16 +250,13 @@ public class MetadataManagementService { } bookMetadataRepository.saveAll(booksWithOldSeries); - - if (writeToFile) { - writeMetadataToFile(booksWithOldSeries, moveFile); - } + writeMetadataToFile(booksWithOldSeries, moveFile); } log.info("Consolidated {} series into '{}': {}", valuesToMerge.size(), targetSeriesName, valuesToMerge); } - private void consolidatePublishers(List targetValues, List valuesToMerge, boolean writeToFile, boolean moveFile) { + private void consolidatePublishers(List targetValues, List valuesToMerge, boolean moveFile) { if (targetValues.size() != 1) { throw new IllegalArgumentException("Publisher merge requires exactly one target value"); } @@ -288,16 +270,13 @@ public class MetadataManagementService { } bookMetadataRepository.saveAll(booksWithOldPublisher); - - if (writeToFile) { - writeMetadataToFile(booksWithOldPublisher, moveFile); - } + writeMetadataToFile(booksWithOldPublisher, moveFile); } log.info("Consolidated {} publishers into '{}': {}", valuesToMerge.size(), targetPublisher, valuesToMerge); } - private void consolidateLanguages(List targetValues, List valuesToMerge, boolean writeToFile, boolean moveFile) { + private void consolidateLanguages(List targetValues, List valuesToMerge, boolean moveFile) { if (targetValues.size() != 1) { throw new IllegalArgumentException("Language merge requires exactly one target value"); } @@ -311,10 +290,7 @@ public class MetadataManagementService { } bookMetadataRepository.saveAll(booksWithOldLanguage); - - if (writeToFile) { - writeMetadataToFile(booksWithOldLanguage, moveFile); - } + writeMetadataToFile(booksWithOldLanguage, moveFile); } log.info("Consolidated {} languages into '{}': {}", valuesToMerge.size(), targetLanguage, valuesToMerge); @@ -324,20 +300,19 @@ public class MetadataManagementService { public void deleteMetadata(MergeMetadataType metadataType, List valuesToDelete) { MetadataPersistenceSettings settings = appSettingService.getAppSettings().getMetadataPersistenceSettings(); boolean moveFile = settings.isMoveFilesToLibraryPattern(); - boolean writeToFile = settings.isSaveToOriginalFile(); switch (metadataType) { - case authors -> deleteAuthors(valuesToDelete, writeToFile, moveFile); - case categories -> deleteCategories(valuesToDelete, writeToFile, moveFile); - case moods -> deleteMoods(valuesToDelete, writeToFile, moveFile); - case tags -> deleteTags(valuesToDelete, writeToFile, moveFile); - case series -> deleteSeries(valuesToDelete, writeToFile, moveFile); - case publishers -> deletePublishers(valuesToDelete, writeToFile, moveFile); - case languages -> deleteLanguages(valuesToDelete, writeToFile, moveFile); + case authors -> deleteAuthors(valuesToDelete, moveFile); + case categories -> deleteCategories(valuesToDelete, moveFile); + case moods -> deleteMoods(valuesToDelete, moveFile); + case tags -> deleteTags(valuesToDelete, moveFile); + case series -> deleteSeries(valuesToDelete, moveFile); + case publishers -> deletePublishers(valuesToDelete, moveFile); + case languages -> deleteLanguages(valuesToDelete, moveFile); } } - private void deleteAuthors(List valuesToDelete, boolean writeToFile, boolean moveFile) { + private void deleteAuthors(List valuesToDelete, boolean moveFile) { List authorsToDelete = valuesToDelete.stream() .map(authorRepository::findByName) .filter(java.util.Optional::isPresent) @@ -353,18 +328,14 @@ public class MetadataManagementService { bookMetadataRepository.saveAll(booksWithAuthor); bookMetadataRepository.flush(); - - if (writeToFile) { - writeMetadataToFile(booksWithAuthor, moveFile); - } - + writeMetadataToFile(booksWithAuthor, moveFile); authorRepository.delete(author); } log.info("Deleted {} authors: {}", authorsToDelete.size(), valuesToDelete); } - private void deleteCategories(List valuesToDelete, boolean writeToFile, boolean moveFile) { + private void deleteCategories(List valuesToDelete, boolean moveFile) { List categoriesToDelete = valuesToDelete.stream() .map(categoryRepository::findByNameIgnoreCase) .filter(java.util.Optional::isPresent) @@ -380,18 +351,14 @@ public class MetadataManagementService { bookMetadataRepository.saveAll(booksWithCategory); bookMetadataRepository.flush(); - - if (writeToFile) { - writeMetadataToFile(booksWithCategory, moveFile); - } - + writeMetadataToFile(booksWithCategory, moveFile); categoryRepository.delete(category); } log.info("Deleted {} categories: {}", categoriesToDelete.size(), valuesToDelete); } - private void deleteMoods(List valuesToDelete, boolean writeToFile, boolean moveFile) { + private void deleteMoods(List valuesToDelete, boolean moveFile) { List moodsToDelete = valuesToDelete.stream() .map(moodRepository::findByNameIgnoreCase) .filter(java.util.Optional::isPresent) @@ -407,18 +374,14 @@ public class MetadataManagementService { bookMetadataRepository.saveAll(booksWithMood); bookMetadataRepository.flush(); - - if (writeToFile) { - writeMetadataToFile(booksWithMood, moveFile); - } - + writeMetadataToFile(booksWithMood, moveFile); moodRepository.delete(mood); } log.info("Deleted {} moods: {}", moodsToDelete.size(), valuesToDelete); } - private void deleteTags(List valuesToDelete, boolean writeToFile, boolean moveFile) { + private void deleteTags(List valuesToDelete, boolean moveFile) { List tagsToDelete = valuesToDelete.stream() .map(tagRepository::findByNameIgnoreCase) .filter(java.util.Optional::isPresent) @@ -434,18 +397,14 @@ public class MetadataManagementService { bookMetadataRepository.saveAll(booksWithTag); bookMetadataRepository.flush(); - - if (writeToFile) { - writeMetadataToFile(booksWithTag, moveFile); - } - + writeMetadataToFile(booksWithTag, moveFile); tagRepository.delete(tag); } log.info("Deleted {} tags: {}", tagsToDelete.size(), valuesToDelete); } - private void deleteSeries(List valuesToDelete, boolean writeToFile, boolean moveFile) { + private void deleteSeries(List valuesToDelete, boolean moveFile) { for (String seriesName : valuesToDelete) { List booksWithSeries = bookMetadataRepository.findAllBySeriesNameIgnoreCase(seriesName); @@ -457,17 +416,14 @@ public class MetadataManagementService { if (!booksWithSeries.isEmpty()) { bookMetadataRepository.saveAll(booksWithSeries); - - if (writeToFile) { - writeMetadataToFile(booksWithSeries, moveFile); - } + writeMetadataToFile(booksWithSeries, moveFile); } } log.info("Deleted {} series: {}", valuesToDelete.size(), valuesToDelete); } - private void deletePublishers(List valuesToDelete, boolean writeToFile, boolean moveFile) { + private void deletePublishers(List valuesToDelete, boolean moveFile) { for (String publisher : valuesToDelete) { List booksWithPublisher = bookMetadataRepository.findAllByPublisherIgnoreCase(publisher); @@ -477,17 +433,14 @@ public class MetadataManagementService { if (!booksWithPublisher.isEmpty()) { bookMetadataRepository.saveAll(booksWithPublisher); - - if (writeToFile) { - writeMetadataToFile(booksWithPublisher, moveFile); - } + writeMetadataToFile(booksWithPublisher, moveFile); } } log.info("Deleted {} publishers: {}", valuesToDelete.size(), valuesToDelete); } - private void deleteLanguages(List valuesToDelete, boolean writeToFile, boolean moveFile) { + private void deleteLanguages(List valuesToDelete, boolean moveFile) { for (String language : valuesToDelete) { List booksWithLanguage = bookMetadataRepository.findAllByLanguageIgnoreCase(language); @@ -497,10 +450,7 @@ public class MetadataManagementService { if (!booksWithLanguage.isEmpty()) { bookMetadataRepository.saveAll(booksWithLanguage); - - if (writeToFile) { - writeMetadataToFile(booksWithLanguage, moveFile); - } + writeMetadataToFile(booksWithLanguage, moveFile); } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java index 31d9b6e40..47f4e6675 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractor.java @@ -28,6 +28,7 @@ import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; + import org.xml.sax.SAXException; import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry; @@ -51,54 +52,54 @@ public class CbxMetadataExtractor implements FileMetadataExtractor { private static final Pattern COMMA_SEMICOLON_PATTERN = Pattern.compile("[,;]"); @Override - public BookMetadata extractMetadata(File file) { - String baseName = FilenameUtils.getBaseName(file.getName()); - String lowerName = file.getName().toLowerCase(); + public BookMetadata extractMetadata(File file) { + String baseName = FilenameUtils.getBaseName(file.getName()); + String lowerName = file.getName().toLowerCase(); - // Non-archive (fallback) - if (!lowerName.endsWith(".cbz") && !lowerName.endsWith(".cbr") && !lowerName.endsWith(".cb7")) { - return BookMetadata.builder().title(baseName).build(); - } + // Non-archive (fallback) + if (!lowerName.endsWith(".cbz") && !lowerName.endsWith(".cbr") && !lowerName.endsWith(".cb7")) { + return BookMetadata.builder().title(baseName).build(); + } - // CBZ path (ZIP) - if (lowerName.endsWith(".cbz")) { - try (ZipFile zipFile = new ZipFile(file)) { - ZipEntry entry = findComicInfoEntry(zipFile); - if (entry == null) { - return BookMetadata.builder().title(baseName).build(); + // CBZ path (ZIP) + if (lowerName.endsWith(".cbz")) { + try (ZipFile zipFile = new ZipFile(file)) { + ZipEntry entry = findComicInfoEntry(zipFile); + if (entry == null) { + return BookMetadata.builder().title(baseName).build(); + } + try (InputStream is = zipFile.getInputStream(entry)) { + Document document = buildSecureDocument(is); + return mapDocumentToMetadata(document, baseName); + } + } catch (Exception e) { + log.warn("Failed to extract metadata from CBZ", e); + return BookMetadata.builder().title(baseName).build(); + } } - try (InputStream is = zipFile.getInputStream(entry)) { - Document document = buildSecureDocument(is); - return mapDocumentToMetadata(document, baseName); - } - } catch (Exception e) { - log.warn("Failed to extract metadata from CBZ", e); - return BookMetadata.builder().title(baseName).build(); - } - } - // CB7 path (7z) - if (lowerName.endsWith(".cb7")) { - try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get()) { - SevenZArchiveEntry entry = findSevenZComicInfoEntry(sevenZ); - if (entry == null) { - return BookMetadata.builder().title(baseName).build(); + // CB7 path (7z) + if (lowerName.endsWith(".cb7")) { + try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get()) { + SevenZArchiveEntry entry = findSevenZComicInfoEntry(sevenZ); + if (entry == null) { + return BookMetadata.builder().title(baseName).build(); + } + byte[] xmlBytes = readSevenZEntryBytes(sevenZ, entry); + if (xmlBytes == null) { + return BookMetadata.builder().title(baseName).build(); + } + try (InputStream is = new ByteArrayInputStream(xmlBytes)) { + Document document = buildSecureDocument(is); + return mapDocumentToMetadata(document, baseName); + } + } catch (Exception e) { + log.warn("Failed to extract metadata from CB7", e); + return BookMetadata.builder().title(baseName).build(); + } } - byte[] xmlBytes = readSevenZEntryBytes(sevenZ, entry); - if (xmlBytes == null) { - return BookMetadata.builder().title(baseName).build(); - } - try (InputStream is = new ByteArrayInputStream(xmlBytes)) { - Document document = buildSecureDocument(is); - return mapDocumentToMetadata(document, baseName); - } - } catch (Exception e) { - log.warn("Failed to extract metadata from CB7", e); - return BookMetadata.builder().title(baseName).build(); - } - } - // CBR path (RAR) + // CBR path (RAR) try (Archive archive = new Archive(file)) { try { FileHeader header = findComicInfoHeader(archive); @@ -120,782 +121,781 @@ public class CbxMetadataExtractor implements FileMetadataExtractor { } catch (Exception ignore) { } return BookMetadata.builder().title(baseName).build(); - } - - private ZipEntry findComicInfoEntry(ZipFile zipFile) { - Enumeration entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - String name = entry.getName(); - if (isComicInfoName(name)) { - return entry; - } - } - return null; - } - - /** - * Builds a secure XML document parser with protection against XXE attacks. - * Configures the DocumentBuilderFactory with security features to prevent: - * - External entity injection - * - DTD processing vulnerabilities - * - Schema injection attacks - * - * @param is InputStream containing XML data to parse - * @return Parsed Document object - * @throws Exception if XML parsing fails or security features cannot be configured - */ - private Document buildSecureDocument(InputStream is) throws Exception { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); // Enable namespace awareness - factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); - try { - factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); - factory.setFeature("http://xml.org/sax/features/external-general-entities", false); - factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); - } catch (Exception ex) { - log.warn("XML factory secure features not supported, XXE protection may be compromised: {}", ex.getMessage()); - throw ex; // Re-throw to fail fast if security features can't be enabled - } - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); - factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); - factory.setExpandEntityReferences(false); - DocumentBuilder builder = factory.newDocumentBuilder(); - return builder.parse(is); - } - - /** - * Maps XML document to BookMetadata by extracting all relevant ComicInfo fields. - * Handles missing or invalid fields gracefully by using fallback values or null. - * - * @param document The parsed XML document containing ComicInfo data - * @param fallbackTitle Title to use if Title element is missing or blank - * @return BookMetadata object populated with extracted values - */ - private BookMetadata mapDocumentToMetadata( - Document document, - String fallbackTitle - ) { - BookMetadata.BookMetadataBuilder builder = BookMetadata.builder(); - - String title = getTextContent(document, "Title"); - builder.title(title == null || title.isBlank() ? fallbackTitle : title); - - builder.description( - coalesce( - getTextContent(document, "Summary"), - getTextContent(document, "Description") - ) - ); - builder.publisher(getTextContent(document, "Publisher")); - - String series = getTextContent(document, "Series"); - String volume = getTextContent(document, "Volume"); - builder.seriesName(volume == null || volume.isBlank() ? series : String.format("%s (%s)", series, volume)); - builder.seriesNumber(parseFloat(getTextContent(document, "Number"))); - builder.seriesTotal(parseInteger(getTextContent(document, "Count"))); - builder.publishedDate( - parseDate( - getTextContent(document, "Year"), - getTextContent(document, "Month"), - getTextContent(document, "Day") - ) - ); - builder.pageCount( - parseInteger( - coalesce( - getTextContent(document, "PageCount"), - getTextContent(document, "Pages") - ) - ) - ); - builder.language(getTextContent(document, "LanguageISO")); - - Set authors = new HashSet<>(); - authors.addAll(splitValues(getTextContent(document, "Writer"))); - authors.addAll(splitValues(getTextContent(document, "Penciller"))); - authors.addAll(splitValues(getTextContent(document, "Inker"))); - authors.addAll(splitValues(getTextContent(document, "Colorist"))); - authors.addAll(splitValues(getTextContent(document, "Letterer"))); - authors.addAll(splitValues(getTextContent(document, "CoverArtist"))); - if (!authors.isEmpty()) { - builder.authors(authors); } - Set categories = new HashSet<>(); - categories.addAll(splitValues(getTextContent(document, "Genre"))); - categories.addAll(splitValues(getTextContent(document, "Tags"))); - if (!categories.isEmpty()) { - builder.categories(categories); + private ZipEntry findComicInfoEntry(ZipFile zipFile) { + Enumeration entries = zipFile.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + String name = entry.getName(); + if (isComicInfoName(name)) { + return entry; + } + } + return null; } - return builder.build(); - } - - /** - * Extracts and trims text content from the first element with the given tag name. - * - * @param document The XML document to search - * @param tag The tag name to find - * @return Trimmed text content of the first matching element, or null if not found - */ - private String getTextContent(Document document, String tag) { - NodeList nodes = document.getElementsByTagName(tag); - if (nodes.getLength() == 0) { - return null; + /** + * Builds a secure XML document parser with protection against XXE attacks. + * Configures the DocumentBuilderFactory with security features to prevent: + * - External entity injection + * - DTD processing vulnerabilities + * - Schema injection attacks + * + * @param is InputStream containing XML data to parse + * @return Parsed Document object + * @throws Exception if XML parsing fails or security features cannot be configured + */ + private Document buildSecureDocument(InputStream is) throws Exception { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setNamespaceAware(true); // Enable namespace awareness + factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); + try { + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + factory.setFeature("http://xml.org/sax/features/external-general-entities", false); + factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + } catch (Exception ex) { + log.warn("XML factory secure features not supported, XXE protection may be compromised: {}", ex.getMessage()); + throw ex; // Re-throw to fail fast if security features can't be enabled + } + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); + factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); + factory.setExpandEntityReferences(false); + DocumentBuilder builder = factory.newDocumentBuilder(); + return builder.parse(is); } - return nodes.item(0).getTextContent().trim(); - } - private String coalesce(String a, String b) { - return (a != null && !a.isBlank()) - ? a - : (b != null && !b.isBlank() ? b : null); - } + /** + * Maps XML document to BookMetadata by extracting all relevant ComicInfo fields. + * Handles missing or invalid fields gracefully by using fallback values or null. + * + * @param document The parsed XML document containing ComicInfo data + * @param fallbackTitle Title to use if Title element is missing or blank + * @return BookMetadata object populated with extracted values + */ + private BookMetadata mapDocumentToMetadata( + Document document, + String fallbackTitle + ) { + BookMetadata.BookMetadataBuilder builder = BookMetadata.builder(); - /** - * Splits a delimited string into a set of trimmed values. - * Supports both comma (,) and semicolon (;) as delimiters. - * Empty values after trimming are excluded from the result. - * - * @param value The delimited string to split - * @return Set of trimmed non-empty values, or empty set if input is null - */ - private Set splitValues(String value) { - if (value == null) { - return new HashSet<>(); + String title = getTextContent(document, "Title"); + builder.title(title == null || title.isBlank() ? fallbackTitle : title); + + builder.description( + coalesce( + getTextContent(document, "Summary"), + getTextContent(document, "Description") + ) + ); + builder.publisher(getTextContent(document, "Publisher")); + + String series = getTextContent(document, "Series"); + String volume = getTextContent(document, "Volume"); + builder.seriesName(volume == null || volume.isBlank() ? series : String.format("%s (%s)", series, volume)); + builder.seriesNumber(parseFloat(getTextContent(document, "Number"))); + builder.seriesTotal(parseInteger(getTextContent(document, "Count"))); + builder.publishedDate( + parseDate( + getTextContent(document, "Year"), + getTextContent(document, "Month"), + getTextContent(document, "Day") + ) + ); + builder.pageCount( + parseInteger( + coalesce( + getTextContent(document, "PageCount"), + getTextContent(document, "Pages") + ) + ) + ); + builder.language(getTextContent(document, "LanguageISO")); + + Set authors = new HashSet<>(); + authors.addAll(splitValues(getTextContent(document, "Writer"))); + if (!authors.isEmpty()) { + builder.authors(authors); + } + + Set categories = new HashSet<>(); + categories.addAll(splitValues(getTextContent(document, "Genre"))); + categories.addAll(splitValues(getTextContent(document, "Tags"))); + if (!categories.isEmpty()) { + builder.categories(categories); + } + + return builder.build(); } - return Arrays.stream(COMMA_SEMICOLON_PATTERN.split(value)) - .map(String::trim) - .filter(s -> !s.isEmpty()) - .collect(Collectors.toSet()); - } - private Integer parseInteger(String value) { - try { - return (value == null || value.isBlank()) - ? null - : Integer.parseInt(value.trim()); - } catch (NumberFormatException e) { - return null; + /** + * Extracts and trims text content from the first element with the given tag name. + * + * @param document The XML document to search + * @param tag The tag name to find + * @return Trimmed text content of the first matching element, or null if not found + */ + private String getTextContent(Document document, String tag) { + NodeList nodes = document.getElementsByTagName(tag); + if (nodes.getLength() == 0) { + return null; + } + return nodes.item(0).getTextContent().trim(); } - } - private Float parseFloat(String value) { - try { - return (value == null || value.isBlank()) - ? null - : Float.parseFloat(value.trim()); - } catch (NumberFormatException e) { - return null; + private String coalesce(String a, String b) { + return (a != null && !a.isBlank()) + ? a + : (b != null && !b.isBlank() ? b : null); } - } - /** - * Parses year, month, and day strings into a LocalDate. - * Defaults missing month/day to 1. Returns null if year is missing or invalid. - * - * @param year Year string (required) - * @param month Month string (optional, defaults to 1) - * @param day Day string (optional, defaults to 1) - * @return LocalDate object, or null if parsing fails or year is null - */ - private LocalDate parseDate(String year, String month, String day) { - Integer y = parseInteger(year); - Integer m = parseInteger(month); - Integer d = parseInteger(day); - if (y == null) { - return null; + /** + * Splits a delimited string into a set of trimmed values. + * Supports both comma (,) and semicolon (;) as delimiters. + * Empty values after trimming are excluded from the result. + * + * @param value The delimited string to split + * @return Set of trimmed non-empty values, or empty set if input is null + */ + private Set splitValues(String value) { + if (value == null) { + return new HashSet<>(); + } + return Arrays.stream(COMMA_SEMICOLON_PATTERN.split(value)) + .map(String::trim) + .filter(s -> !s.isEmpty()) + .collect(Collectors.toSet()); } - if (m == null) { - m = 1; - } - if (d == null) { - d = 1; - } - try { - return LocalDate.of(y, m, d); - } catch (Exception e) { - return null; - } - } - /** - * Extracts metadata from a standalone ComicInfo.xml file. - * This method is useful for processing ComicInfo.xml files that have been - * extracted from comic book archives or exist independently. - * - * @param xmlFile The ComicInfo.xml file to parse - * @return BookMetadata extracted from the XML file, or fallback metadata if parsing fails - * @throws IllegalArgumentException if xmlFile is null - */ - public BookMetadata extractFromComicInfoXml(File xmlFile) { - if (xmlFile == null) { - throw new IllegalArgumentException("XML file cannot be null"); - } + private Integer parseInteger(String value) { + try { + return (value == null || value.isBlank()) + ? null + : Integer.parseInt(value.trim()); + } catch (NumberFormatException e) { + return null; + } + } - String fallbackTitle = determineFallbackTitle(xmlFile); + private Float parseFloat(String value) { + try { + return (value == null || value.isBlank()) + ? null + : Float.parseFloat(value.trim()); + } catch (NumberFormatException e) { + return null; + } + } - try (InputStream is = new FileInputStream(xmlFile)) { - Document document = buildSecureDocument(is); - return mapDocumentToMetadata(document, fallbackTitle); - } catch (IOException e) { - log.error("Failed to read ComicInfo.xml file '{}': {}", - xmlFile.getAbsolutePath(), e.getMessage(), e); - return BookMetadata.builder().title(fallbackTitle).build(); - } catch (SAXException | ParserConfigurationException e) { - log.warn("Failed to parse ComicInfo.xml from file '{}': {}", - xmlFile.getAbsolutePath(), e.getMessage(), e); - return BookMetadata.builder().title(fallbackTitle).build(); - } catch (Exception e) { - log.error("Unexpected error processing ComicInfo.xml '{}': {}", + /** + * Parses year, month, and day strings into a LocalDate. + * Defaults missing month/day to 1. Returns null if year is missing or invalid. + * + * @param year Year string (required) + * @param month Month string (optional, defaults to 1) + * @param day Day string (optional, defaults to 1) + * @return LocalDate object, or null if parsing fails or year is null + */ + private LocalDate parseDate(String year, String month, String day) { + Integer y = parseInteger(year); + Integer m = parseInteger(month); + Integer d = parseInteger(day); + if (y == null) { + return null; + } + if (m == null) { + m = 1; + } + if (d == null) { + d = 1; + } + try { + return LocalDate.of(y, m, d); + } catch (Exception e) { + return null; + } + } + + /** + * Extracts metadata from a standalone ComicInfo.xml file. + * This method is useful for processing ComicInfo.xml files that have been + * extracted from comic book archives or exist independently. + * + * @param xmlFile The ComicInfo.xml file to parse + * @return BookMetadata extracted from the XML file, or fallback metadata if parsing fails + * @throws IllegalArgumentException if xmlFile is null + */ + public BookMetadata extractFromComicInfoXml(File xmlFile) { + if (xmlFile == null) { + throw new IllegalArgumentException("XML file cannot be null"); + } + + String fallbackTitle = determineFallbackTitle(xmlFile); + + try (InputStream is = new FileInputStream(xmlFile)) { + Document document = buildSecureDocument(is); + return mapDocumentToMetadata(document, fallbackTitle); + } catch (IOException e) { + log.error("Failed to read ComicInfo.xml file '{}': {}", xmlFile.getAbsolutePath(), e.getMessage(), e); - return BookMetadata.builder().title(fallbackTitle).build(); - } - } - - /** - * Determines the fallback title to use when metadata extraction fails. - * Uses the parent directory name if available, otherwise the file name. - * - * @param file The file to determine the fallback title for - * @return A fallback title string - */ - private String determineFallbackTitle(File file) { - // Try parent directory first (usually the comic folder/archive name) - if (file.getParentFile() != null) { - String parentName = file.getParentFile().getName(); - if (parentName != null && !parentName.isBlank()) { - return parentName; - } - } - // Fall back to filename without extension - return FilenameUtils.getBaseName(file.getName()); - } - - @Override - public byte[] extractCover(File file) { - String lowerName = file.getName().toLowerCase(); - - // Non-archive fallback - if (!lowerName.endsWith(".cbz") && !lowerName.endsWith(".cbr") && !lowerName.endsWith(".cb7")) { - return generatePlaceholderCover(250, 350); + return BookMetadata.builder().title(fallbackTitle).build(); + } catch (SAXException | ParserConfigurationException e) { + log.warn("Failed to parse ComicInfo.xml from file '{}': {}", + xmlFile.getAbsolutePath(), e.getMessage(), e); + return BookMetadata.builder().title(fallbackTitle).build(); + } catch (Exception e) { + log.error("Unexpected error processing ComicInfo.xml '{}': {}", + xmlFile.getAbsolutePath(), e.getMessage(), e); + return BookMetadata.builder().title(fallbackTitle).build(); + } } - // CBZ path - if (lowerName.endsWith(".cbz")) { - try (ZipFile zipFile = new ZipFile(file)) { - // Try front cover via ComicInfo - ZipEntry coverEntry = findFrontCoverEntry(zipFile); - if (coverEntry != null) { - try (InputStream is = zipFile.getInputStream(coverEntry)) { - byte[] bytes = is.readAllBytes(); - if (canDecode(bytes)) return bytes; - } - } - // Fallback: iterate images alphabetically until a decodable one is found - ZipEntry firstImage = findFirstAlphabeticalImageEntry(zipFile); - if (firstImage != null) { - // Build a sorted list and iterate for decodable formats - java.util.List images = listZipImageEntries(zipFile); - for (ZipEntry e : images) { - try (InputStream is = zipFile.getInputStream(e)) { - byte[] bytes = is.readAllBytes(); - if (canDecode(bytes)) return bytes; + /** + * Determines the fallback title to use when metadata extraction fails. + * Uses the parent directory name if available, otherwise the file name. + * + * @param file The file to determine the fallback title for + * @return A fallback title string + */ + private String determineFallbackTitle(File file) { + // Try parent directory first (usually the comic folder/archive name) + if (file.getParentFile() != null) { + String parentName = file.getParentFile().getName(); + if (parentName != null && !parentName.isBlank()) { + return parentName; } - } } - } catch (Exception e) { - log.warn("Failed to extract cover image from CBZ", e); - return generatePlaceholderCover(250, 350); - } + // Fall back to filename without extension + return FilenameUtils.getBaseName(file.getName()); } - // CB7 path - if (lowerName.endsWith(".cb7")) { - try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get()) { - // Try via ComicInfo.xml first - SevenZArchiveEntry ci = findSevenZComicInfoEntry(sevenZ); - if (ci != null) { - byte[] xmlBytes = readSevenZEntryBytes(sevenZ, ci); - if (xmlBytes != null) { - try (InputStream is = new ByteArrayInputStream(xmlBytes)) { - Document document = buildSecureDocument(is); - String imageName = findFrontCoverImageName(document); - if (imageName != null) { - SevenZArchiveEntry byName = findSevenZEntryByName(sevenZ, imageName); - if (byName != null) { - byte[] bytes = readSevenZEntryBytes(sevenZ, byName); - if (canDecode(bytes)) return bytes; - } - try { - int index = Integer.parseInt(imageName); - SevenZArchiveEntry byIndex = findSevenZImageEntryByIndex(sevenZ, index); - if (byIndex != null) { - byte[] bytes = readSevenZEntryBytes(sevenZ, byIndex); - if (canDecode(bytes)) return bytes; - } - if (index > 0) { - SevenZArchiveEntry offByOne = findSevenZImageEntryByIndex(sevenZ, index - 1); - if (offByOne != null) { - byte[] bytes = readSevenZEntryBytes(sevenZ, offByOne); - if (canDecode(bytes)) return bytes; + @Override + public byte[] extractCover(File file) { + String lowerName = file.getName().toLowerCase(); + + // Non-archive fallback + if (!lowerName.endsWith(".cbz") && !lowerName.endsWith(".cbr") && !lowerName.endsWith(".cb7")) { + return generatePlaceholderCover(250, 350); + } + + // CBZ path + if (lowerName.endsWith(".cbz")) { + try (ZipFile zipFile = new ZipFile(file)) { + // Try front cover via ComicInfo + ZipEntry coverEntry = findFrontCoverEntry(zipFile); + if (coverEntry != null) { + try (InputStream is = zipFile.getInputStream(coverEntry)) { + byte[] bytes = is.readAllBytes(); + if (canDecode(bytes)) return bytes; } - } - } catch (NumberFormatException ignore) { - // continue to fallback } - } + // Fallback: iterate images alphabetically until a decodable one is found + ZipEntry firstImage = findFirstAlphabeticalImageEntry(zipFile); + if (firstImage != null) { + // Build a sorted list and iterate for decodable formats + java.util.List images = listZipImageEntries(zipFile); + for (ZipEntry e : images) { + try (InputStream is = zipFile.getInputStream(e)) { + byte[] bytes = is.readAllBytes(); + if (canDecode(bytes)) return bytes; + } + } + } + } catch (Exception e) { + log.warn("Failed to extract cover image from CBZ", e); + return generatePlaceholderCover(250, 350); } - } } - // Fallback: iterate images alphabetically until a decodable one is found - SevenZArchiveEntry first = findFirstAlphabeticalSevenZImageEntry(sevenZ); - if (first != null) { - java.util.List images = listSevenZImageEntries(sevenZ); - for (SevenZArchiveEntry e : images) { - byte[] bytes = readSevenZEntryBytes(sevenZ, e); - if (canDecode(bytes)) return bytes; - } + // CB7 path + if (lowerName.endsWith(".cb7")) { + try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get()) { + // Try via ComicInfo.xml first + SevenZArchiveEntry ci = findSevenZComicInfoEntry(sevenZ); + if (ci != null) { + byte[] xmlBytes = readSevenZEntryBytes(sevenZ, ci); + if (xmlBytes != null) { + try (InputStream is = new ByteArrayInputStream(xmlBytes)) { + Document document = buildSecureDocument(is); + String imageName = findFrontCoverImageName(document); + if (imageName != null) { + SevenZArchiveEntry byName = findSevenZEntryByName(sevenZ, imageName); + if (byName != null) { + byte[] bytes = readSevenZEntryBytes(sevenZ, byName); + if (canDecode(bytes)) return bytes; + } + try { + int index = Integer.parseInt(imageName); + SevenZArchiveEntry byIndex = findSevenZImageEntryByIndex(sevenZ, index); + if (byIndex != null) { + byte[] bytes = readSevenZEntryBytes(sevenZ, byIndex); + if (canDecode(bytes)) return bytes; + } + if (index > 0) { + SevenZArchiveEntry offByOne = findSevenZImageEntryByIndex(sevenZ, index - 1); + if (offByOne != null) { + byte[] bytes = readSevenZEntryBytes(sevenZ, offByOne); + if (canDecode(bytes)) return bytes; + } + } + } catch (NumberFormatException ignore) { + // continue to fallback + } + } + } + } + } + + // Fallback: iterate images alphabetically until a decodable one is found + SevenZArchiveEntry first = findFirstAlphabeticalSevenZImageEntry(sevenZ); + if (first != null) { + java.util.List images = listSevenZImageEntries(sevenZ); + for (SevenZArchiveEntry e : images) { + byte[] bytes = readSevenZEntryBytes(sevenZ, e); + if (canDecode(bytes)) return bytes; + } + } + } catch (Exception e) { + log.warn("Failed to extract cover image from CB7", e); + return generatePlaceholderCover(250, 350); + } } - } catch (Exception e) { - log.warn("Failed to extract cover image from CB7", e); + + // CBR path + try (Archive archive = new Archive(file)) { + try { + + // Try via ComicInfo.xml first + FileHeader comicInfo = findComicInfoHeader(archive); + if (comicInfo != null) { + byte[] xmlBytes = readRarEntryBytes(archive, comicInfo); + if (xmlBytes != null) { + try (InputStream is = new ByteArrayInputStream(xmlBytes)) { + Document document = buildSecureDocument(is); + String imageName = findFrontCoverImageName(document); + if (imageName != null) { + FileHeader byName = findRarHeaderByName(archive, imageName); + if (byName != null) { + byte[] bytes = readRarEntryBytes(archive, byName); + if (canDecode(bytes)) return bytes; + } + try { + int index = Integer.parseInt(imageName); + FileHeader byIndex = findRarImageHeaderByIndex(archive, index); + if (byIndex != null) { + byte[] bytes = readRarEntryBytes(archive, byIndex); + if (canDecode(bytes)) return bytes; + } + if (index > 0) { + FileHeader offByOne = findRarImageHeaderByIndex(archive, index - 1); + if (offByOne != null) { + byte[] bytes = readRarEntryBytes(archive, offByOne); + if (canDecode(bytes)) return bytes; + } + } + } catch (NumberFormatException ignore) { + // ignore and continue fallback + } + } + } + } + } + + // Fallback: iterate images alphabetically until a decodable one is found + FileHeader firstImage = findFirstAlphabeticalImageHeader(archive); + if (firstImage != null) { + List images = listRarImageHeaders(archive); + for (FileHeader fh : images) { + byte[] bytes = readRarEntryBytes(archive, fh); + if (canDecode(bytes)) return bytes; + } + } + } catch (Exception e) { + log.warn("Failed to extract cover image from CBR", e); + return generatePlaceholderCover(250, 350); + } + } catch (Exception ignore) { + } + return generatePlaceholderCover(250, 350); - } } - // CBR path - try (Archive archive = new Archive(file)) { - try { - - // Try via ComicInfo.xml first - FileHeader comicInfo = findComicInfoHeader(archive); - if (comicInfo != null) { - byte[] xmlBytes = readRarEntryBytes(archive, comicInfo); - if (xmlBytes != null) { - try (InputStream is = new ByteArrayInputStream(xmlBytes)) { - Document document = buildSecureDocument(is); - String imageName = findFrontCoverImageName(document); - if (imageName != null) { - FileHeader byName = findRarHeaderByName(archive, imageName); - if (byName != null) { - byte[] bytes = readRarEntryBytes(archive, byName); - if (canDecode(bytes)) return bytes; - } - try { - int index = Integer.parseInt(imageName); - FileHeader byIndex = findRarImageHeaderByIndex(archive, index); - if (byIndex != null) { - byte[] bytes = readRarEntryBytes(archive, byIndex); - if (canDecode(bytes)) return bytes; - } - if (index > 0) { - FileHeader offByOne = findRarImageHeaderByIndex(archive, index - 1); - if (offByOne != null) { - byte[] bytes = readRarEntryBytes(archive, offByOne); - if (canDecode(bytes)) return bytes; - } - } - } catch (NumberFormatException ignore) { - // ignore and continue fallback - } - } - } - } - } - - // Fallback: iterate images alphabetically until a decodable one is found - FileHeader firstImage = findFirstAlphabeticalImageHeader(archive); - if (firstImage != null) { - List images = listRarImageHeaders(archive); - for (FileHeader fh : images) { - byte[] bytes = readRarEntryBytes(archive, fh); - if (canDecode(bytes)) return bytes; - } - } - } catch (Exception e) { - log.warn("Failed to extract cover image from CBR", e); - return generatePlaceholderCover(250, 350); - } - } catch (Exception ignore) { - } - - return generatePlaceholderCover(250, 350); - } - - private boolean canDecode(byte[] bytes) { - if (bytes == null || bytes.length == 0) return false; - try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes)) { - BufferedImage img = ImageIO.read(bais); - return img != null; - } catch (IOException e) { - return false; + private boolean canDecode(byte[] bytes) { + if (bytes == null || bytes.length == 0) return false; + try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes)) { + BufferedImage img = ImageIO.read(bais); + return img != null; + } catch (IOException e) { + return false; + } } - } - private ZipEntry findFrontCoverEntry(ZipFile zipFile) { - ZipEntry comicInfoEntry = findComicInfoEntry(zipFile); - if (comicInfoEntry != null) { - try (InputStream is = zipFile.getInputStream(comicInfoEntry)) { - Document document = buildSecureDocument(is); - String imageName = findFrontCoverImageName(document); - if (imageName != null) { - ZipEntry byName = zipFile.getEntry(imageName); - if (byName != null) { - return byName; - } - // also try base-name match for archives with directories or odd encodings - String imageBase = baseName(imageName); - java.util.Enumeration it = zipFile.entries(); - while (it.hasMoreElements()) { - ZipEntry e = it.nextElement(); + private ZipEntry findFrontCoverEntry(ZipFile zipFile) { + ZipEntry comicInfoEntry = findComicInfoEntry(zipFile); + if (comicInfoEntry != null) { + try (InputStream is = zipFile.getInputStream(comicInfoEntry)) { + Document document = buildSecureDocument(is); + String imageName = findFrontCoverImageName(document); + if (imageName != null) { + ZipEntry byName = zipFile.getEntry(imageName); + if (byName != null) { + return byName; + } + // also try base-name match for archives with directories or odd encodings + String imageBase = baseName(imageName); + java.util.Enumeration it = zipFile.entries(); + while (it.hasMoreElements()) { + ZipEntry e = it.nextElement(); + if (!e.isDirectory() && isImageEntry(e.getName())) { + if (baseName(e.getName()).equalsIgnoreCase(imageBase)) { + return e; + } + } + } + try { + int index = Integer.parseInt(imageName); + ZipEntry byIndex = findImageEntryByIndex(zipFile, index); + if (byIndex != null) { + return byIndex; + } + if (index > 0) { + ZipEntry offByOne = findImageEntryByIndex(zipFile, index - 1); + if (offByOne != null) return offByOne; + } + } catch (NumberFormatException ignore) { + // ignore + } + } + } catch (Exception e) { + log.warn("Failed to parse ComicInfo.xml for cover", e); + } + } + // Heuristic filenames before generic fallback + ZipEntry heuristic = findHeuristicCover(zipFile); + if (heuristic != null) return heuristic; + return findFirstAlphabeticalImageEntry(zipFile); + } + + private ZipEntry findImageEntryByIndex(ZipFile zipFile, int index) { + Enumeration entries = zipFile.entries(); + int count = 0; + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + if (!entry.isDirectory() && isImageEntry(entry.getName())) { + if (count == index) { + return entry; + } + count++; + } + } + return null; + } + + private String findFrontCoverImageName(Document document) { + NodeList pages = document.getElementsByTagName("Page"); + for (int i = 0; i < pages.getLength(); i++) { + org.w3c.dom.Node node = pages.item(i); + if (node instanceof org.w3c.dom.Element page) { + String type = page.getAttribute("Type"); + if (type != null && "FrontCover".equalsIgnoreCase(type)) { + String imageFile = page.getAttribute("ImageFile"); + if (imageFile != null && !imageFile.isBlank()) { + return imageFile.trim(); + } + String image = page.getAttribute("Image"); + if (image != null && !image.isBlank()) { + return image.trim(); + } + } + } + } + return null; + } + + private boolean isImageEntry(String name) { + if (!isContentEntry(name)) return false; + String lower = name.toLowerCase(); + return ( + lower.endsWith(".jpg") || + lower.endsWith(".jpeg") || + lower.endsWith(".png") || + lower.endsWith(".gif") || + lower.endsWith(".bmp") || + lower.endsWith(".webp") + ); + } + + private boolean isContentEntry(String name) { + if (name == null) return false; + String norm = name.replace('\\', '/'); + if (norm.startsWith("__MACOSX/") || norm.contains("/__MACOSX/")) return false; + String base = baseName(norm); + if (base.startsWith(".")) return false; + if (".ds_store".equalsIgnoreCase(base)) return false; + return true; + } + + private byte[] generatePlaceholderCover(int width, int height) { + BufferedImage image = new BufferedImage( + width, + height, + BufferedImage.TYPE_INT_RGB + ); + Graphics2D g = image.createGraphics(); + + g.setColor(Color.LIGHT_GRAY); + g.fillRect(0, 0, width, height); + + g.setColor(Color.DARK_GRAY); + g.setFont(new Font("SansSerif", Font.BOLD, width / 10)); + FontMetrics fm = g.getFontMetrics(); + String text = "Preview Unavailable"; + + int textWidth = fm.stringWidth(text); + int textHeight = fm.getAscent(); + g.drawString(text, (width - textWidth) / 2, (height + textHeight) / 2); + + g.dispose(); + + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + ImageIO.write(image, "jpg", baos); + return baos.toByteArray(); + } catch (IOException e) { + log.warn("Failed to generate placeholder image", e); + return null; + } + } + + + // ==== RAR (.cbr) helpers ==== + private FileHeader findComicInfoHeader(Archive archive) { + if (archive == null) return null; + for (FileHeader fh : archive.getFileHeaders()) { + String name = fh.getFileName(); + if (name == null) continue; + if (isComicInfoName(name)) { + return fh; + } + } + return null; + } + + private FileHeader findRarHeaderByName(Archive archive, String imageName) { + if (archive == null || imageName == null) return null; + for (FileHeader fh : archive.getFileHeaders()) { + String name = fh.getFileName(); + if (name == null) continue; + if (name.equalsIgnoreCase(imageName)) return fh; + // also try base-name match to be lenient + if (baseName(name).equalsIgnoreCase(baseName(imageName))) return fh; + } + return null; + } + + private FileHeader findRarImageHeaderByIndex(Archive archive, int index) { + int count = 0; + for (FileHeader fh : archive.getFileHeaders()) { + if (!fh.isDirectory() && isImageEntry(fh.getFileName())) { + if (count == index) return fh; + count++; + } + } + return null; + } + + private FileHeader findFirstImageHeader(Archive archive) { + for (FileHeader fh : archive.getFileHeaders()) { + if (!fh.isDirectory() && isImageEntry(fh.getFileName())) { + return fh; + } + } + return null; + } + + private byte[] readRarEntryBytes(Archive archive, FileHeader header) { + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + archive.extractFile(header, baos); + return baos.toByteArray(); + } catch (Exception e) { + log.warn("Failed to read RAR entry bytes for {}", header != null ? header.getFileName() : "", e); + return null; + } + } + + private String baseName(String path) { + if (path == null) return null; + int slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')); + return slash >= 0 ? path.substring(slash + 1) : path; + } + + private FileHeader findFirstAlphabeticalImageHeader(Archive archive) { + if (archive == null) return null; + List images = new ArrayList<>(); + for (FileHeader fh : archive.getFileHeaders()) { + if (fh == null || fh.isDirectory()) continue; + String name = fh.getFileName(); + if (name == null) continue; + if (isImageEntry(name)) { + images.add(fh); + } + } + if (images.isEmpty()) return null; + images.sort((a, b) -> naturalCompare(a.getFileName(), b.getFileName())); + return images.getFirst(); + } + + private ZipEntry findFirstAlphabeticalImageEntry(ZipFile zipFile) { + List images = new ArrayList<>(); + Enumeration entries = zipFile.entries(); + while (entries.hasMoreElements()) { + ZipEntry e = entries.nextElement(); if (!e.isDirectory() && isImageEntry(e.getName())) { - if (baseName(e.getName()).equalsIgnoreCase(imageBase)) { + images.add(e); + } + } + if (images.isEmpty()) return null; + images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); + return images.getFirst(); + } + + // ==== 7z (.cb7) helpers ==== + private SevenZArchiveEntry findSevenZComicInfoEntry(SevenZFile sevenZ) { + for (SevenZArchiveEntry e : sevenZ.getEntries()) { + if (e == null || e.isDirectory()) continue; + String name = e.getName(); + if (name != null && isComicInfoName(name)) { return e; - } } - } - try { - int index = Integer.parseInt(imageName); - ZipEntry byIndex = findImageEntryByIndex(zipFile, index); - if (byIndex != null) { - return byIndex; + } + return null; + } + + private SevenZArchiveEntry findSevenZEntryByName(SevenZFile sevenZ, String imageName) { + if (imageName == null) return null; + for (SevenZArchiveEntry e : sevenZ.getEntries()) { + if (e == null || e.isDirectory()) continue; + String name = e.getName(); + if (name == null) continue; + if (name.equalsIgnoreCase(imageName)) return e; + // also allow base-name match + if (baseName(name).equalsIgnoreCase(baseName(imageName))) return e; + } + return null; + } + + private SevenZArchiveEntry findSevenZImageEntryByIndex(SevenZFile sevenZ, int index) { + int count = 0; + for (SevenZArchiveEntry e : sevenZ.getEntries()) { + if (!e.isDirectory() && isImageEntry(e.getName())) { + if (count == index) return e; + count++; } - if (index > 0) { - ZipEntry offByOne = findImageEntryByIndex(zipFile, index - 1); - if (offByOne != null) return offByOne; + } + return null; + } + + private SevenZArchiveEntry findFirstAlphabeticalSevenZImageEntry(SevenZFile sevenZ) { + List images = new ArrayList<>(); + for (SevenZArchiveEntry e : sevenZ.getEntries()) { + if (!e.isDirectory() && isImageEntry(e.getName())) { + images.add(e); } - } catch (NumberFormatException ignore) { - // ignore - } } - } catch (Exception e) { - log.warn("Failed to parse ComicInfo.xml for cover", e); - } + if (images.isEmpty()) return null; + images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); + return images.getFirst(); } - // Heuristic filenames before generic fallback - ZipEntry heuristic = findHeuristicCover(zipFile); - if (heuristic != null) return heuristic; - return findFirstAlphabeticalImageEntry(zipFile); - } - private ZipEntry findImageEntryByIndex(ZipFile zipFile, int index) { - Enumeration entries = zipFile.entries(); - int count = 0; - while (entries.hasMoreElements()) { - ZipEntry entry = entries.nextElement(); - if (!entry.isDirectory() && isImageEntry(entry.getName())) { - if (count == index) { - return entry; + private byte[] readSevenZEntryBytes(SevenZFile sevenZ, SevenZArchiveEntry entry) throws IOException { + try (InputStream is = sevenZ.getInputStream(entry); + ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + if (is == null) return null; + is.transferTo(baos); + return baos.toByteArray(); } - count++; - } } - return null; - } - private String findFrontCoverImageName(Document document) { - NodeList pages = document.getElementsByTagName("Page"); - for (int i = 0; i < pages.getLength(); i++) { - org.w3c.dom.Node node = pages.item(i); - if (node instanceof org.w3c.dom.Element page) { - String type = page.getAttribute("Type"); - if (type != null && "FrontCover".equalsIgnoreCase(type)) { - String imageFile = page.getAttribute("ImageFile"); - if (imageFile != null && !imageFile.isBlank()) { - return imageFile.trim(); - } - String image = page.getAttribute("Image"); - if (image != null && !image.isBlank()) { - return image.trim(); - } + private java.util.List listZipImageEntries(ZipFile zipFile) { + java.util.List images = new java.util.ArrayList<>(); + java.util.Enumeration en = zipFile.entries(); + while (en.hasMoreElements()) { + ZipEntry e = en.nextElement(); + if (!e.isDirectory() && isImageEntry(e.getName())) images.add(e); } - } + images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); + // Heuristic preferred names first + images.sort((a, b) -> Boolean.compare(!likelyCoverName(baseName(a.getName())), !likelyCoverName(baseName(b.getName())))); + return images; } - return null; - } - private boolean isImageEntry(String name) { - if (!isContentEntry(name)) return false; - String lower = name.toLowerCase(); - return ( - lower.endsWith(".jpg") || - lower.endsWith(".jpeg") || - lower.endsWith(".png") || - lower.endsWith(".gif") || - lower.endsWith(".bmp") || - lower.endsWith(".webp") - ); - } - - private boolean isContentEntry(String name) { - if (name == null) return false; - String norm = name.replace('\\', '/'); - if (norm.startsWith("__MACOSX/") || norm.contains("/__MACOSX/")) return false; - String base = baseName(norm); - if (base.startsWith(".")) return false; - if (".ds_store".equalsIgnoreCase(base)) return false; - return true; - } - - private byte[] generatePlaceholderCover(int width, int height) { - BufferedImage image = new BufferedImage( - width, - height, - BufferedImage.TYPE_INT_RGB - ); - Graphics2D g = image.createGraphics(); - - g.setColor(Color.LIGHT_GRAY); - g.fillRect(0, 0, width, height); - - g.setColor(Color.DARK_GRAY); - g.setFont(new Font("SansSerif", Font.BOLD, width / 10)); - FontMetrics fm = g.getFontMetrics(); - String text = "Preview Unavailable"; - - int textWidth = fm.stringWidth(text); - int textHeight = fm.getAscent(); - g.drawString(text, (width - textWidth) / 2, (height + textHeight) / 2); - - g.dispose(); - - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - ImageIO.write(image, "jpg", baos); - return baos.toByteArray(); - } catch (IOException e) { - log.warn("Failed to generate placeholder image", e); - return null; + private java.util.List listSevenZImageEntries(SevenZFile sevenZ) { + java.util.List images = new java.util.ArrayList<>(); + for (SevenZArchiveEntry e : sevenZ.getEntries()) { + if (!e.isDirectory() && isImageEntry(e.getName())) images.add(e); + } + images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); + images.sort((a, b) -> Boolean.compare(!likelyCoverName(baseName(a.getName())), !likelyCoverName(baseName(b.getName())))); + return images; } - } - - // ==== RAR (.cbr) helpers ==== - private FileHeader findComicInfoHeader(Archive archive) { - if (archive == null) return null; - for (FileHeader fh : archive.getFileHeaders()) { - String name = fh.getFileName(); - if (name == null) continue; - if (isComicInfoName(name)) { - return fh; - } + private java.util.List listRarImageHeaders(Archive archive) { + java.util.List images = new java.util.ArrayList<>(); + for (FileHeader fh : archive.getFileHeaders()) { + if (fh != null && !fh.isDirectory() && isImageEntry(fh.getFileName())) images.add(fh); + } + images.sort((a, b) -> naturalCompare(a.getFileName(), b.getFileName())); + images.sort((a, b) -> Boolean.compare(!likelyCoverName(baseName(a.getFileName())), !likelyCoverName(baseName(b.getFileName())))); + return images; } - return null; - } - private FileHeader findRarHeaderByName(Archive archive, String imageName) { - if (archive == null || imageName == null) return null; - for (FileHeader fh : archive.getFileHeaders()) { - String name = fh.getFileName(); - if (name == null) continue; - if (name.equalsIgnoreCase(imageName)) return fh; - // also try base-name match to be lenient - if (baseName(name).equalsIgnoreCase(baseName(imageName))) return fh; + private boolean likelyCoverName(String base) { + if (base == null) return false; + String n = base.toLowerCase(); + return n.startsWith("cover") || "folder".equals(n) || n.startsWith("front"); } - return null; - } - private FileHeader findRarImageHeaderByIndex(Archive archive, int index) { - int count = 0; - for (FileHeader fh : archive.getFileHeaders()) { - if (!fh.isDirectory() && isImageEntry(fh.getFileName())) { - if (count == index) return fh; - count++; - } + private int naturalCompare(String a, String b) { + if (a == null) return b == null ? 0 : -1; + if (b == null) return 1; + String s1 = a.toLowerCase(); + String s2 = b.toLowerCase(); + int i = 0, j = 0, n1 = s1.length(), n2 = s2.length(); + while (i < n1 && j < n2) { + char c1 = s1.charAt(i); + char c2 = s2.charAt(j); + if (Character.isDigit(c1) && Character.isDigit(c2)) { + int i1 = i; + while (i1 < n1 && Character.isDigit(s1.charAt(i1))) i1++; + int j1 = j; + while (j1 < n2 && Character.isDigit(s2.charAt(j1))) j1++; + String num1 = LEADING_ZEROS_PATTERN.matcher(s1.substring(i, i1)).replaceFirst(""); + String num2 = LEADING_ZEROS_PATTERN.matcher(s2.substring(j, j1)).replaceFirst(""); + int cmp = Integer.compare(num1.isEmpty() ? 0 : Integer.parseInt(num1), num2.isEmpty() ? 0 : Integer.parseInt(num2)); + if (cmp != 0) return cmp; + i = i1; + j = j1; + } else { + if (c1 != c2) return Character.compare(c1, c2); + i++; + j++; + } + } + return Integer.compare(n1 - i, n2 - j); } - return null; - } - private FileHeader findFirstImageHeader(Archive archive) { - for (FileHeader fh : archive.getFileHeaders()) { - if (!fh.isDirectory() && isImageEntry(fh.getFileName())) { - return fh; - } + private ZipEntry findHeuristicCover(ZipFile zipFile) { + java.util.List images = listZipImageEntries(zipFile); + for (ZipEntry e : images) { + if (likelyCoverName(baseName(e.getName()))) return e; + } + return null; } - return null; - } - private byte[] readRarEntryBytes(Archive archive, FileHeader header) { - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - archive.extractFile(header, baos); - return baos.toByteArray(); - } catch (Exception e) { - log.warn("Failed to read RAR entry bytes for {}", header != null ? header.getFileName() : "", e); - return null; + private static boolean isComicInfoName(String name) { + if (name == null) return false; + String n = name.replace('\\', '/'); + if (n.endsWith("/")) return false; + String lower = n.toLowerCase(); + return "comicinfo.xml".equals(lower) || lower.endsWith("/comicinfo.xml"); } - } - - private String baseName(String path) { - if (path == null) return null; - int slash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')); - return slash >= 0 ? path.substring(slash + 1) : path; - } - - private FileHeader findFirstAlphabeticalImageHeader(Archive archive) { - if (archive == null) return null; - List images = new ArrayList<>(); - for (FileHeader fh : archive.getFileHeaders()) { - if (fh == null || fh.isDirectory()) continue; - String name = fh.getFileName(); - if (name == null) continue; - if (isImageEntry(name)) { - images.add(fh); - } - } - if (images.isEmpty()) return null; - images.sort((a, b) -> naturalCompare(a.getFileName(), b.getFileName())); - return images.getFirst(); - } - - private ZipEntry findFirstAlphabeticalImageEntry(ZipFile zipFile) { - List images = new ArrayList<>(); - Enumeration entries = zipFile.entries(); - while (entries.hasMoreElements()) { - ZipEntry e = entries.nextElement(); - if (!e.isDirectory() && isImageEntry(e.getName())) { - images.add(e); - } - } - if (images.isEmpty()) return null; - images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); - return images.getFirst(); - } - - // ==== 7z (.cb7) helpers ==== - private SevenZArchiveEntry findSevenZComicInfoEntry(SevenZFile sevenZ) { - for (SevenZArchiveEntry e : sevenZ.getEntries()) { - if (e == null || e.isDirectory()) continue; - String name = e.getName(); - if (name != null && isComicInfoName(name)) { - return e; - } - } - return null; - } - - private SevenZArchiveEntry findSevenZEntryByName(SevenZFile sevenZ, String imageName) { - if (imageName == null) return null; - for (SevenZArchiveEntry e : sevenZ.getEntries()) { - if (e == null || e.isDirectory()) continue; - String name = e.getName(); - if (name == null) continue; - if (name.equalsIgnoreCase(imageName)) return e; - // also allow base-name match - if (baseName(name).equalsIgnoreCase(baseName(imageName))) return e; - } - return null; - } - - private SevenZArchiveEntry findSevenZImageEntryByIndex(SevenZFile sevenZ, int index) { - int count = 0; - for (SevenZArchiveEntry e : sevenZ.getEntries()) { - if (!e.isDirectory() && isImageEntry(e.getName())) { - if (count == index) return e; - count++; - } - } - return null; - } - - private SevenZArchiveEntry findFirstAlphabeticalSevenZImageEntry(SevenZFile sevenZ) { - List images = new ArrayList<>(); - for (SevenZArchiveEntry e : sevenZ.getEntries()) { - if (!e.isDirectory() && isImageEntry(e.getName())) { - images.add(e); - } - } - if (images.isEmpty()) return null; - images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); - return images.getFirst(); - } - - private byte[] readSevenZEntryBytes(SevenZFile sevenZ, SevenZArchiveEntry entry) throws IOException { - try (InputStream is = sevenZ.getInputStream(entry); - ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - if (is == null) return null; - is.transferTo(baos); - return baos.toByteArray(); - } - } - - private java.util.List listZipImageEntries(ZipFile zipFile) { - java.util.List images = new java.util.ArrayList<>(); - java.util.Enumeration en = zipFile.entries(); - while (en.hasMoreElements()) { - ZipEntry e = en.nextElement(); - if (!e.isDirectory() && isImageEntry(e.getName())) images.add(e); - } - images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); - // Heuristic preferred names first - images.sort((a, b) -> Boolean.compare(!likelyCoverName(baseName(a.getName())), !likelyCoverName(baseName(b.getName())))); - return images; - } - - private java.util.List listSevenZImageEntries(SevenZFile sevenZ) { - java.util.List images = new java.util.ArrayList<>(); - for (SevenZArchiveEntry e : sevenZ.getEntries()) { - if (!e.isDirectory() && isImageEntry(e.getName())) images.add(e); - } - images.sort((a, b) -> naturalCompare(a.getName(), b.getName())); - images.sort((a, b) -> Boolean.compare(!likelyCoverName(baseName(a.getName())), !likelyCoverName(baseName(b.getName())))); - return images; - } - - private java.util.List listRarImageHeaders(Archive archive) { - java.util.List images = new java.util.ArrayList<>(); - for (FileHeader fh : archive.getFileHeaders()) { - if (fh != null && !fh.isDirectory() && isImageEntry(fh.getFileName())) images.add(fh); - } - images.sort((a, b) -> naturalCompare(a.getFileName(), b.getFileName())); - images.sort((a, b) -> Boolean.compare(!likelyCoverName(baseName(a.getFileName())), !likelyCoverName(baseName(b.getFileName())))); - return images; - } - - private boolean likelyCoverName(String base) { - if (base == null) return false; - String n = base.toLowerCase(); - return n.startsWith("cover") || "folder".equals(n) || n.startsWith("front"); - } - - private int naturalCompare(String a, String b) { - if (a == null) return b == null ? 0 : -1; - if (b == null) return 1; - String s1 = a.toLowerCase(); - String s2 = b.toLowerCase(); - int i = 0, j = 0, n1 = s1.length(), n2 = s2.length(); - while (i < n1 && j < n2) { - char c1 = s1.charAt(i); - char c2 = s2.charAt(j); - if (Character.isDigit(c1) && Character.isDigit(c2)) { - int i1 = i; while (i1 < n1 && Character.isDigit(s1.charAt(i1))) i1++; - int j1 = j; while (j1 < n2 && Character.isDigit(s2.charAt(j1))) j1++; - String num1 = LEADING_ZEROS_PATTERN.matcher(s1.substring(i, i1)).replaceFirst(""); - String num2 = LEADING_ZEROS_PATTERN.matcher(s2.substring(j, j1)).replaceFirst(""); - int cmp = Integer.compare(num1.isEmpty() ? 0 : Integer.parseInt(num1), num2.isEmpty() ? 0 : Integer.parseInt(num2)); - if (cmp != 0) return cmp; - i = i1; j = j1; - } else { - if (c1 != c2) return Character.compare(c1, c2); - i++; j++; - } - } - return Integer.compare(n1 - i, n2 - j); - } - - private ZipEntry findHeuristicCover(ZipFile zipFile) { - java.util.List images = listZipImageEntries(zipFile); - for (ZipEntry e : images) { - if (likelyCoverName(baseName(e.getName()))) return e; - } - return null; - } - - private static boolean isComicInfoName(String name) { - if (name == null) return false; - String n = name.replace('\\', '/'); - if (n.endsWith("/")) return false; - String lower = n.toLowerCase(); - return "comicinfo.xml".equals(lower) || lower.endsWith("/comicinfo.xml"); - } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriter.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriter.java index be19f765d..b45e1ccd9 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriter.java @@ -1,10 +1,13 @@ package com.adityachandel.booklore.service.metadata.writer; import com.adityachandel.booklore.model.MetadataClearFlags; +import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.github.junrar.Archive; import com.github.junrar.rarfile.FileHeader; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry; import org.apache.commons.compress.archivers.sevenz.SevenZFile; @@ -38,414 +41,509 @@ import java.util.zip.ZipOutputStream; @Slf4j @Component +@RequiredArgsConstructor public class CbxMetadataWriter implements MetadataWriter { private static final Pattern VALID_FILENAME_PATTERN = Pattern.compile("^[\\w./\\\\-]+$"); + private static final int BUFFER_SIZE = 8192; + + private final AppSettingService appSettingService; @Override - public void writeMetadataToFile(File file, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clearFlags) { - Path backup = null; - Path tempDir = null; - Path tempFile = null; - boolean writeSucceeded = false; - try { - // Create a backup next to the source file (temp name, safe to delete later) - backup = Files.createTempFile(file.getParentFile().toPath(), "cbx_backup_", ".bak"); - Files.copy(file.toPath(), backup, StandardCopyOption.REPLACE_EXISTING); - } catch (Exception ex) { - log.warn("Unable to create backup for {}: {}", file.getAbsolutePath(), ex.getMessage(), ex); + public void saveMetadataToFile(File file, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clearFlags) { + if (!shouldSaveMetadataToFile(file)) { + return; } + String fileName = file.getName().toLowerCase(Locale.ROOT); + boolean isCbz = fileName.endsWith(".cbz"); + boolean isCbr = fileName.endsWith(".cbr"); + boolean isCb7 = fileName.endsWith(".cb7"); + + if (!isCbz && !isCbr && !isCb7) { + log.warn("Unsupported file type for CBX writer: {}", file.getName()); + return; + } + + Path backupPath = createBackupFile(file); + Path extractDir = null; + Path tempArchive = null; + boolean writeSucceeded = false; + try { - String nameLower = file.getName().toLowerCase(Locale.ROOT); - boolean isCbz = nameLower.endsWith(".cbz"); - boolean isCbr = nameLower.endsWith(".cbr"); - boolean isCb7 = nameLower.endsWith(".cb7"); + Document xmlDoc = loadOrCreateComicInfoXml(file, isCbz, isCb7, isCbr); + applyMetadataChanges(xmlDoc, metadata, clearFlags); + byte[] xmlContent = convertDocumentToBytes(xmlDoc); - if (!isCbz && !isCbr && !isCb7) { - log.warn("Unsupported file type for CBX writer: {}", file.getName()); - return; - } - - // Build (or load and update) ComicInfo.xml as a Document - Document doc; if (isCbz) { - try (ZipFile zipFile = new ZipFile(file)) { - ZipEntry existing = findComicInfoEntry(zipFile); - if (existing != null) { - try (InputStream is = zipFile.getInputStream(existing)) { - doc = buildSecureDocument(is); - } - } else { - doc = newEmptyComicInfo(); - } - } + tempArchive = updateZipArchive(file, xmlContent); + writeSucceeded = true; } else if (isCb7) { - try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get()) { - SevenZArchiveEntry existing = null; - for (SevenZArchiveEntry e : sevenZ.getEntries()) { - if (e != null && !e.isDirectory() && isComicInfoName(e.getName())) { - existing = e; - break; - } - } - if (existing != null) { - try (InputStream is = sevenZ.getInputStream(existing)) { - doc = buildSecureDocument(is); - } - } else { - doc = newEmptyComicInfo(); - } - } - } else { // CBR - try (Archive archive = new Archive(file)) { - FileHeader existing = findComicInfoHeader(archive); - if (existing != null) { - try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { - archive.extractFile(existing, baos); - try (InputStream is = new java.io.ByteArrayInputStream(baos.toByteArray())) { - doc = buildSecureDocument(is); - } - } - } else { - doc = newEmptyComicInfo(); - } - } - } - - // Apply metadata to the Document - Element root = doc.getDocumentElement(); - MetadataCopyHelper helper = new MetadataCopyHelper(metadata); - helper.copyTitle(clearFlags != null && clearFlags.isTitle(), val -> setElement(doc, root, "Title", val)); - helper.copyDescription(clearFlags != null && clearFlags.isDescription(), val -> { - setElement(doc, root, "Summary", val); - removeElement(root, "Description"); - }); - helper.copyPublisher(clearFlags != null && clearFlags.isPublisher(), val -> setElement(doc, root, "Publisher", val)); - helper.copySeriesName(clearFlags != null && clearFlags.isSeriesName(), val -> setElement(doc, root, "Series", val)); - helper.copySeriesNumber(clearFlags != null && clearFlags.isSeriesNumber(), val -> setElement(doc, root, "Number", formatFloat(val))); - helper.copySeriesTotal(clearFlags != null && clearFlags.isSeriesTotal(), val -> setElement(doc, root, "Count", val != null ? val.toString() : null)); - helper.copyPublishedDate(clearFlags != null && clearFlags.isPublishedDate(), date -> setDateElements(doc, root, date)); - helper.copyPageCount(clearFlags != null && clearFlags.isPageCount(), val -> setElement(doc, root, "PageCount", val != null ? val.toString() : null)); - helper.copyLanguage(clearFlags != null && clearFlags.isLanguage(), val -> setElement(doc, root, "LanguageISO", val)); - helper.copyAuthors(clearFlags != null && clearFlags.isAuthors(), set -> { - setElement(doc, root, "Writer", join(set)); - removeElement(root, "Penciller"); - removeElement(root, "Inker"); - removeElement(root, "Colorist"); - removeElement(root, "Letterer"); - removeElement(root, "CoverArtist"); - }); - helper.copyCategories(clearFlags != null && clearFlags.isCategories(), set -> { - setElement(doc, root, "Genre", join(set)); - removeElement(root, "Tags"); - }); - - // Serialize ComicInfo.xml - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - ByteArrayOutputStream xmlBaos = new ByteArrayOutputStream(); - transformer.transform(new DOMSource(doc), new StreamResult(xmlBaos)); - byte[] xmlBytes = xmlBaos.toByteArray(); - - // Repack depending on container type; always write to a temp target then atomic move - if (isCbz) { - tempFile = Files.createTempFile("cbx_edit", ".cbz"); - repackZipReplacingComicInfo(file.toPath(), tempFile, xmlBytes); - atomicReplace(tempFile, file.toPath()); - tempFile = null; // Successfully moved, don't delete in finally + tempArchive = convert7zToZip(file, xmlContent); writeSucceeded = true; - return; - } - - if (isCb7) { - // Convert to CBZ with updated ComicInfo.xml - tempFile = Files.createTempFile("cbx_edit", ".cbz"); - try (SevenZFile sevenZ = SevenZFile.builder().setFile(file).get(); - ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(tempFile))) { - for (SevenZArchiveEntry e : sevenZ.getEntries()) { - if (e.isDirectory()) continue; - String entryName = e.getName(); - if (isComicInfoName(entryName)) continue; // skip old - if (!isSafeEntryName(entryName)) { - log.warn("Skipping unsafe 7z entry name: {}", entryName); - continue; - } - zos.putNextEntry(new ZipEntry(entryName)); - try (InputStream is = sevenZ.getInputStream(e)) { - if (is != null) is.transferTo(zos); - } - zos.closeEntry(); - } - zos.putNextEntry(new ZipEntry("ComicInfo.xml")); - zos.write(xmlBytes); - zos.closeEntry(); - } - Path target = file.toPath().resolveSibling(stripExtension(file.getName()) + ".cbz"); - atomicReplace(tempFile, target); - tempFile = null; // Successfully moved, don't delete in finally - try { - Files.deleteIfExists(file.toPath()); - } catch (Exception ignored) { - } - writeSucceeded = true; - return; - } - - // CBR path - String rarBin = System.getenv().getOrDefault("BOOKLORE_RAR_BIN", "rar"); - boolean rarAvailable = isRarAvailable(rarBin); - - if (rarAvailable) { - tempDir = Files.createTempDirectory("cbx_rar_"); - // Extract entire RAR into a temp directory - try (Archive archive = new Archive(file)) { - for (FileHeader fh : archive.getFileHeaders()) { - String name = fh.getFileName(); - if (name == null || name.isBlank()) continue; - if (!isSafeEntryName(name)) { - log.warn("Skipping unsafe RAR entry name: {}", name); - continue; - } - Path out = tempDir.resolve(name).normalize(); - if (!out.startsWith(tempDir)) { - log.warn("Skipping traversal entry outside tempDir: {}", name); - continue; - } - if (fh.isDirectory()) { - Files.createDirectories(out); - } else { - Files.createDirectories(out.getParent()); - try (OutputStream os = Files.newOutputStream(out, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { - archive.extractFile(fh, os); - } - } - } - } - - // Write/replace ComicInfo.xml in extracted tree root - Path comicInfo = tempDir.resolve("ComicInfo.xml"); - Files.write(comicInfo, xmlBytes); - - // Rebuild RAR in-place (replace original file) - Path targetRar = file.toPath().toAbsolutePath().normalize(); - String rarExec = isSafeExecutable(rarBin) ? rarBin : "rar"; // prefer validated path, then PATH lookup - ProcessBuilder pb = new ProcessBuilder(rarExec, "a", "-idq", "-ep1", "-ma5", targetRar.toString(), "."); - pb.directory(tempDir.toFile()); - Process p = pb.start(); - int code = p.waitFor(); - if (code == 0) { - writeSucceeded = true; - return; - } else { - log.warn("RAR creation failed with exit code {}. Falling back to CBZ conversion for {}", code, file.getName()); - } } else { - log.warn("`rar` binary not found. Falling back to CBZ conversion for {}", file.getName()); + tempArchive = updateRarArchive(file, xmlContent, extractDir); + writeSucceeded = true; } - - // Fallback: convert the CBR to CBZ containing updated ComicInfo.xml - tempFile = Files.createTempFile("cbx_edit", ".cbz"); - try (Archive archive = new Archive(file); - ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(tempFile))) { - for (FileHeader fh : archive.getFileHeaders()) { - if (fh.isDirectory()) continue; - String entryName = fh.getFileName(); - if (isComicInfoName(entryName)) continue; // skip old - if (!isSafeEntryName(entryName)) { - log.warn("Skipping unsafe RAR entry name: {}", entryName); - continue; - } - zos.putNextEntry(new ZipEntry(entryName)); - archive.extractFile(fh, zos); - zos.closeEntry(); - } - zos.putNextEntry(new ZipEntry("ComicInfo.xml")); - zos.write(xmlBytes); - zos.closeEntry(); - } - Path target = file.toPath().resolveSibling(stripExtension(file.getName()) + ".cbz"); - atomicReplace(tempFile, target); - tempFile = null; // Successfully moved, don't delete in finally - try { - Files.deleteIfExists(file.toPath()); - } catch (Exception ignored) { - } - writeSucceeded = true; } catch (Exception e) { - // Attempt to restore the original file from backup - try { - if (backup != null) { - Files.copy(backup, file.toPath(), StandardCopyOption.REPLACE_EXISTING); - log.info("Restored original file from backup after failure: {}", file.getAbsolutePath()); - } - } catch (Exception restoreEx) { - log.warn("Failed to restore original file from backup: {} -> {}", backup, file.getAbsolutePath(), restoreEx); - } + restoreOriginalFile(backupPath, file); log.warn("Failed to write metadata for {}: {}", file.getName(), e.getMessage(), e); } finally { - // Clean up temporary file if it wasn't successfully moved - if (tempFile != null) { - try { - Files.deleteIfExists(tempFile); - } catch (Exception e) { - log.warn("Failed to delete temp file: {}", tempFile, e); + cleanupTempFiles(tempArchive, extractDir, backupPath, writeSucceeded); + } + } + + public boolean shouldSaveMetadataToFile(File file) { + MetadataPersistenceSettings.SaveToOriginalFile settings = appSettingService.getAppSettings().getMetadataPersistenceSettings().getSaveToOriginalFile(); + + MetadataPersistenceSettings.FormatSettings cbxSettings = settings.getCbx(); + if (cbxSettings == null || !cbxSettings.isEnabled()) { + log.debug("CBX metadata writing is disabled. Skipping: {}", file.getName()); + return false; + } + + long fileSizeInMb = file.length() / (1024 * 1024); + if (fileSizeInMb > cbxSettings.getMaxFileSizeInMb()) { + log.info("CBX file {} ({} MB) exceeds max size limit ({} MB). Skipping metadata write.", file.getName(), fileSizeInMb, cbxSettings.getMaxFileSizeInMb()); + return false; + } + + return true; + } + + private Path createBackupFile(File file) { + try { + Path backupPath = Files.createTempFile(file.getParentFile().toPath(), "cbx_backup_", ".bak"); + Files.copy(file.toPath(), backupPath, StandardCopyOption.REPLACE_EXISTING); + return backupPath; + } catch (Exception ex) { + log.warn("Unable to create backup for {}: {}", file.getAbsolutePath(), ex.getMessage(), ex); + return null; + } + } + + private Document loadOrCreateComicInfoXml(File file, boolean isCbz, boolean isCb7, boolean isCbr) throws Exception { + if (isCbz) { + return loadXmlFromZip(file); + } else if (isCb7) { + return loadXmlFrom7z(file); + } else { + return loadXmlFromRar(file); + } + } + + private Document loadXmlFromZip(File file) throws Exception { + try (ZipFile zipFile = new ZipFile(file)) { + ZipEntry xmlEntry = findComicInfoEntry(zipFile); + if (xmlEntry != null) { + try (InputStream stream = zipFile.getInputStream(xmlEntry)) { + return parseXmlSecurely(stream); } } + return createEmptyComicInfoXml(); + } + } - // Clean up temporary directory if it was created - if (tempDir != null) { - deleteDirectoryRecursively(tempDir); + private Document loadXmlFrom7z(File file) throws Exception { + try (SevenZFile archive = SevenZFile.builder().setFile(file).get()) { + SevenZArchiveEntry xmlEntry = findComicInfoIn7z(archive); + if (xmlEntry != null) { + try (InputStream stream = archive.getInputStream(xmlEntry)) { + return parseXmlSecurely(stream); + } + } + return createEmptyComicInfoXml(); + } + } + + private SevenZArchiveEntry findComicInfoIn7z(SevenZFile archive) { + for (SevenZArchiveEntry entry : archive.getEntries()) { + if (entry != null && !entry.isDirectory() && isComicInfoXml(entry.getName())) { + return entry; + } + } + return null; + } + + private Document loadXmlFromRar(File file) throws Exception { + try (Archive archive = new Archive(file)) { + FileHeader xmlHeader = findComicInfoInRar(archive); + if (xmlHeader != null) { + try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) { + extractRarEntry(archive, xmlHeader, buffer); + try (InputStream stream = new ByteArrayInputStream(buffer.toByteArray())) { + return parseXmlSecurely(stream); + } + } + } + return createEmptyComicInfoXml(); + } + } + + private void applyMetadataChanges(Document xmlDoc, BookMetadataEntity metadata, MetadataClearFlags clearFlags) { + Element rootElement = xmlDoc.getDocumentElement(); + MetadataCopyHelper helper = new MetadataCopyHelper(metadata); + + helper.copyTitle(clearFlags != null && clearFlags.isTitle(), val -> updateXmlElement(xmlDoc, rootElement, "Title", val)); + helper.copyDescription(clearFlags != null && clearFlags.isDescription(), val -> { + updateXmlElement(xmlDoc, rootElement, "Summary", val); + removeXmlElement(rootElement, "Description"); + }); + helper.copyPublisher(clearFlags != null && clearFlags.isPublisher(), val -> updateXmlElement(xmlDoc, rootElement, "Publisher", val)); + helper.copySeriesName(clearFlags != null && clearFlags.isSeriesName(), val -> updateXmlElement(xmlDoc, rootElement, "Series", val)); + helper.copySeriesNumber(clearFlags != null && clearFlags.isSeriesNumber(), val -> updateXmlElement(xmlDoc, rootElement, "Number", formatFloatValue(val))); + helper.copySeriesTotal(clearFlags != null && clearFlags.isSeriesTotal(), val -> updateXmlElement(xmlDoc, rootElement, "Count", val != null ? val.toString() : null)); + helper.copyPublishedDate(clearFlags != null && clearFlags.isPublishedDate(), date -> updateDateElements(xmlDoc, rootElement, date)); + helper.copyPageCount(clearFlags != null && clearFlags.isPageCount(), val -> updateXmlElement(xmlDoc, rootElement, "PageCount", val != null ? val.toString() : null)); + helper.copyLanguage(clearFlags != null && clearFlags.isLanguage(), val -> updateXmlElement(xmlDoc, rootElement, "LanguageISO", val)); + helper.copyAuthors(clearFlags != null && clearFlags.isAuthors(), set -> { + updateXmlElement(xmlDoc, rootElement, "Writer", joinStrings(set)); + removeXmlElement(rootElement, "Penciller"); + removeXmlElement(rootElement, "Inker"); + removeXmlElement(rootElement, "Colorist"); + removeXmlElement(rootElement, "Letterer"); + removeXmlElement(rootElement, "CoverArtist"); + }); + helper.copyCategories(clearFlags != null && clearFlags.isCategories(), set -> { + updateXmlElement(xmlDoc, rootElement, "Genre", joinStrings(set)); + removeXmlElement(rootElement, "Tags"); + }); + } + + private byte[] convertDocumentToBytes(Document xmlDoc) throws Exception { + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + transformer.transform(new DOMSource(xmlDoc), new StreamResult(outputStream)); + return outputStream.toByteArray(); + } + + private Path updateZipArchive(File originalFile, byte[] xmlContent) throws Exception { + Path tempArchive = Files.createTempFile("cbx_edit", ".cbz"); + rebuildZipWithNewXml(originalFile.toPath(), tempArchive, xmlContent); + replaceFileAtomic(tempArchive, originalFile.toPath()); + return null; // temp file already moved + } + + private Path convert7zToZip(File original7z, byte[] xmlContent) throws Exception { + Path tempZip = Files.createTempFile("cbx_edit", ".cbz"); + repack7zToZipWithXml(original7z, tempZip, xmlContent); + + Path targetPath = original7z.toPath().resolveSibling(removeFileExtension(original7z.getName()) + ".cbz"); + replaceFileAtomic(tempZip, targetPath); + + try { + Files.deleteIfExists(original7z.toPath()); + } catch (Exception ignored) { + } + return null; + } + + private void repack7zToZipWithXml(File source7z, Path targetZip, byte[] xmlContent) throws Exception { + try (SevenZFile archive = SevenZFile.builder().setFile(source7z).get(); + ZipOutputStream zipOutput = new ZipOutputStream(Files.newOutputStream(targetZip))) { + + for (SevenZArchiveEntry entry : archive.getEntries()) { + if (entry.isDirectory()) continue; + String entryName = entry.getName(); + if (isComicInfoXml(entryName)) continue; + if (!isPathSafe(entryName)) { + log.warn("Skipping unsafe 7z entry name: {}", entryName); + continue; + } + + zipOutput.putNextEntry(new ZipEntry(entryName)); + try (InputStream entryStream = archive.getInputStream(entry)) { + if (entryStream != null) copyStream(entryStream, zipOutput); + } + zipOutput.closeEntry(); } - // Clean up backup file if write succeeded - if (writeSucceeded && backup != null) { - try { - Files.deleteIfExists(backup); - } catch (Exception e) { - log.warn("Failed to delete backup file: {}", backup, e); + zipOutput.putNextEntry(new ZipEntry("ComicInfo.xml")); + zipOutput.write(xmlContent); + zipOutput.closeEntry(); + } + } + + private Path updateRarArchive(File originalRar, byte[] xmlContent, Path extractDir) throws Exception { + String rarCommand = System.getenv().getOrDefault("BOOKLORE_RAR_BIN", "rar"); + boolean rarAvailable = checkRarAvailability(rarCommand); + + if (rarAvailable) { + return updateRarWithCommand(originalRar, xmlContent, rarCommand, extractDir); + } else { + log.warn("`rar` binary not found. Falling back to CBZ conversion for {}", originalRar.getName()); + return convertRarToZipArchive(originalRar, xmlContent); + } + } + + private Path updateRarWithCommand(File originalRar, byte[] xmlContent, String rarCommand, Path extractDir) throws Exception { + extractDir = Files.createTempDirectory("cbx_rar_"); + extractRarContents(originalRar, extractDir); + + Path xmlPath = extractDir.resolve("ComicInfo.xml"); + Files.write(xmlPath, xmlContent); + + Path targetRar = originalRar.toPath().toAbsolutePath().normalize(); + String safeCommand = isExecutableSafe(rarCommand) ? rarCommand : "rar"; + ProcessBuilder processBuilder = new ProcessBuilder(safeCommand, "a", "-idq", "-ep1", "-ma5", targetRar.toString(), "."); + processBuilder.directory(extractDir.toFile()); + Process process = processBuilder.start(); + int exitCode = process.waitFor(); + + if (exitCode == 0) { + return null; + } else { + log.warn("RAR creation failed with exit code {}. Falling back to CBZ conversion for {}", exitCode, originalRar.getName()); + return convertRarToZipArchive(originalRar, xmlContent); + } + } + + private void extractRarContents(File rarFile, Path targetDir) throws Exception { + try (Archive archive = new Archive(rarFile)) { + for (FileHeader header : archive.getFileHeaders()) { + String entryName = header.getFileName(); + if (entryName == null || entryName.isBlank()) continue; + if (!isPathSafe(entryName)) { + log.warn("Skipping unsafe RAR entry name: {}", entryName); + continue; + } + + Path outputPath = targetDir.resolve(entryName).normalize(); + if (!outputPath.startsWith(targetDir)) { + log.warn("Skipping traversal entry outside tempDir: {}", entryName); + continue; + } + + if (header.isDirectory()) { + Files.createDirectories(outputPath); + } else { + Files.createDirectories(outputPath.getParent()); + try (OutputStream fileOutput = Files.newOutputStream(outputPath, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING)) { + extractRarEntry(archive, header, fileOutput); + } } } } } - // ----------------------- helpers ----------------------- + private Path convertRarToZipArchive(File rarFile, byte[] xmlContent) throws Exception { + Path tempZip = Files.createTempFile("cbx_edit", ".cbz"); + + try (Archive rarArchive = new Archive(rarFile); + ZipOutputStream zipOutput = new ZipOutputStream(Files.newOutputStream(tempZip))) { + + for (FileHeader header : rarArchive.getFileHeaders()) { + if (header.isDirectory()) continue; + String entryName = header.getFileName(); + if (isComicInfoXml(entryName)) continue; + if (!isPathSafe(entryName)) { + log.warn("Skipping unsafe RAR entry name: {}", entryName); + continue; + } + + zipOutput.putNextEntry(new ZipEntry(entryName)); + extractRarEntry(rarArchive, header, zipOutput); + zipOutput.closeEntry(); + } + + zipOutput.putNextEntry(new ZipEntry("ComicInfo.xml")); + zipOutput.write(xmlContent); + zipOutput.closeEntry(); + } + + Path targetPath = rarFile.toPath().resolveSibling(removeFileExtension(rarFile.getName()) + ".cbz"); + replaceFileAtomic(tempZip, targetPath); + + try { + Files.deleteIfExists(rarFile.toPath()); + } catch (Exception ignored) { + } + + return null; + } + + private void restoreOriginalFile(Path backupPath, File targetFile) { + try { + if (backupPath != null) { + Files.copy(backupPath, targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + log.info("Restored original file from backup after failure: {}", targetFile.getAbsolutePath()); + } + } catch (Exception restoreException) { + log.warn("Failed to restore original file from backup: {} -> {}", backupPath, targetFile.getAbsolutePath(), restoreException); + } + } + + private void cleanupTempFiles(Path tempArchive, Path extractDir, Path backupPath, boolean writeSucceeded) { + if (tempArchive != null) { + try { + Files.deleteIfExists(tempArchive); + } catch (Exception e) { + log.warn("Failed to delete temp file: {}", tempArchive, e); + } + } + + if (extractDir != null) { + deleteDirectoryRecursively(extractDir); + } + + if (writeSucceeded && backupPath != null) { + try { + Files.deleteIfExists(backupPath); + } catch (Exception e) { + log.warn("Failed to delete backup file: {}", backupPath, e); + } + } + } private ZipEntry findComicInfoEntry(ZipFile zipFile) { Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); - String n = entry.getName(); - if (isComicInfoName(n)) return entry; + String entryName = entry.getName(); + if (isComicInfoXml(entryName)) return entry; } return null; } - private FileHeader findComicInfoHeader(Archive archive) { - for (FileHeader fh : archive.getFileHeaders()) { - String name = fh.getFileName(); - if (name != null && isComicInfoName(name)) return fh; + private FileHeader findComicInfoInRar(Archive archive) { + for (FileHeader header : archive.getFileHeaders()) { + String entryName = header.getFileName(); + if (entryName != null && isComicInfoXml(entryName)) return header; } return null; } - private Document buildSecureDocument(InputStream is) throws Exception { + private Document parseXmlSecurely(InputStream xmlStream) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); factory.setExpandEntityReferences(false); DocumentBuilder builder = factory.newDocumentBuilder(); - return builder.parse(is); + return builder.parse(xmlStream); } - private Document newEmptyComicInfo() throws Exception { + private Document createEmptyComicInfoXml() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); DocumentBuilder builder = factory.newDocumentBuilder(); - Document doc = builder.newDocument(); - doc.appendChild(doc.createElement("ComicInfo")); - return doc; + Document xmlDoc = builder.newDocument(); + xmlDoc.appendChild(xmlDoc.createElement("ComicInfo")); + return xmlDoc; } - private void setElement(Document doc, Element root, String tag, String value) { - removeElement(root, tag); + private void updateXmlElement(Document xmlDoc, Element rootElement, String tagName, String value) { + removeXmlElement(rootElement, tagName); if (value != null && !value.isBlank()) { - Element el = doc.createElement(tag); - el.setTextContent(value); - root.appendChild(el); + Element element = xmlDoc.createElement(tagName); + element.setTextContent(value); + rootElement.appendChild(element); } } - private void removeElement(Element root, String tag) { - NodeList nodes = root.getElementsByTagName(tag); + private void removeXmlElement(Element rootElement, String tagName) { + NodeList nodes = rootElement.getElementsByTagName(tagName); for (int i = nodes.getLength() - 1; i >= 0; i--) { - root.removeChild(nodes.item(i)); + rootElement.removeChild(nodes.item(i)); } } - private void setDateElements(Document doc, Element root, LocalDate date) { + private void updateDateElements(Document xmlDoc, Element rootElement, LocalDate date) { if (date == null) { - removeElement(root, "Year"); - removeElement(root, "Month"); - removeElement(root, "Day"); + removeXmlElement(rootElement, "Year"); + removeXmlElement(rootElement, "Month"); + removeXmlElement(rootElement, "Day"); return; } - setElement(doc, root, "Year", Integer.toString(date.getYear())); - setElement(doc, root, "Month", Integer.toString(date.getMonthValue())); - setElement(doc, root, "Day", Integer.toString(date.getDayOfMonth())); + updateXmlElement(xmlDoc, rootElement, "Year", Integer.toString(date.getYear())); + updateXmlElement(xmlDoc, rootElement, "Month", Integer.toString(date.getMonthValue())); + updateXmlElement(xmlDoc, rootElement, "Day", Integer.toString(date.getDayOfMonth())); } - private String join(Set set) { - return (set == null || set.isEmpty()) ? null : String.join(", ", set); + private String joinStrings(Set values) { + return (values == null || values.isEmpty()) ? null : String.join(", ", values); } - private String formatFloat(Float val) { - if (val == null) return null; - if (val % 1 == 0) return Integer.toString(val.intValue()); - return val.toString(); + private String formatFloatValue(Float value) { + if (value == null) return null; + if (value % 1 == 0) return Integer.toString(value.intValue()); + return value.toString(); } - private static boolean isComicInfoName(String name) { - if (name == null) return false; - String n = name.replace('\\', '/'); - if (n.endsWith("/")) return false; - String lower = n.toLowerCase(Locale.ROOT); - return "comicinfo.xml".equals(lower) || lower.endsWith("/comicinfo.xml"); + private static boolean isComicInfoXml(String entryName) { + if (entryName == null) return false; + String normalized = entryName.replace('\\', '/'); + if (normalized.endsWith("/")) return false; + String lowerCase = normalized.toLowerCase(Locale.ROOT); + return "comicinfo.xml".equals(lowerCase) || lowerCase.endsWith("/comicinfo.xml"); } - private static boolean isSafeEntryName(String name) { - if (name == null || name.isBlank()) return false; - String n = name.replace('\\', '/'); - if (n.startsWith("/")) return false; // absolute - if (n.contains("../")) return false; // traversal - if (n.contains("\0")) return false; // NUL + private static boolean isPathSafe(String entryName) { + if (entryName == null || entryName.isBlank()) return false; + String normalized = entryName.replace('\\', '/'); + if (normalized.startsWith("/")) return false; + if (normalized.contains("../")) return false; + if (normalized.contains("\0")) return false; return true; } - private void repackZipReplacingComicInfo(Path sourceZip, Path targetZip, byte[] xmlBytes) throws Exception { + private void rebuildZipWithNewXml(Path sourceZip, Path targetZip, byte[] xmlContent) throws Exception { try (ZipFile zipFile = new ZipFile(sourceZip.toFile()); - ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(targetZip))) { - ZipEntry existing = findComicInfoEntry(zipFile); + ZipOutputStream zipOutput = new ZipOutputStream(Files.newOutputStream(targetZip))) { + ZipEntry existingXml = findComicInfoEntry(zipFile); Enumeration entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); String entryName = entry.getName(); - if (existing != null && entryName.equals(existing.getName())) { - continue; // skip old ComicInfo.xml + if (existingXml != null && entryName.equals(existingXml.getName())) { + continue; } - if (!isSafeEntryName(entryName)) { + if (!isPathSafe(entryName)) { log.warn("Skipping unsafe ZIP entry name: {}", entryName); continue; } - zos.putNextEntry(new ZipEntry(entryName)); - try (InputStream is = zipFile.getInputStream(entry)) { - is.transferTo(zos); + zipOutput.putNextEntry(new ZipEntry(entryName)); + try (InputStream entryStream = zipFile.getInputStream(entry)) { + copyStream(entryStream, zipOutput); } - zos.closeEntry(); + zipOutput.closeEntry(); } - String entryName = (existing != null ? existing.getName() : "ComicInfo.xml"); - zos.putNextEntry(new ZipEntry(entryName)); - zos.write(xmlBytes); - zos.closeEntry(); + String xmlEntryName = (existingXml != null ? existingXml.getName() : "ComicInfo.xml"); + zipOutput.putNextEntry(new ZipEntry(xmlEntryName)); + zipOutput.write(xmlContent); + zipOutput.closeEntry(); } } - private static void atomicReplace(Path temp, Path target) throws Exception { + private void copyStream(InputStream input, OutputStream output) throws IOException { + byte[] buffer = new byte[BUFFER_SIZE]; + int bytesRead; + while ((bytesRead = input.read(buffer)) != -1) { + output.write(buffer, 0, bytesRead); + } + } + + private void extractRarEntry(Archive archive, FileHeader fileHeader, OutputStream output) throws Exception { + try (InputStream entryStream = archive.getInputStream(fileHeader)) { + copyStream(entryStream, output); + } + } + + private static void replaceFileAtomic(Path source, Path target) throws Exception { try { - Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); + Files.move(source, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { - // Fallback if filesystem doesn't support ATOMIC_MOVE - Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING); + Files.move(source, target, StandardCopyOption.REPLACE_EXISTING); } } - private boolean isRarAvailable(String rarBin) { + private boolean checkRarAvailability(String rarCommand) { try { - String exec = isSafeExecutable(rarBin) ? rarBin : "rar"; - Process check = new ProcessBuilder(exec, "--help").redirectErrorStream(true).start(); + String safeCommand = isExecutableSafe(rarCommand) ? rarCommand : "rar"; + Process check = new ProcessBuilder(safeCommand, "--help").redirectErrorStream(true).start(); int exitCode = check.waitFor(); return (exitCode == 0); } catch (Exception ex) { @@ -454,19 +552,14 @@ public class CbxMetadataWriter implements MetadataWriter { } } - /** - * Returns true if the provided executable reference is a simple name or sanitized absolute/relative path. - * No spaces or shell meta chars; passed as argv to ProcessBuilder (no shell). - */ - private boolean isSafeExecutable(String exec) { - if (exec == null || exec.isBlank()) return false; - // allow word chars, dot, slash, backslash, dash and underscore (no spaces or shell metas) - return VALID_FILENAME_PATTERN.matcher(exec).matches(); + private boolean isExecutableSafe(String command) { + if (command == null || command.isBlank()) return false; + return VALID_FILENAME_PATTERN.matcher(command).matches(); } - private static String stripExtension(String filename) { - int i = filename.lastIndexOf('.'); - if (i > 0) return filename.substring(0, i); + private static String removeFileExtension(String filename) { + int lastDot = filename.lastIndexOf('.'); + if (lastDot > 0) return filename.substring(0, lastDot); return filename; } @@ -475,8 +568,8 @@ public class CbxMetadataWriter implements MetadataWriter { return BookFileType.CBX; } - private void deleteDirectoryRecursively(Path dir) { - try (var pathStream = Files.walk(dir)) { + private void deleteDirectoryRecursively(Path directory) { + try (var pathStream = Files.walk(directory)) { pathStream .sorted(Comparator.reverseOrder()) .forEach(path -> { @@ -487,7 +580,7 @@ public class CbxMetadataWriter implements MetadataWriter { } }); } catch (IOException e) { - log.warn("Failed to clean up temporary directory: {}", dir, e); + log.warn("Failed to clean up temporary directory: {}", directory, e); } } -} \ No newline at end of file +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java index 68b6feb2e..396f017f0 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriter.java @@ -1,9 +1,12 @@ package com.adityachandel.booklore.service.metadata.writer; import com.adityachandel.booklore.model.MetadataClearFlags; +import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; 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.service.appsettings.AppSettingService; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import net.lingala.zip4j.ZipFile; import net.lingala.zip4j.model.ZipParameters; @@ -41,12 +44,18 @@ import java.util.UUID; @Slf4j @Component +@RequiredArgsConstructor public class EpubMetadataWriter implements MetadataWriter { private static final String OPF_NS = "http://www.idpf.org/2007/opf"; + private final AppSettingService appSettingService; @Override - public void writeMetadataToFile(File epubFile, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clear) { + public void saveMetadataToFile(File epubFile, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clear) { + if (!shouldSaveMetadataToFile(epubFile)) { + return; + } + File backupFile = new File(epubFile.getParentFile(), epubFile.getName() + ".bak"); try { Files.copy(epubFile.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING); @@ -237,68 +246,61 @@ public class EpubMetadataWriter implements MetadataWriter { return changed; } + + public void replaceCoverImageFromBytes(BookEntity bookEntity, byte[] file) { + if (!shouldSaveMetadataToFile(bookEntity.getFullFilePath().toFile())) { + return; + } + if (file == null || file.length == 0) { + log.warn("Cover update failed: empty or null byte array."); + return; + } + + replaceCoverImageInternal(bookEntity, file, "byte array"); + } + public void replaceCoverImageFromUpload(BookEntity bookEntity, MultipartFile multipartFile) { + if (!shouldSaveMetadataToFile(bookEntity.getFullFilePath().toFile())) { + return; + } if (multipartFile == null || multipartFile.isEmpty()) { log.warn("Cover upload failed: empty or null file."); return; } - Path tempDir = null; try { - File epubFile = new File(bookEntity.getFullFilePath().toUri()); - tempDir = Files.createTempDirectory("epub_cover_" + UUID.randomUUID()); - try (ZipFile zipFile = new ZipFile(epubFile)) { - zipFile.extractAll(tempDir.toString()); - } - - File opfFile = findOpfFile(tempDir.toFile()); - if (opfFile == null) { - log.warn("OPF file not found in EPUB: {}", epubFile.getName()); - return; - } - - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - DocumentBuilder builder = dbf.newDocumentBuilder(); - Document opfDoc = builder.parse(opfFile); - byte[] coverData = multipartFile.getBytes(); - applyCoverImageToEpub(tempDir, opfDoc, coverData); - - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); - transformer.transform(new DOMSource(opfDoc), new StreamResult(opfFile)); - - File tempEpub = new File(epubFile.getParentFile(), epubFile.getName() + ".tmp"); - try (ZipFile tempZipFile = new ZipFile(tempEpub)) { - addFolderContentsToZip(tempZipFile, tempDir.toFile(), tempDir.toFile()); - } - - if (!epubFile.delete()) throw new IOException("Could not delete original EPUB"); - if (!tempEpub.renameTo(epubFile)) throw new IOException("Could not rename temp EPUB"); - - log.info("Cover image updated in EPUB: {}", epubFile.getName()); - - } catch (Exception e) { - log.warn("Failed to update EPUB with uploaded cover image: {}", e.getMessage(), e); - } finally { - if (tempDir != null) { - deleteDirectoryRecursively(tempDir); - } + replaceCoverImageInternal(bookEntity, coverData, "upload"); + } catch (IOException e) { + log.warn("Failed to read uploaded cover image: {}", e.getMessage(), e); } } @Override public void replaceCoverImageFromUrl(BookEntity bookEntity, String url) { + if (!shouldSaveMetadataToFile(bookEntity.getFullFilePath().toFile())) { + return; + } if (url == null || url.isBlank()) { log.warn("Cover update via URL failed: empty or null URL."); return; } + + byte[] coverData = loadImage(url); + if (coverData == null) { + log.warn("Failed to load image from URL: {}", url); + return; + } + + replaceCoverImageInternal(bookEntity, coverData, "URL"); + } + + private void replaceCoverImageInternal(BookEntity bookEntity, byte[] coverData, String source) { Path tempDir = null; try { File epubFile = new File(bookEntity.getFullFilePath().toUri()); - tempDir = Files.createTempDirectory("epub_cover_url_" + UUID.randomUUID()); + tempDir = Files.createTempDirectory("epub_cover_" + UUID.randomUUID()); + try (ZipFile zipFile = new ZipFile(epubFile)) { zipFile.extractAll(tempDir.toString()); } @@ -314,12 +316,6 @@ public class EpubMetadataWriter implements MetadataWriter { DocumentBuilder builder = dbf.newDocumentBuilder(); Document opfDoc = builder.parse(opfFile); - byte[] coverData = loadImage(url); - if (coverData == null) { - log.warn("Failed to load image from URL: {}", url); - return; - } - applyCoverImageToEpub(tempDir, opfDoc, coverData); Transformer transformer = TransformerFactory.newInstance().newTransformer(); @@ -335,9 +331,10 @@ public class EpubMetadataWriter implements MetadataWriter { if (!epubFile.delete()) throw new IOException("Could not delete original EPUB"); if (!tempEpub.renameTo(epubFile)) throw new IOException("Could not rename temp EPUB"); - log.info("Cover image updated in EPUB via URL: {}", epubFile.getName()); + log.info("Cover image updated in EPUB from {}: {}", source, epubFile.getName()); + } catch (Exception e) { - log.warn("Failed to update EPUB with cover from URL: {}", e.getMessage(), e); + log.warn("Failed to update EPUB cover image from {}: {}", source, e.getMessage(), e); } finally { if (tempDir != null) { deleteDirectoryRecursively(tempDir); @@ -543,13 +540,13 @@ public class EpubMetadataWriter implements MetadataWriter { if (StringUtils.isNotBlank(id) && StringUtils.isBlank(creatorRole)) { // Finds any matching role meta tags for this creator ID Element meta = getMetaElementByFilter(metadataElement, el -> ("role".equals(el.getAttribute("property")) && "#".concat(id).equals(el.getAttribute("refines")))); - if ( meta != null ) { - creatorRole = meta.hasAttribute("content") ? meta.getAttribute("content").trim() : meta.getTextContent().trim(); + if (meta != null) { + creatorRole = meta.hasAttribute("content") ? meta.getAttribute("content").trim() : meta.getTextContent().trim(); } } if (role.equalsIgnoreCase(creatorRole)) { metadataElement.removeChild(creatorElement); - if (StringUtils.isNotBlank(id)){ + if (StringUtils.isNotBlank(id)) { removeMetaByRefines(metadataElement, "#".concat(id)); } } @@ -588,9 +585,9 @@ public class EpubMetadataWriter implements MetadataWriter { } private String getMetaContentByName(Element metadataElement, String name) { - Element meta = getMetaElementByFilter( metadataElement, el -> name.equals(el.getAttribute("name")) ); + Element meta = getMetaElementByFilter(metadataElement, el -> name.equals(el.getAttribute("name"))); if (meta != null) { - return meta.getAttribute("content"); + return meta.getAttribute("content"); } return null; } @@ -610,4 +607,22 @@ public class EpubMetadataWriter implements MetadataWriter { log.warn("Failed to clean up temporary directory: {}", dir, e); } } + + public boolean shouldSaveMetadataToFile(File epubFile) { + MetadataPersistenceSettings.SaveToOriginalFile settings = appSettingService.getAppSettings().getMetadataPersistenceSettings().getSaveToOriginalFile(); + + MetadataPersistenceSettings.FormatSettings epubSettings = settings.getEpub(); + if (epubSettings == null || !epubSettings.isEnabled()) { + log.debug("EPUB metadata writing is disabled. Skipping: {}", epubFile.getName()); + return false; + } + + long fileSizeInMb = epubFile.length() / (1024 * 1024); + if (fileSizeInMb > epubSettings.getMaxFileSizeInMb()) { + log.info("EPUB file {} ({} MB) exceeds max size limit ({} MB). Skipping metadata write.", epubFile.getName(), fileSizeInMb, epubSettings.getMaxFileSizeInMb()); + return false; + } + + return true; + } } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/MetadataWriter.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/MetadataWriter.java index f7f342794..73c939f6b 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/MetadataWriter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/MetadataWriter.java @@ -10,11 +10,16 @@ import java.io.File; public interface MetadataWriter { - void writeMetadataToFile(File file, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clearFlags); + void saveMetadataToFile(File file, BookMetadataEntity metadata, String thumbnailUrl, MetadataClearFlags clearFlags); + + boolean shouldSaveMetadataToFile(File file); default void replaceCoverImageFromUpload(BookEntity bookEntity, MultipartFile file) { } + default void replaceCoverImageFromBytes(BookEntity bookEntity, byte[] file) { + } + default void replaceCoverImageFromUrl(BookEntity bookEntity, String url) { } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/PdfMetadataWriter.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/PdfMetadataWriter.java index 63e50f546..64311948a 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/PdfMetadataWriter.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/metadata/writer/PdfMetadataWriter.java @@ -3,6 +3,9 @@ package com.adityachandel.booklore.service.metadata.writer; import com.adityachandel.booklore.model.MetadataClearFlags; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.service.appsettings.AppSettingService; +import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.pdfbox.Loader; @@ -41,10 +44,17 @@ import java.util.UUID; @Slf4j @Component +@RequiredArgsConstructor public class PdfMetadataWriter implements MetadataWriter { + private final AppSettingService appSettingService; + @Override - public void writeMetadataToFile(File file, BookMetadataEntity metadataEntity, String thumbnailUrl, MetadataClearFlags clear) { + public void saveMetadataToFile(File file, BookMetadataEntity metadataEntity, String thumbnailUrl, MetadataClearFlags clear) { + if (!shouldSaveMetadataToFile(file)) { + return; + } + if (!file.exists() || !file.getName().toLowerCase().endsWith(".pdf")) { log.warn("Invalid PDF file: {}", file.getAbsolutePath()); return; @@ -102,6 +112,24 @@ public class PdfMetadataWriter implements MetadataWriter { return BookFileType.PDF; } + public boolean shouldSaveMetadataToFile(File pdfFile) { + MetadataPersistenceSettings.SaveToOriginalFile settings = appSettingService.getAppSettings().getMetadataPersistenceSettings().getSaveToOriginalFile(); + + MetadataPersistenceSettings.FormatSettings pdfSettings = settings.getPdf(); + if (pdfSettings == null || !pdfSettings.isEnabled()) { + log.debug("PDF metadata writing is disabled. Skipping: {}", pdfFile.getName()); + return false; + } + + long fileSizeInMb = pdfFile.length() / (1024 * 1024); + if (fileSizeInMb > pdfSettings.getMaxFileSizeInMb()) { + log.info("PDF file {} ({} MB) exceeds max size limit ({} MB). Skipping metadata write.", pdfFile.getName(), fileSizeInMb, pdfSettings.getMaxFileSizeInMb()); + return false; + } + + return true; + } + private void applyMetadataToDocument(PDDocument pdf, BookMetadataEntity entity, MetadataClearFlags clear) { PDDocumentInformation info = pdf.getDocumentInformation(); MetadataCopyHelper helper = new MetadataCopyHelper(entity); @@ -122,7 +150,7 @@ public class PdfMetadataWriter implements MetadataWriter { helper.copyPublishedDate(clear != null && clear.isPublishedDate(), date -> { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis((date != null ? date : ZonedDateTime.now().toLocalDate()) - .atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()); + .atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()); dc.addDate(cal); }); 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 2d168b3e9..3baa82aa8 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 @@ -281,7 +281,7 @@ public class FileService { if (!success) { throw ApiError.FILE_READ_ERROR.createException("Failed to save cover images"); } - originalImage.flush(); // Release resources after processing + originalImage.flush(); log.info("Cover images created and saved from URL for book ID: {}", bookId); } catch (Exception e) { log.error("An error occurred while creating thumbnail from URL: {}", e.getMessage(), e); @@ -489,87 +489,6 @@ public class FileService { log.info("Deleted {} book covers", bookIds.size()); } - // ======================================== - // BACKGROUND OPERATIONS - // ======================================== - - public void saveBackgroundImage(BufferedImage image, String filename, Long userId) throws IOException { - String backgroundsFolder = getBackgroundsFolder(userId); - File folder = new File(backgroundsFolder); - if (!folder.exists() && !folder.mkdirs()) { - throw new IOException("Failed to create backgrounds directory: " + folder.getAbsolutePath()); - } - - File outputFile = new File(folder, filename); - boolean saved = ImageIO.write(image, IMAGE_FORMAT, outputFile); - if (!saved) { - throw new IOException("Failed to save background image: " + filename); - } - - log.info("Background image saved successfully for user {}: {}", userId, filename); - // Note: input image is not flushed here - caller is responsible for its lifecycle - } public void deleteBackgroundFile(String filename, Long userId) { - try { - String backgroundsFolder = getBackgroundsFolder(userId); - File file = new File(backgroundsFolder, filename); - if (file.exists() && file.isFile()) { - boolean deleted = file.delete(); - if (deleted) { - if (userId != null) { - deleteEmptyUserBackgroundFolder(userId); - } - } else { - log.warn("Failed to delete background file for user {}: {}", userId, filename); - } - } - } catch (Exception e) { - log.warn("Error deleting background file {} for user {}: {}", filename, userId, e.getMessage()); - } - } - - private void deleteEmptyUserBackgroundFolder(Long userId) { - try { - String userBackgroundsFolder = getBackgroundsFolder(userId); - File folder = new File(userBackgroundsFolder); - - if (folder.exists() && folder.isDirectory()) { - File[] files = folder.listFiles(); - if (files != null && files.length == 0) { - boolean deleted = folder.delete(); - if (deleted) { - log.info("Deleted empty background folder for user: {}", userId); - } else { - log.warn("Failed to delete empty background folder for user: {}", userId); - } - } - } - } catch (Exception e) { - log.warn("Error checking/deleting empty background folder for user {}: {}", userId, e.getMessage()); - } - } - - public Resource getBackgroundResource(Long userId) { - String[] possibleFiles = {"1.jpg", "1.jpeg", "1.png"}; - - if (userId != null) { - String userBackgroundsFolder = getBackgroundsFolder(userId); - for (String filename : possibleFiles) { - File customFile = new File(userBackgroundsFolder, filename); - if (customFile.exists() && customFile.isFile()) { - return new FileSystemResource(customFile); - } - } - } - String globalBackgroundsFolder = getBackgroundsFolder(); - for (String filename : possibleFiles) { - File customFile = new File(globalBackgroundsFolder, filename); - if (customFile.exists() && customFile.isFile()) { - return new FileSystemResource(customFile); - } - } - return new ClassPathResource("static/images/background.jpg"); - } - public String getIconsSvgFolder() { return Paths.get(appProperties.getPathConfig(), ICONS_DIR, SVG_DIR).toString(); } diff --git a/booklore-api/src/main/resources/db/migration/V87__Migrate_MetadataPersistenceSettings_Structure.sql b/booklore-api/src/main/resources/db/migration/V87__Migrate_MetadataPersistenceSettings_Structure.sql new file mode 100644 index 000000000..851f73fac --- /dev/null +++ b/booklore-api/src/main/resources/db/migration/V87__Migrate_MetadataPersistenceSettings_Structure.sql @@ -0,0 +1,50 @@ +-- Migrate MetadataPersistenceSettings from old structure to new nested structure +-- Old: {"saveToOriginalFile":boolean,...} +-- New: {"saveToOriginalFile":{"epub":{...},"pdf":{...}},...} +-- Creates metadata_persistence_settings_v2 instead of overwriting the original + +INSERT INTO app_settings (name, val) +SELECT + 'metadata_persistence_settings_v2', + CASE + -- If saveToOriginalFile is true, enable all formats + WHEN JSON_EXTRACT(val, '$.saveToOriginalFile') = true THEN + JSON_SET( + val, + '$.saveToOriginalFile', + JSON_OBJECT( + 'epub', JSON_OBJECT('enabled', true, 'maxFileSizeInMb', 250), + 'pdf', JSON_OBJECT('enabled', true, 'maxFileSizeInMb', 250), + 'cbx', JSON_OBJECT('enabled', true, 'maxFileSizeInMb', 250) + ) + ) + -- If saveToOriginalFile is false, disable all formats + WHEN JSON_EXTRACT(val, '$.saveToOriginalFile') = false THEN + JSON_SET( + val, + '$.saveToOriginalFile', + JSON_OBJECT( + 'epub', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250), + 'pdf', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250), + 'cbx', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250) + ) + ) + -- If null or missing, default to disabled + ELSE + JSON_SET( + COALESCE(val, '{}'), + '$.saveToOriginalFile', + JSON_OBJECT( + 'epub', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250), + 'pdf', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250), + 'cbx', JSON_OBJECT('enabled', false, 'maxFileSizeInMb', 250) + ) + ) + END +FROM app_settings +WHERE name = 'metadata_persistence_settings' +AND val IS NOT NULL +AND val != '' +AND NOT EXISTS ( + SELECT 1 FROM app_settings WHERE name = 'metadata_persistence_settings_v2' +); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/controller/BookMediaControllerTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/controller/BookMediaControllerTest.java deleted file mode 100644 index 4e3cc1cf6..000000000 --- a/booklore-api/src/test/java/com/adityachandel/booklore/controller/BookMediaControllerTest.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.adityachandel.booklore.controller; - -import com.adityachandel.booklore.service.book.BookService; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.core.io.Resource; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -@ExtendWith(MockitoExtension.class) -class BookMediaControllerTest { - - @Mock - private BookService bookService; - - @InjectMocks - private BookMediaController bookMediaController; - - @Test - void getBackgroundImage_shouldReturnBadRequestWhenFilenameIsNull() { - Resource resource = mock(Resource.class); - when(bookService.getBackgroundImage()).thenReturn(resource); - when(resource.exists()).thenReturn(true); - when(resource.getFilename()).thenReturn(null); - - ResponseEntity response = bookMediaController.getBackgroundImage(); - - assertEquals(HttpStatus.BAD_REQUEST, response.getStatusCode()); - } -} 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 5c335a25b..449fe341e 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 @@ -41,20 +41,34 @@ import static org.mockito.Mockito.*; @ExtendWith(org.mockito.junit.jupiter.MockitoExtension.class) class BookServiceTest { - @Mock private BookRepository bookRepository; - @Mock private PdfViewerPreferencesRepository pdfViewerPreferencesRepository; - @Mock private EpubViewerPreferencesRepository epubViewerPreferencesRepository; - @Mock private CbxViewerPreferencesRepository cbxViewerPreferencesRepository; - @Mock private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository; - @Mock private FileService fileService; - @Mock private BookMapper bookMapper; - @Mock private UserBookProgressRepository userBookProgressRepository; - @Mock private AuthenticationService authenticationService; - @Mock private BookQueryService bookQueryService; - @Mock private UserProgressService userProgressService; - @Mock private BookDownloadService bookDownloadService; - @Mock private MonitoringRegistrationService monitoringRegistrationService; - @Mock private BookUpdateService bookUpdateService; + @Mock + private BookRepository bookRepository; + @Mock + private PdfViewerPreferencesRepository pdfViewerPreferencesRepository; + @Mock + private EpubViewerPreferencesRepository epubViewerPreferencesRepository; + @Mock + private CbxViewerPreferencesRepository cbxViewerPreferencesRepository; + @Mock + private NewPdfViewerPreferencesRepository newPdfViewerPreferencesRepository; + @Mock + private FileService fileService; + @Mock + private BookMapper bookMapper; + @Mock + private UserBookProgressRepository userBookProgressRepository; + @Mock + private AuthenticationService authenticationService; + @Mock + private BookQueryService bookQueryService; + @Mock + private UserProgressService userProgressService; + @Mock + private BookDownloadService bookDownloadService; + @Mock + private MonitoringRegistrationService monitoringRegistrationService; + @Mock + private BookUpdateService bookUpdateService; @InjectMocks private BookService bookService; @@ -258,18 +272,6 @@ class BookServiceTest { assertThrows(RuntimeException.class, () -> bookService.getBookCover(123L)); } - @Test - void getBackgroundImage_returnsResource() { - Resource mockResource = mock(Resource.class); - when(fileService.getBackgroundResource(testUser.getId())).thenReturn(mockResource); - - when(authenticationService.getAuthenticatedUser()).thenReturn(testUser); - - Resource res = bookService.getBackgroundImage(); - - assertEquals(mockResource, res); - } - @Test void downloadBook_delegatesToDownloadService() { ResponseEntity response = ResponseEntity.ok(mock(Resource.class)); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookCoverServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookCoverServiceTest.java index 02a321682..d75a0f277 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookCoverServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookCoverServiceTest.java @@ -2,15 +2,14 @@ package com.adityachandel.booklore.service.metadata; import com.adityachandel.booklore.exception.ApiError; import com.adityachandel.booklore.mapper.BookMetadataMapper; -import com.adityachandel.booklore.model.dto.BookMetadata; import com.adityachandel.booklore.model.dto.settings.AppSettings; import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; 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.enums.BookFileType; -import com.adityachandel.booklore.model.websocket.Topic; import com.adityachandel.booklore.repository.BookRepository; +import com.adityachandel.booklore.repository.projection.BookCoverUpdateProjection; import com.adityachandel.booklore.service.NotificationService; import com.adityachandel.booklore.service.appsettings.AppSettingService; import com.adityachandel.booklore.service.book.BookQueryService; @@ -70,94 +69,115 @@ class BookCoverServiceTest { return book; } - @Test - void generateCustomCover_success() { - BookEntity book = mockBookEntity(1L, false); - when(bookRepository.findById(1L)).thenReturn(Optional.of(book)); - when(coverImageGenerator.generateCover(any(), any())).thenReturn(new byte[]{1,2,3}); - doNothing().when(fileService).createThumbnailFromBytes(eq(1L), any()); - when(bookRepository.save(any())).thenReturn(book); - - bookCoverService.generateCustomCover(1L); - - verify(fileService).createThumbnailFromBytes(eq(1L), any()); - verify(bookRepository).save(book); - verify(notificationService).sendMessage(eq(Topic.BOOKS_COVER_UPDATE), any()); - } - @Test void generateCustomCover_coverLocked_throws() { BookEntity book = mockBookEntity(2L, true); when(bookRepository.findById(2L)).thenReturn(Optional.of(book)); + when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); + when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false)); assertThatThrownBy(() -> bookCoverService.generateCustomCover(2L)) .isInstanceOf(ApiError.METADATA_LOCKED.createException().getClass()); } @Test - void updateCoverImageFromFile_success() { + void updateCoverFromFile_success() { MultipartFile file = mock(MultipartFile.class); - BookEntity book = mockBookEntity(3L, false); - when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); + BookEntity book = spy(mockBookEntity(3L, false)); + doReturn(Path.of("/dummy/path")).when(book).getFullFilePath(); + when(bookRepository.findById(3L)).thenReturn(Optional.of(book)); when(bookRepository.save(any())).thenReturn(book); when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false)); - when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata()); - BookMetadata result = bookCoverService.updateCoverImageFromFile(3L, file); + MetadataWriter writer = mock(MetadataWriter.class); + when(metadataWriterFactory.getWriter(any())).thenReturn(Optional.of(writer)); - verify(fileService).createThumbnailFromFile(3L, file); - assertThat(result).isNotNull(); + BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class); + when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of(projection)); + + try (MockedStatic fingerprintMock = mockStatic(FileFingerprint.class)) { + fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("dummyhash"); + bookCoverService.updateCoverFromFile(3L, file); + + verify(fileService).createThumbnailFromFile(3L, file); + } } @Test - void updateCoverImageFromUrl_success() { + void updateCoverFromUrl_success() { String url = "http://test.com/cover.jpg"; - BookEntity book = mockBookEntity(4L, false); - when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); + BookEntity book = spy(mockBookEntity(4L, false)); + doReturn(Path.of("/dummy/path")).when(book).getFullFilePath(); + when(bookRepository.findById(4L)).thenReturn(Optional.of(book)); when(bookRepository.save(any())).thenReturn(book); when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false)); - when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata()); - BookMetadata result = bookCoverService.updateCoverImageFromUrl(4L, url); + MetadataWriter writer = mock(MetadataWriter.class); + when(metadataWriterFactory.getWriter(any())).thenReturn(Optional.of(writer)); - verify(fileService).createThumbnailFromUrl(4L, url); - assertThat(result).isNotNull(); + BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class); + when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of(projection)); + + try (MockedStatic fingerprintMock = mockStatic(FileFingerprint.class)) { + fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("dummyhash"); + bookCoverService.updateCoverFromUrl(4L, url); + + verify(fileService).createThumbnailFromUrl(4L, url); + } } @Test - void updateCoverImageFromFileForBooks_success() throws Exception { + void updateCoverFromFileForBooks_success() throws Exception { try (MockedStatic ignored = mockStatic(SecurityContextVirtualThread.class)) { MultipartFile file = mock(MultipartFile.class); when(file.isEmpty()).thenReturn(false); when(file.getContentType()).thenReturn("image/jpeg"); doReturn(new byte[]{1,2,3}).when(file).getBytes(); - BookEntity book = mockBookEntity(5L, false); + BookEntity book = spy(mockBookEntity(5L, false)); + doReturn(Path.of("/dummy/path")).when(book).getFullFilePath(); when(bookQueryService.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); when(bookRepository.findById(5L)).thenReturn(Optional.of(book)); when(bookRepository.save(any())).thenReturn(book); - + when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false)); doNothing().when(fileService).createThumbnailFromBytes(eq(5L), any()); + doNothing().when(notificationService).sendMessage(any(), any()); - ignored.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class))) - .thenAnswer(invocation -> { - Runnable runnable = invocation.getArgument(0); - runnable.run(); - return null; - }); + MetadataWriter writer = mock(MetadataWriter.class); + when(metadataWriterFactory.getWriter(any())).thenReturn(Optional.of(writer)); - bookCoverService.updateCoverImageFromFileForBooks(Set.of(5L), file); + BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class); + when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of(projection)); - ArgumentCaptor idCaptor = ArgumentCaptor.forClass(Long.class); - verify(fileService).createThumbnailFromBytes(idCaptor.capture(), any()); - assertThat(idCaptor.getValue()).isEqualTo(5L); - verify(bookRepository).save(any(BookEntity.class)); + when(transactionTemplate.execute(any())).thenAnswer(invocation -> { + org.springframework.transaction.support.TransactionCallback callback = invocation.getArgument(0); + return callback.doInTransaction(null); + }); + + try (MockedStatic fingerprintMock = mockStatic(FileFingerprint.class)) { + fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("dummyhash"); + + ignored.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class))) + .thenAnswer(invocation -> { + Runnable runnable = invocation.getArgument(0); + runnable.run(); + return null; + }); + + bookCoverService.updateCoverFromFileForBooks(Set.of(5L), file); + + ArgumentCaptor idCaptor = ArgumentCaptor.forClass(Long.class); + verify(fileService).createThumbnailFromBytes(idCaptor.capture(), any()); + assertThat(idCaptor.getValue()).isEqualTo(5L); + verify(bookRepository).save(any(BookEntity.class)); + verify(notificationService, atLeastOnce()).sendMessage(any(), any()); + } } } @Test - void updateCoverImageFromFileForBooks_invalidFile_throws() { + void updateCoverFromFileForBooks_invalidFile_throws() { MultipartFile file = mock(MultipartFile.class); when(file.isEmpty()).thenReturn(true); - assertThatThrownBy(() -> bookCoverService.updateCoverImageFromFileForBooks(Set.of(6L), file)) + assertThatThrownBy(() -> bookCoverService.updateCoverFromFileForBooks(Set.of(6L), file)) .isInstanceOf(ApiError.INVALID_INPUT.createException("dummy").getClass()); } @@ -165,6 +185,7 @@ class BookCoverServiceTest { void regenerateCover_success() { BookEntity book = mockBookEntity(7L, false); when(bookRepository.findById(7L)).thenReturn(Optional.of(book)); + when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); BookFileProcessor processor = mock(BookFileProcessor.class); when(processorRegistry.getProcessorOrThrow(any())).thenReturn(processor); when(processor.generateCover(any())).thenReturn(true); @@ -180,6 +201,7 @@ class BookCoverServiceTest { void regenerateCover_coverLocked_throws() { BookEntity book = mockBookEntity(8L, true); when(bookRepository.findById(8L)).thenReturn(Optional.of(book)); + when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); assertThatThrownBy(() -> bookCoverService.regenerateCover(8L)) .isInstanceOf(ApiError.METADATA_LOCKED.createException().getClass()); } @@ -189,11 +211,21 @@ class BookCoverServiceTest { try (MockedStatic ignored = mockStatic(SecurityContextVirtualThread.class)) { BookEntity book = mockBookEntity(9L, false); when(bookQueryService.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); + when(bookRepository.findById(9L)).thenReturn(Optional.of(book)); + when(bookRepository.save(any())).thenReturn(book); + BookFileProcessor processor = mock(BookFileProcessor.class); when(processorRegistry.getProcessorOrThrow(any())).thenReturn(processor); when(processor.generateCover(any())).thenReturn(true); - when(bookRepository.findById(9L)).thenReturn(Optional.of(book)); - when(bookRepository.save(any())).thenReturn(book); + + BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class); + when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of(projection)); + doNothing().when(notificationService).sendMessage(any(), any()); + + when(transactionTemplate.execute(any())).thenAnswer(invocation -> { + org.springframework.transaction.support.TransactionCallback callback = invocation.getArgument(0); + return callback.doInTransaction(null); + }); ignored.when(() -> SecurityContextVirtualThread.runWithSecurityContext(any(Runnable.class))) .thenAnswer(invocation -> { @@ -207,6 +239,7 @@ class BookCoverServiceTest { ArgumentCaptor bookCaptor = ArgumentCaptor.forClass(BookEntity.class); verify(processor).generateCover(bookCaptor.capture()); assertThat(bookCaptor.getValue().getId()).isEqualTo(9L); + verify(notificationService, atLeastOnce()).sendMessage(any(), any()); } } @@ -215,40 +248,34 @@ class BookCoverServiceTest { MultipartFile file = mock(MultipartFile.class); BookEntity book = spy(mockBookEntity(10L, false)); doReturn(Path.of("/dummy/path")).when(book).getFullFilePath(); - when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); + when(bookRepository.findById(10L)).thenReturn(Optional.of(book)); when(bookRepository.save(any())).thenReturn(book); when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(true, false)); + MetadataWriter writer = mock(MetadataWriter.class); when(metadataWriterFactory.getWriter(any())).thenReturn(Optional.of(writer)); - when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata()); + + BookCoverUpdateProjection projection = mock(BookCoverUpdateProjection.class); + when(bookRepository.findCoverUpdateInfoByIds(any())).thenReturn(List.of(projection)); try (MockedStatic fingerprintMock = mockStatic(FileFingerprint.class)) { fingerprintMock.when(() -> FileFingerprint.generateHash(any())).thenReturn("dummyhash"); - BookMetadata result = bookCoverService.updateCoverImageFromFile(10L, file); + bookCoverService.updateCoverFromFile(10L, file); verify(writer).replaceCoverImageFromUpload(book, file); - assertThat(result).isNotNull(); } } - @Test - void updateCover_metadataPersistenceSettings_noSaveToOriginalFile() { - MultipartFile file = mock(MultipartFile.class); - BookEntity book = mockBookEntity(11L, false); - when(bookRepository.findAllWithMetadataByIds(any())).thenReturn(List.of(book)); - when(bookRepository.save(any())).thenReturn(book); - when(appSettingService.getAppSettings()).thenReturn(mockAppSettings(false, false)); - when(bookMetadataMapper.toBookMetadata(any(), eq(true))).thenReturn(new BookMetadata()); - - BookMetadata result = bookCoverService.updateCoverImageFromFile(11L, file); - - verify(metadataWriterFactory, never()).getWriter(any()); - assertThat(result).isNotNull(); - } - private AppSettings mockAppSettings(boolean saveToOriginalFile, boolean convertCbrCb7ToCbz) { + MetadataPersistenceSettings.SaveToOriginalFile saveToOriginalFileObj = + MetadataPersistenceSettings.SaveToOriginalFile.builder() + .epub(MetadataPersistenceSettings.FormatSettings.builder().enabled(saveToOriginalFile).build()) + .pdf(MetadataPersistenceSettings.FormatSettings.builder().enabled(saveToOriginalFile).build()) + .cbx(MetadataPersistenceSettings.FormatSettings.builder().enabled(saveToOriginalFile).build()) + .build(); + MetadataPersistenceSettings settings = new MetadataPersistenceSettings(); - settings.setSaveToOriginalFile(saveToOriginalFile); + settings.setSaveToOriginalFile(saveToOriginalFileObj); settings.setConvertCbrCb7ToCbz(convertCbrCb7ToCbz); return new com.adityachandel.booklore.model.dto.settings.AppSettings() { @Override diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterCategoryTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterCategoryTest.java index f8b363c57..943ebe18c 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterCategoryTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterCategoryTest.java @@ -20,6 +20,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import java.util.HashSet; @@ -32,17 +33,28 @@ import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class BookMetadataUpdaterCategoryTest { - @Mock private AuthorRepository authorRepository; - @Mock private CategoryRepository categoryRepository; - @Mock private MoodRepository moodRepository; - @Mock private TagRepository tagRepository; - @Mock private BookRepository bookRepository; - @Mock private FileService fileService; - @Mock private MetadataMatchService metadataMatchService; - @Mock private AppSettingService appSettingService; - @Mock private MetadataWriterFactory metadataWriterFactory; - @Mock private BookReviewUpdateService bookReviewUpdateService; - @Mock private FileMoveService fileMoveService; + @Mock + private AuthorRepository authorRepository; + @Mock + private CategoryRepository categoryRepository; + @Mock + private MoodRepository moodRepository; + @Mock + private TagRepository tagRepository; + @Mock + private BookRepository bookRepository; + @Mock + private FileService fileService; + @Mock + private MetadataMatchService metadataMatchService; + @Mock + private AppSettingService appSettingService; + @Mock + private MetadataWriterFactory metadataWriterFactory; + @Mock + private BookReviewUpdateService bookReviewUpdateService; + @Mock + private FileMoveService fileMoveService; @InjectMocks private BookMetadataUpdater bookMetadataUpdater; @@ -50,7 +62,13 @@ class BookMetadataUpdaterCategoryTest { @BeforeEach void setUp() { AppSettings appSettings = new AppSettings(); - appSettings.setMetadataPersistenceSettings(new MetadataPersistenceSettings()); + MetadataPersistenceSettings persistenceSettings = new MetadataPersistenceSettings(); + + MetadataPersistenceSettings.SaveToOriginalFile saveToOriginalFile = Mockito.mock(MetadataPersistenceSettings.SaveToOriginalFile.class); + when(saveToOriginalFile.isAnyFormatEnabled()).thenReturn(false); + persistenceSettings.setSaveToOriginalFile(saveToOriginalFile); + + appSettings.setMetadataPersistenceSettings(persistenceSettings); lenient().when(appSettingService.getAppSettings()).thenReturn(appSettings); lenient().when(categoryRepository.findByName(anyString())).thenAnswer(invocation -> { @@ -59,8 +77,9 @@ class BookMetadataUpdaterCategoryTest { }); lenient().when(categoryRepository.save(any(CategoryEntity.class))).thenAnswer(invocation -> - invocation.getArgument(0)); + invocation.getArgument(0)); } + @Test void replaceAll_withMergeFalse_shouldClearAndAddNew() { BookEntity bookEntity = createBookWithCategories("Old1", "Old2"); @@ -303,7 +322,7 @@ class BookMetadataUpdaterCategoryTest { bookMetadataUpdater.setBookMetadata(context); assertTrue(bookEntity.getMetadata().getCategories().isEmpty(), - "BUG REPRODUCED: Empty array cleared all categories"); + "BUG REPRODUCED: Empty array cleared all categories"); } @Test @@ -392,4 +411,5 @@ class BookMetadataUpdaterCategoryTest { private boolean containsCategory(Set categories, String name) { return categories.stream().anyMatch(c -> c.getName().equals(name)); } -} \ No newline at end of file +} + diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterTest.java index 93812d7de..33218b3bc 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/BookMetadataUpdaterTest.java @@ -20,6 +20,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Collections; @@ -33,17 +34,28 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class BookMetadataUpdaterTest { - @Mock private AuthorRepository authorRepository; - @Mock private CategoryRepository categoryRepository; - @Mock private MoodRepository moodRepository; - @Mock private TagRepository tagRepository; - @Mock private BookRepository bookRepository; - @Mock private FileService fileService; - @Mock private MetadataMatchService metadataMatchService; - @Mock private AppSettingService appSettingService; - @Mock private MetadataWriterFactory metadataWriterFactory; - @Mock private BookReviewUpdateService bookReviewUpdateService; - @Mock private FileMoveService fileMoveService; + @Mock + private AuthorRepository authorRepository; + @Mock + private CategoryRepository categoryRepository; + @Mock + private MoodRepository moodRepository; + @Mock + private TagRepository tagRepository; + @Mock + private BookRepository bookRepository; + @Mock + private FileService fileService; + @Mock + private MetadataMatchService metadataMatchService; + @Mock + private AppSettingService appSettingService; + @Mock + private MetadataWriterFactory metadataWriterFactory; + @Mock + private BookReviewUpdateService bookReviewUpdateService; + @Mock + private FileMoveService fileMoveService; @InjectMocks private BookMetadataUpdater bookMetadataUpdater; @@ -51,7 +63,13 @@ class BookMetadataUpdaterTest { @BeforeEach void setUp() { AppSettings appSettings = new AppSettings(); - appSettings.setMetadataPersistenceSettings(new MetadataPersistenceSettings()); + MetadataPersistenceSettings persistenceSettings = new MetadataPersistenceSettings(); + + MetadataPersistenceSettings.SaveToOriginalFile saveToOriginalFile = Mockito.mock(MetadataPersistenceSettings.SaveToOriginalFile.class); + when(saveToOriginalFile.isAnyFormatEnabled()).thenReturn(false); + persistenceSettings.setSaveToOriginalFile(saveToOriginalFile); + + appSettings.setMetadataPersistenceSettings(persistenceSettings); when(appSettingService.getAppSettings()).thenReturn(appSettings); } @@ -60,7 +78,7 @@ class BookMetadataUpdaterTest { BookEntity bookEntity = new BookEntity(); bookEntity.setId(1L); BookMetadataEntity metadataEntity = new BookMetadataEntity(); - + Set existingTags = new HashSet<>(); existingTags.add(TagEntity.builder().name("Tag1").build()); existingTags.add(TagEntity.builder().name("Tag2").build()); @@ -120,12 +138,13 @@ class BookMetadataUpdaterTest { assertTrue(bookEntity.getMetadata().getTags().isEmpty(), "All tags should be cleared when incoming set is empty"); } + @Test void setBookMetadata_withMergeTagsTrue_shouldMergeTags() { BookEntity bookEntity = new BookEntity(); bookEntity.setId(1L); BookMetadataEntity metadataEntity = new BookMetadataEntity(); - + Set existingTags = new HashSet<>(); existingTags.add(TagEntity.builder().name("Tag1").build()); existingTags.add(TagEntity.builder().name("Tag2").build()); @@ -157,6 +176,7 @@ class BookMetadataUpdaterTest { assertTrue(bookEntity.getMetadata().getTags().stream().anyMatch(t -> t.getName().equals("Tag2"))); assertTrue(bookEntity.getMetadata().getTags().stream().anyMatch(t -> t.getName().equals("Tag3"))); } + @Test void setBookMetadata_withMergeMoodsFalse_shouldReplaceMoods() { BookEntity bookEntity = new BookEntity(); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractorTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractorTest.java index 6b1c2c575..fb91db26e 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractorTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/CbxMetadataExtractorTest.java @@ -83,7 +83,6 @@ class CbxMetadataExtractorTest { assertEquals(Integer.valueOf(42), md.getPageCount()); assertEquals("en", md.getLanguage()); assertTrue(md.getAuthors().contains("Alice")); - assertTrue(md.getAuthors().contains("Bob")); assertTrue(md.getCategories().contains("action")); assertTrue(md.getCategories().contains("adventure")); } @@ -122,7 +121,6 @@ class CbxMetadataExtractorTest { assertEquals(Integer.valueOf(42), md.getPageCount()); assertEquals("en", md.getLanguage()); assertTrue(md.getAuthors().contains("Alice")); - assertTrue(md.getAuthors().contains("Bob")); assertTrue(md.getCategories().contains("action")); assertTrue(md.getCategories().contains("adventure")); } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ComicInfoParsingIssuesTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ComicInfoParsingIssuesTest.java index 71a81cce3..8d7f453ed 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ComicInfoParsingIssuesTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ComicInfoParsingIssuesTest.java @@ -73,7 +73,6 @@ class ComicInfoParsingIssuesTest { assertEquals(Integer.valueOf(1964), metadata.getPublishedDate().getYear()); assertEquals("Marvel", metadata.getPublisher()); assertTrue(metadata.getAuthors().contains("Stan Lee")); - assertTrue(metadata.getAuthors().contains("Joe Orlando")); } @Test @@ -160,10 +159,6 @@ class ComicInfoParsingIssuesTest { assertEquals("Special anniversary issue", metadata.getDescription()); assertTrue(metadata.getAuthors().contains("Frank Miller")); - assertTrue(metadata.getAuthors().contains("John Romita Jr.")); - assertTrue(metadata.getAuthors().contains("Scott Hanna")); - assertTrue(metadata.getAuthors().contains("Steve Oliff")); - assertTrue(metadata.getAuthors().contains("Joe Rosen")); assertTrue(metadata.getCategories().contains("Marvel")); assertTrue(metadata.getCategories().contains("Daredevil")); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ExtractFromComicInfoXmlTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ExtractFromComicInfoXmlTest.java index fb4c5ddf9..0edfbb738 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ExtractFromComicInfoXmlTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/extractor/ExtractFromComicInfoXmlTest.java @@ -19,7 +19,7 @@ import static org.junit.jupiter.api.Assertions.*; class ExtractFromComicInfoXmlTest { private CbxMetadataExtractor extractor; - + @TempDir Path tempDir; @@ -44,11 +44,6 @@ class ExtractFromComicInfoXmlTest { DC Comics Batman comes out of retirement to fight crime in Gotham City. Frank Miller - Frank Miller - Klaus Janson - Lynn Varley - John Costanza - Frank Miller Superhero, Crime Batman, DC, Frank Miller 48 @@ -69,13 +64,10 @@ class ExtractFromComicInfoXmlTest { assertEquals("Batman comes out of retirement to fight crime in Gotham City.", metadata.getDescription()); assertEquals(48, metadata.getPageCount()); assertEquals("en", metadata.getLanguage()); - + // Verify authors assertTrue(metadata.getAuthors().contains("Frank Miller")); - assertTrue(metadata.getAuthors().contains("Klaus Janson")); - assertTrue(metadata.getAuthors().contains("Lynn Varley")); - assertTrue(metadata.getAuthors().contains("John Costanza")); - + // Verify categories assertTrue(metadata.getCategories().contains("Superhero")); assertTrue(metadata.getCategories().contains("Crime")); @@ -119,7 +111,7 @@ class ExtractFromComicInfoXmlTest { Path parentDir = tempDir.resolve("comic_folder"); Files.createDirectories(parentDir); File xmlFile = createXmlFileInDir(parentDir, "no_title.xml", xml); - + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); assertNotNull(metadata); @@ -140,7 +132,7 @@ class ExtractFromComicInfoXmlTest { Path parentDir = tempDir.resolve("empty_title_comic"); Files.createDirectories(parentDir); File xmlFile = createXmlFileInDir(parentDir, "empty_title.xml", xml); - + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); assertNotNull(metadata); @@ -159,7 +151,7 @@ class ExtractFromComicInfoXmlTest { Path parentDir = tempDir.resolve("whitespace_comic"); Files.createDirectories(parentDir); File xmlFile = createXmlFileInDir(parentDir, "whitespace_title.xml", xml); - + BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); assertNotNull(metadata); @@ -316,7 +308,6 @@ class ExtractFromComicInfoXmlTest { Test Comic John Doe, Jane Smith - Bob Artist, Alice Drawer """; @@ -326,8 +317,6 @@ class ExtractFromComicInfoXmlTest { assertNotNull(metadata); assertTrue(metadata.getAuthors().contains("John Doe")); assertTrue(metadata.getAuthors().contains("Jane Smith")); - assertTrue(metadata.getAuthors().contains("Bob Artist")); - assertTrue(metadata.getAuthors().contains("Alice Drawer")); } @Test @@ -336,7 +325,6 @@ class ExtractFromComicInfoXmlTest { Test Comic John Doe; Jane Smith - Bob Inker; Alice Helper """; @@ -346,8 +334,6 @@ class ExtractFromComicInfoXmlTest { assertNotNull(metadata); assertTrue(metadata.getAuthors().contains("John Doe")); assertTrue(metadata.getAuthors().contains("Jane Smith")); - assertTrue(metadata.getAuthors().contains("Bob Inker")); - assertTrue(metadata.getAuthors().contains("Alice Helper")); } @Test @@ -666,21 +652,21 @@ class ExtractFromComicInfoXmlTest { @ParameterizedTest @CsvSource({ - "2020,,,2020-01-01", - "2020,6,,2020-06-01", - "2020,3,15,2020-03-15", - "2020,13,32," // Invalid + "2020,,,2020-01-01", + "2020,6,,2020-06-01", + "2020,3,15,2020-03-15", + "2020,13,32," // Invalid }) void testExtractFromComicInfoXml_DateParsing(String year, String month, String day, String expected) throws IOException { String xml = String.format(""" - - Date Test - %s%s%s - - """, - year != null ? "" + year + "" : "", - month != null ? "" + month + "" : "", - day != null ? "" + day + "" : "" + + Date Test + %s%s%s + + """, + year != null ? "" + year + "" : "", + month != null ? "" + month + "" : "", + day != null ? "" + day + "" : "" ); File xmlFile = createXmlFile("date_test.xml", xml); @@ -696,8 +682,8 @@ class ExtractFromComicInfoXmlTest { @Test void testExtractFromComicInfoXml_NullInput_ThrowsIllegalArgumentException() { IllegalArgumentException exception = assertThrows( - IllegalArgumentException.class, - () -> extractor.extractFromComicInfoXml(null) + IllegalArgumentException.class, + () -> extractor.extractFromComicInfoXml(null) ); assertEquals("XML file cannot be null", exception.getMessage()); } @@ -746,9 +732,6 @@ class ExtractFromComicInfoXmlTest { // Verify authors assertTrue(metadata.getAuthors().contains("Frank Miller")); - assertTrue(metadata.getAuthors().contains("Klaus Janson")); - assertTrue(metadata.getAuthors().contains("Lynn Varley")); - assertTrue(metadata.getAuthors().contains("John Costanza")); // Verify categories assertTrue(metadata.getCategories().contains("Superhero")); @@ -811,30 +794,10 @@ class ExtractFromComicInfoXmlTest { BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); assertNotNull(metadata); - // Set should contain only one "Frank Miller" assertEquals(1, metadata.getAuthors().size()); assertTrue(metadata.getAuthors().contains("Frank Miller")); } - @Test - void testExtractFromComicInfoXml_EmptyAuthorFields_NotAdded() throws IOException { - String xml = """ - - Test Comic - - - Valid Author - - """; - - File xmlFile = createXmlFile("empty_authors.xml", xml); - BookMetadata metadata = extractor.extractFromComicInfoXml(xmlFile); - - assertNotNull(metadata); - assertEquals(1, metadata.getAuthors().size()); - assertTrue(metadata.getAuthors().contains("Valid Author")); - } - @Test void testExtractFromComicInfoXml_NoAuthors_AuthorsNull() throws IOException { String xml = """ diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriterTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriterTest.java index 587dbd701..395d3375e 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriterTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/CbxMetadataWriterTest.java @@ -1,13 +1,17 @@ package com.adityachandel.booklore.service.metadata.writer; import com.adityachandel.booklore.model.MetadataClearFlags; +import com.adityachandel.booklore.model.dto.settings.AppSettings; +import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; import com.adityachandel.booklore.model.entity.AuthorEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.model.entity.CategoryEntity; import com.adityachandel.booklore.model.enums.BookFileType; +import com.adityachandel.booklore.service.appsettings.AppSettingService; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.Mockito; import org.w3c.dom.Document; import javax.xml.XMLConstants; @@ -36,7 +40,19 @@ class CbxMetadataWriterTest { @BeforeEach void setup() throws Exception { - writer = new CbxMetadataWriter(); + AppSettingService appSettingService = Mockito.mock(AppSettingService.class); + AppSettings settings = new AppSettings(); + MetadataPersistenceSettings persistence = new MetadataPersistenceSettings(); + MetadataPersistenceSettings.SaveToOriginalFile save = new MetadataPersistenceSettings.SaveToOriginalFile(); + MetadataPersistenceSettings.FormatSettings cbx = new MetadataPersistenceSettings.FormatSettings(); + cbx.setEnabled(true); + cbx.setMaxFileSizeInMb(100); + save.setCbx(cbx); + persistence.setSaveToOriginalFile(save); + settings.setMetadataPersistenceSettings(persistence); + Mockito.when(appSettingService.getAppSettings()).thenReturn(settings); + + writer = new CbxMetadataWriter(appSettingService); tempDir = Files.createTempDirectory("cbx_writer_test_"); } @@ -45,7 +61,12 @@ class CbxMetadataWriterTest { if (tempDir != null) { Files.walk(tempDir) .sorted(Comparator.reverseOrder()) - .forEach(p -> { try { Files.deleteIfExists(p); } catch (Exception ignore) {} }); + .forEach(p -> { + try { + Files.deleteIfExists(p); + } catch (Exception ignore) { + } + }); } } @@ -55,7 +76,7 @@ class CbxMetadataWriterTest { } @Test - void writeMetadataToFile_cbz_updatesOrCreatesComicInfo_andPreservesOtherFiles() throws Exception { + void saveMetadataToFile_cbz_updatesOrCreatesComicInfo_andPreservesOtherFiles() throws Exception { // Create a CBZ without ComicInfo.xml and with a couple of images File cbz = createCbz(tempDir.resolve("sample.cbz"), new String[]{ "images/002.jpg", "images/001.jpg" @@ -69,7 +90,7 @@ class CbxMetadataWriterTest { meta.setSeriesName("Series X"); meta.setSeriesNumber(2.5f); meta.setSeriesTotal(12); - meta.setPublishedDate(LocalDate.of(2020,7,14)); + meta.setPublishedDate(LocalDate.of(2020, 7, 14)); meta.setPageCount(42); meta.setLanguage("en"); @@ -95,7 +116,7 @@ class CbxMetadataWriterTest { meta.setCategories(cats); // Execute - writer.writeMetadataToFile(cbz, meta, null, new MetadataClearFlags()); + writer.saveMetadataToFile(cbz, meta, null, new MetadataClearFlags()); // Assert ComicInfo.xml exists and contains our fields try (ZipFile zip = new ZipFile(cbz)) { @@ -144,7 +165,7 @@ class CbxMetadataWriterTest { } @Test - void writeMetadataToFile_cbz_updatesExistingComicInfo() throws Exception { + void saveMetadataToFile_cbz_updatesExistingComicInfo() throws Exception { // Create a CBZ *with* an existing ComicInfo.xml Path out = tempDir.resolve("with_meta.cbz"); String xml = """ @@ -161,7 +182,7 @@ class CbxMetadataWriterTest { meta.setTitle("New Title"); meta.setDescription("New Summary"); - writer.writeMetadataToFile(out.toFile(), meta, null, new MetadataClearFlags()); + writer.saveMetadataToFile(out.toFile(), meta, null, new MetadataClearFlags()); try (ZipFile zip = new ZipFile(out.toFile())) { ZipEntry ci = zip.getEntry("ComicInfo.xml"); @@ -178,7 +199,7 @@ class CbxMetadataWriterTest { private static File createCbz(Path path, String[] imageNames) throws Exception { try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(path.toFile()))) { for (String name : imageNames) { - put(zos, name, new byte[]{1,2,3}); + put(zos, name, new byte[]{1, 2, 3}); } } return path.toFile(); diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java index c7b6f87e1..97c179e67 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/metadata/writer/EpubMetadataWriterTest.java @@ -1,10 +1,13 @@ package com.adityachandel.booklore.service.metadata.writer; import com.adityachandel.booklore.model.MetadataClearFlags; +import com.adityachandel.booklore.model.dto.settings.AppSettings; +import com.adityachandel.booklore.model.dto.settings.MetadataPersistenceSettings; 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.LibraryPathEntity; +import com.adityachandel.booklore.service.appsettings.AppSettingService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; @@ -13,33 +16,48 @@ import org.junit.jupiter.api.io.TempDir; import org.springframework.mock.web.MockMultipartFile; import org.springframework.web.multipart.MultipartFile; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.InputStream; -import java.io.IOException; +import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; -import java.util.zip.ZipFile; import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; class EpubMetadataWriterTest { private EpubMetadataWriter writer; private BookMetadataEntity metadata; private BookEntity bookEntity; + private AppSettingService appSettingService; @TempDir Path tempDir; @BeforeEach void setUp() { - writer = new EpubMetadataWriter(); + appSettingService = mock(AppSettingService.class); + MetadataPersistenceSettings.FormatSettings epubFormatSettings = MetadataPersistenceSettings.FormatSettings.builder() + .enabled(true) + .maxFileSizeInMb(100) + .build(); + MetadataPersistenceSettings.SaveToOriginalFile saveToOriginalFile = MetadataPersistenceSettings.SaveToOriginalFile.builder() + .epub(epubFormatSettings) + .build(); + MetadataPersistenceSettings metadataPersistenceSettings = new MetadataPersistenceSettings(); + metadataPersistenceSettings.setSaveToOriginalFile(saveToOriginalFile); + + AppSettings appSettings = mock(AppSettings.class); + when(appSettings.getMetadataPersistenceSettings()).thenReturn(metadataPersistenceSettings); + when(appSettingService.getAppSettings()).thenReturn(appSettings); + + writer = new EpubMetadataWriter(appSettingService); metadata = new BookMetadataEntity(); metadata.setTitle("Test Book"); AuthorEntity author = new AuthorEntity(); @@ -66,14 +84,14 @@ class EpubMetadataWriterTest { existingMetadata.append("ill"); existingMetadata.append(""); String opfContent = String.format(""" - - - %s - - """, existingMetadata); + + + %s + + """, existingMetadata); File epubFile = createEpubWithOpf(opfContent, "test-metadata-" + System.nanoTime() + ".epub"); - assertDoesNotThrow(() -> writer.writeMetadataToFile(epubFile, metadata, null, new MetadataClearFlags())); + assertDoesNotThrow(() -> writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags())); assertTrue(epubFile.exists()); assertTrue(epubFile.length() > 0); @@ -99,7 +117,7 @@ class EpubMetadataWriterTest { File epubFile = tempDir.resolve("test_unicode.epub").toFile(); Files.write(epubFile.toPath(), epubContent); - assertDoesNotThrow(() -> writer.writeMetadataToFile(epubFile, metadata, null, new MetadataClearFlags())); + assertDoesNotThrow(() -> writer.saveMetadataToFile(epubFile, metadata, null, new MetadataClearFlags())); assertTrue(epubFile.exists()); assertTrue(epubFile.length() > 0); @@ -114,10 +132,10 @@ class EpubMetadataWriterTest { byte[] imageBytes = createMinimalPngImage(); MultipartFile coverFile = new MockMultipartFile( - "cover.png", - "cover.png", - "image/png", - imageBytes + "cover.png", + "cover.png", + "image/png", + imageBytes ); assertDoesNotThrow(() -> writer.replaceCoverImageFromUpload(bookEntity, coverFile)); @@ -128,13 +146,13 @@ class EpubMetadataWriterTest { File epubFile = tempDir.resolve(filename).toFile(); String containerXml = """ - - - - - - - """; + + + + + + + """; try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epubFile))) { zos.putNextEntry(new ZipEntry("mimetype")); @@ -155,67 +173,67 @@ class EpubMetadataWriterTest { private byte[] createEpubWithUnicodeCoverHref() throws IOException { String opfContent = """ - - - - Test Book with Unicode Cover - Test Author - - - - - - - - - - - - """; + + + + Test Book with Unicode Cover + Test Author + + + + + + + + + + + + """; String containerXml = """ - - - - - - - """; + + + + + + + """; String htmlContent = """ - - - - - Test - - -

Test Content

- - - """; + + + + + Test + + +

Test Content

+ + + """; String ncxContent = """ - - - - - - - - Test Book - - - - - Test - - - - - - """; + + + + + + + + Test Book + + + + + Test + + + + + + """; byte[] coverImage = createMinimalPngImage(); @@ -253,22 +271,23 @@ class EpubMetadataWriterTest { private byte[] createMinimalPngImage() { return new byte[]{ - (byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, - 0x00, 0x00, 0x00, 0x0D, - 0x49, 0x48, 0x44, 0x52, - 0x00, 0x00, 0x00, 0x01, - 0x00, 0x00, 0x00, 0x01, - 0x08, 0x06, - 0x00, 0x00, 0x00, - (byte) 0x90, (byte) 0x77, (byte) 0x53, (byte) 0xDE, - 0x00, 0x00, 0x00, 0x0A, - 0x49, 0x44, 0x41, 0x54, - 0x78, (byte) 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, - 0x00, 0x01, - 0x0D, (byte) 0x0A, 0x2D, (byte) 0xB4, - 0x00, 0x00, 0x00, 0x00, - 0x49, 0x45, 0x4E, 0x44, - (byte) 0xAE, 0x42, 0x60, (byte) 0x82 + (byte) 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, + 0x00, 0x00, 0x00, 0x0D, + 0x49, 0x48, 0x44, 0x52, + 0x00, 0x00, 0x00, 0x01, + 0x00, 0x00, 0x00, 0x01, + 0x08, 0x06, + 0x00, 0x00, 0x00, + (byte) 0x90, (byte) 0x77, (byte) 0x53, (byte) 0xDE, + 0x00, 0x00, 0x00, 0x0A, + 0x49, 0x44, 0x41, 0x54, + 0x78, (byte) 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, 0x05, + 0x00, 0x01, + 0x0D, (byte) 0x0A, 0x2D, (byte) 0xB4, + 0x00, 0x00, 0x00, 0x00, + 0x49, 0x45, 0x4E, 0x44, + (byte) 0xAE, 0x42, 0x60, (byte) 0x82 }; } -} \ No newline at end of file +} + diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java index 4195ff012..76265458b 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/util/FileServiceTest.java @@ -15,9 +15,6 @@ import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.FileSystemResource; -import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; @@ -64,7 +61,7 @@ class FileServiceTest { .coverCroppingSettings(coverCroppingSettings) .build(); lenient().when(appSettingService.getAppSettings()).thenReturn(appSettings); - + fileService = new FileService(appProperties, mock(RestTemplate.class), appSettingService, mock(BookMetadataRepository.class)); } @@ -165,12 +162,12 @@ class FileServiceTest { static Stream truncateTestCases() { return Stream.of( - Arguments.of("hello world", 5, "hello"), - Arguments.of("test", 10, "test"), - Arguments.of("abc", 3, "abc"), - Arguments.of("ab", 3, "ab"), - Arguments.of("a", 1, "a"), - Arguments.of("newline\ntest", 7, "newline") + Arguments.of("hello world", 5, "hello"), + Arguments.of("test", 10, "test"), + Arguments.of("abc", 3, "abc"), + Arguments.of("ab", 3, "ab"), + Arguments.of("a", 1, "a"), + Arguments.of("newline\ntest", 7, "newline") ); } } @@ -191,11 +188,11 @@ class FileServiceTest { @Test void returnsCorrectPath() { String result = fileService.getImagesFolder(123L); - + assertAll( - () -> assertTrue(result.contains("images")), - () -> assertTrue(result.contains("123")), - () -> assertTrue(result.startsWith(tempDir.toString())) + () -> assertTrue(result.contains("images")), + () -> assertTrue(result.contains("123")), + () -> assertTrue(result.startsWith(tempDir.toString())) ); } @@ -214,10 +211,10 @@ class FileServiceTest { @Test void returnsCorrectPath() { String result = fileService.getThumbnailFile(456L); - + assertAll( - () -> assertTrue(result.contains("456")), - () -> assertTrue(result.endsWith("thumbnail.jpg")) + () -> assertTrue(result.contains("456")), + () -> assertTrue(result.endsWith("thumbnail.jpg")) ); } } @@ -229,10 +226,10 @@ class FileServiceTest { @Test void returnsCorrectPath() { String result = fileService.getCoverFile(789L); - + assertAll( - () -> assertTrue(result.contains("789")), - () -> assertTrue(result.endsWith("cover.jpg")) + () -> assertTrue(result.contains("789")), + () -> assertTrue(result.endsWith("cover.jpg")) ); } } @@ -244,20 +241,20 @@ class FileServiceTest { @Test void withUserId_returnsUserSpecificPath() { String result = fileService.getBackgroundsFolder(42L); - + assertAll( - () -> assertTrue(result.contains("backgrounds")), - () -> assertTrue(result.contains("user-42")) + () -> assertTrue(result.contains("backgrounds")), + () -> assertTrue(result.contains("user-42")) ); } @Test void withNullUserId_returnsGlobalPath() { String result = fileService.getBackgroundsFolder(null); - + assertAll( - () -> assertTrue(result.contains("backgrounds")), - () -> assertFalse(result.contains("user-")) + () -> assertTrue(result.contains("backgrounds")), + () -> assertFalse(result.contains("user-")) ); } @@ -265,7 +262,7 @@ class FileServiceTest { void noArgs_delegatesToNullUserId() { String withNull = fileService.getBackgroundsFolder(null); String noArgs = fileService.getBackgroundsFolder(); - + assertEquals(withNull, noArgs); } } @@ -277,24 +274,24 @@ class FileServiceTest { @Test void withUserId_returnsCorrectUrl() { String result = FileService.getBackgroundUrl("bg.jpg", 10L); - + assertAll( - () -> assertTrue(result.startsWith("/")), - () -> assertTrue(result.contains("backgrounds")), - () -> assertTrue(result.contains("user-10")), - () -> assertTrue(result.endsWith("bg.jpg")), - () -> assertFalse(result.contains("\\"), "Should use forward slashes") + () -> assertTrue(result.startsWith("/")), + () -> assertTrue(result.contains("backgrounds")), + () -> assertTrue(result.contains("user-10")), + () -> assertTrue(result.endsWith("bg.jpg")), + () -> assertFalse(result.contains("\\"), "Should use forward slashes") ); } @Test void withoutUserId_returnsGlobalUrl() { String result = FileService.getBackgroundUrl("bg.jpg", null); - + assertAll( - () -> assertFalse(result.contains("user-")), - () -> assertTrue(result.contains("backgrounds")), - () -> assertFalse(result.contains("\\")) + () -> assertFalse(result.contains("user-")), + () -> assertTrue(result.contains("backgrounds")), + () -> assertFalse(result.contains("\\")) ); } @@ -312,10 +309,10 @@ class FileServiceTest { @Test void getBookMetadataBackupPath_returnsCorrectPath() { String result = fileService.getBookMetadataBackupPath(100L); - + assertAll( - () -> assertTrue(result.contains("metadata_backup")), - () -> assertTrue(result.contains("100")) + () -> assertTrue(result.contains("metadata_backup")), + () -> assertTrue(result.contains("100")) ); } @@ -332,20 +329,20 @@ class FileServiceTest { @Test void getTempBookdropCoverImagePath_returnsCorrectPath() { String result = fileService.getTempBookdropCoverImagePath(555L); - + assertAll( - () -> assertTrue(result.contains("bookdrop_temp")), - () -> assertTrue(result.endsWith("555.jpg")) + () -> assertTrue(result.contains("bookdrop_temp")), + () -> assertTrue(result.endsWith("555.jpg")) ); } @Test void getToolsKepubifyPath_returnsCorrectPath() { String result = fileService.getToolsKepubifyPath(); - + assertAll( - () -> assertTrue(result.contains("tools")), - () -> assertTrue(result.contains("kepubify")) + () -> assertTrue(result.contains("tools")), + () -> assertTrue(result.contains("kepubify")) ); } } @@ -362,9 +359,9 @@ class FileServiceTest { void validData_returnsImage() throws IOException { BufferedImage image = createTestImage(100, 100); byte[] imageData = imageToBytes(image); - + BufferedImage result = FileService.readImage(imageData); - + assertNotNull(result); assertEquals(100, result.getWidth()); assertEquals(100, result.getHeight()); @@ -396,70 +393,70 @@ class FileServiceTest { @Test void shrinks_imageProperly() { BufferedImage original = createTestImage(100, 100); - + BufferedImage resized = FileService.resizeImage(original, 50, 50); - + assertAll( - () -> assertEquals(50, resized.getWidth()), - () -> assertEquals(50, resized.getHeight()) + () -> assertEquals(50, resized.getWidth()), + () -> assertEquals(50, resized.getHeight()) ); } @Test void enlarges_imageProperly() { BufferedImage original = createTestImage(50, 50); - + BufferedImage resized = FileService.resizeImage(original, 200, 200); - + assertAll( - () -> assertEquals(200, resized.getWidth()), - () -> assertEquals(200, resized.getHeight()) + () -> assertEquals(200, resized.getWidth()), + () -> assertEquals(200, resized.getHeight()) ); } @Test void changesAspectRatio() { BufferedImage original = createTestImage(100, 100); - + BufferedImage resized = FileService.resizeImage(original, 200, 50); - + assertAll( - () -> assertEquals(200, resized.getWidth()), - () -> assertEquals(50, resized.getHeight()) + () -> assertEquals(200, resized.getWidth()), + () -> assertEquals(50, resized.getHeight()) ); } @Test void sameSize_worksCorrectly() { BufferedImage original = createTestImage(100, 100); - + BufferedImage resized = FileService.resizeImage(original, 100, 100); - + assertAll( - () -> assertEquals(100, resized.getWidth()), - () -> assertEquals(100, resized.getHeight()), - () -> assertNotSame(original, resized) + () -> assertEquals(100, resized.getWidth()), + () -> assertEquals(100, resized.getHeight()), + () -> assertNotSame(original, resized) ); } @Test void returnsRGBType() { BufferedImage original = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); - + BufferedImage resized = FileService.resizeImage(original, 50, 50); - + assertEquals(BufferedImage.TYPE_INT_RGB, resized.getType()); } @Test void handlesVerySmallDimensions() { BufferedImage original = createTestImage(100, 100); - + BufferedImage resized = FileService.resizeImage(original, 1, 1); - + assertAll( - () -> assertEquals(1, resized.getWidth()), - () -> assertEquals(1, resized.getHeight()) + () -> assertEquals(1, resized.getWidth()), + () -> assertEquals(1, resized.getHeight()) ); } } @@ -473,12 +470,12 @@ class FileServiceTest { BufferedImage image = createTestImage(100, 100); byte[] imageData = imageToBytes(image); Path outputPath = tempDir.resolve("test-output.jpg"); - + FileService.saveImage(imageData, outputPath.toString()); - + assertAll( - () -> assertTrue(Files.exists(outputPath)), - () -> assertTrue(Files.size(outputPath) > 0) + () -> assertTrue(Files.exists(outputPath)), + () -> assertTrue(Files.size(outputPath) > 0) ); } @@ -487,9 +484,9 @@ class FileServiceTest { BufferedImage image = createTestImage(100, 100); byte[] imageData = imageToBytes(image); Path outputPath = tempDir.resolve("nested/deep/folder/test.jpg"); - + FileService.saveImage(imageData, outputPath.toString()); - + assertTrue(Files.exists(outputPath)); } @@ -499,7 +496,7 @@ class FileServiceTest { Path outputPath = tempDir.resolve("invalid.jpg"); assertDoesNotThrow(() -> - FileService.saveImage(invalidData, outputPath.toString())); + FileService.saveImage(invalidData, outputPath.toString())); assertFalse(Files.exists(outputPath)); } @@ -509,7 +506,7 @@ class FileServiceTest { Path outputPath = tempDir.resolve("empty.jpg"); IOException ex = assertThrows(IOException.class, () -> - FileService.saveImage(emptyData, outputPath.toString())); + FileService.saveImage(emptyData, outputPath.toString())); assertEquals("Image data is null or empty", ex.getMessage()); } @@ -518,14 +515,14 @@ class FileServiceTest { BufferedImage original = createTestImage(100, 100); byte[] imageData = imageToBytes(original); Path outputPath = tempDir.resolve("readable.jpg"); - + FileService.saveImage(imageData, outputPath.toString()); BufferedImage loaded = ImageIO.read(outputPath.toFile()); - + assertAll( - () -> assertNotNull(loaded), - () -> assertEquals(100, loaded.getWidth()), - () -> assertEquals(100, loaded.getHeight()) + () -> assertNotNull(loaded), + () -> assertEquals(100, loaded.getWidth()), + () -> assertEquals(100, loaded.getHeight()) ); } @@ -535,7 +532,7 @@ class FileServiceTest { byte[] imageData = imageToBytes(image); Path nestedPath = tempDir.resolve("nested/deep/folder/test.jpg"); assertDoesNotThrow(() -> FileService.saveImage(imageData, nestedPath.toString()), - "Should create nested directories automatically"); + "Should create nested directories automatically"); assertTrue(Files.exists(nestedPath), "File should be created in nested directory"); } @@ -543,7 +540,7 @@ class FileServiceTest { void nullImageData_throwsException() { Path outputPath = tempDir.resolve("null.jpg"); IOException ex = assertThrows(IOException.class, () -> - FileService.saveImage(null, outputPath.toString())); + FileService.saveImage(null, outputPath.toString())); assertEquals("Image data is null or empty", ex.getMessage()); } } @@ -565,46 +562,46 @@ class FileServiceTest { @Test void createsBothCoverAndThumbnail() throws IOException { BufferedImage image = createTestImage(500, 700); - + boolean result = fileService.saveCoverImages(image, 1L); - + assertAll( - () -> assertTrue(result), - () -> assertTrue(Files.exists(Path.of(fileService.getCoverFile(1L)))), - () -> assertTrue(Files.exists(Path.of(fileService.getThumbnailFile(1L)))) + () -> assertTrue(result), + () -> assertTrue(Files.exists(Path.of(fileService.getCoverFile(1L)))), + () -> assertTrue(Files.exists(Path.of(fileService.getThumbnailFile(1L)))) ); } @Test void thumbnailHasCorrectDimensions() throws IOException { BufferedImage image = createTestImage(1000, 1400); - + fileService.saveCoverImages(image, 2L); - + BufferedImage thumbnail = ImageIO.read( - new File(fileService.getThumbnailFile(2L))); - + new File(fileService.getThumbnailFile(2L))); + assertAll( - () -> assertEquals(250, thumbnail.getWidth()), - () -> assertEquals(350, thumbnail.getHeight()) + () -> assertEquals(250, thumbnail.getWidth()), + () -> assertEquals(350, thumbnail.getHeight()) ); } @Test void convertsTransparentToOpaqueWithWhiteBackground() throws IOException { BufferedImage imageWithAlpha = new BufferedImage( - 100, 100, BufferedImage.TYPE_INT_ARGB); + 100, 100, BufferedImage.TYPE_INT_ARGB); Graphics2D g = imageWithAlpha.createGraphics(); g.setColor(new Color(255, 0, 0, 128)); // Semi-transparent red g.fillRect(0, 0, 100, 100); g.dispose(); - + boolean result = fileService.saveCoverImages(imageWithAlpha, 3L); - + assertTrue(result); - + BufferedImage saved = ImageIO.read( - new File(fileService.getCoverFile(3L))); + new File(fileService.getCoverFile(3L))); assertFalse(saved.getColorModel().hasAlpha(), "Saved image should not have transparency"); } @@ -612,25 +609,25 @@ class FileServiceTest { void createsDirectoryIfNotExists() throws IOException { BufferedImage image = createTestImage(100, 100); long bookId = 999L; - + fileService.saveCoverImages(image, bookId); - + assertTrue(Files.isDirectory( - Path.of(fileService.getImagesFolder(bookId)))); + Path.of(fileService.getImagesFolder(bookId)))); } @Test void originalMaintainsDimensions() throws IOException { BufferedImage image = createTestImage(800, 1200); - + fileService.saveCoverImages(image, 4L); - + BufferedImage saved = ImageIO.read( - new File(fileService.getCoverFile(4L))); - + new File(fileService.getCoverFile(4L))); + assertAll( - () -> assertEquals(800, saved.getWidth()), - () -> assertEquals(1200, saved.getHeight()) + () -> assertEquals(800, saved.getWidth()), + () -> assertEquals(1200, saved.getHeight()) ); } @@ -646,14 +643,14 @@ class FileServiceTest { assertTrue(result); BufferedImage savedCover = ImageIO.read( - new File(fileService.getCoverFile(5L))); + new File(fileService.getCoverFile(5L))); assertNotNull(savedCover); assertTrue(savedCover.getWidth() <= 1000, - "Cover width should be <= MAX_ORIGINAL_WIDTH (1000), was: " + savedCover.getWidth()); + "Cover width should be <= MAX_ORIGINAL_WIDTH (1000), was: " + savedCover.getWidth()); assertTrue(savedCover.getHeight() <= 1500, - "Cover height should be <= MAX_ORIGINAL_HEIGHT (1500), was: " + savedCover.getHeight()); + "Cover height should be <= MAX_ORIGINAL_HEIGHT (1500), was: " + savedCover.getHeight()); double originalRatio = (double) largeWidth / largeHeight; double savedRatio = (double) savedCover.getWidth() / savedCover.getHeight(); @@ -672,14 +669,14 @@ class FileServiceTest { assertTrue(result); BufferedImage savedCover = ImageIO.read( - new File(fileService.getCoverFile(6L))); + new File(fileService.getCoverFile(6L))); assertNotNull(savedCover); assertEquals(smallWidth, savedCover.getWidth(), - "Small image width should be preserved"); + "Small image width should be preserved"); assertEquals(smallHeight, savedCover.getHeight(), - "Small image height should be preserved"); + "Small image height should be preserved"); } } @@ -700,14 +697,14 @@ class FileServiceTest { assertTrue(result); BufferedImage savedCover = ImageIO.read( - new File(fileService.getCoverFile(100L))); + new File(fileService.getCoverFile(100L))); assertNotNull(savedCover); - + // The image should be cropped to approximately 1.5:1 ratio from the top double savedRatio = (double) savedCover.getHeight() / savedCover.getWidth(); - assertTrue(savedRatio < 3.0, - "Cropped image should have reasonable aspect ratio, was: " + savedRatio); + assertTrue(savedRatio < 3.0, + "Cropped image should have reasonable aspect ratio, was: " + savedRatio); } @Test @@ -723,14 +720,14 @@ class FileServiceTest { assertTrue(result); BufferedImage savedCover = ImageIO.read( - new File(fileService.getCoverFile(101L))); + new File(fileService.getCoverFile(101L))); assertNotNull(savedCover); - + // The image should be cropped to a more reasonable aspect ratio double savedRatio = (double) savedCover.getWidth() / savedCover.getHeight(); - assertTrue(savedRatio < 3.0, - "Cropped image should have reasonable aspect ratio, was: " + savedRatio); + assertTrue(savedRatio < 3.0, + "Cropped image should have reasonable aspect ratio, was: " + savedRatio); } @Test @@ -746,15 +743,15 @@ class FileServiceTest { assertTrue(result); BufferedImage savedCover = ImageIO.read( - new File(fileService.getCoverFile(102L))); + new File(fileService.getCoverFile(102L))); assertNotNull(savedCover); - + // The image should maintain its original aspect ratio double originalRatio = (double) height / width; double savedRatio = (double) savedCover.getHeight() / savedCover.getWidth(); - assertEquals(originalRatio, savedRatio, 0.01, - "Normal aspect ratio image should not be cropped"); + assertEquals(originalRatio, savedRatio, 0.01, + "Normal aspect ratio image should not be cropped"); } @Test @@ -781,15 +778,15 @@ class FileServiceTest { assertTrue(result); BufferedImage savedCover = ImageIO.read( - new File(fileService.getCoverFile(103L))); + new File(fileService.getCoverFile(103L))); assertNotNull(savedCover); - + // Since the image exceeds max dimensions, it will be scaled, but aspect ratio preserved double originalRatio = (double) height / width; double savedRatio = (double) savedCover.getHeight() / savedCover.getWidth(); - assertEquals(originalRatio, savedRatio, 0.01, - "Image should not be cropped when cropping is disabled"); + assertEquals(originalRatio, savedRatio, 0.01, + "Image should not be cropped when cropping is disabled"); } @Test @@ -915,34 +912,34 @@ class FileServiceTest { void validImageBytes_succeeds() throws IOException { BufferedImage image = createTestImage(300, 400); byte[] imageBytes = imageToBytes(image); - - assertDoesNotThrow(() -> - fileService.createThumbnailFromBytes(15L, imageBytes)); + + assertDoesNotThrow(() -> + fileService.createThumbnailFromBytes(15L, imageBytes)); assertTrue(Files.exists(Path.of(fileService.getCoverFile(15L)))); } @Test void invalidImageBytes_skipsThumbnail() { byte[] invalidData = "not an image".getBytes(); - + assertDoesNotThrow(() -> - fileService.createThumbnailFromBytes(16L, invalidData)); + fileService.createThumbnailFromBytes(16L, invalidData)); assertFalse(Files.exists(Path.of(fileService.getCoverFile(16L)))); } @Test void emptyImageBytes_throwsRuntimeException() { byte[] emptyData = new byte[0]; - + RuntimeException exception = assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromBytes(17L, emptyData)); + fileService.createThumbnailFromBytes(17L, emptyData)); assertEquals("Error reading files from path: Image data is null or empty", exception.getMessage()); } @Test void nullImageBytes_throwsRuntimeException() { RuntimeException exception = assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromBytes(18L, null)); + fileService.createThumbnailFromBytes(18L, null)); assertEquals("Error reading files from path: Image data is null or empty", exception.getMessage()); } } @@ -956,10 +953,10 @@ class FileServiceTest { BufferedImage image = createTestImage(300, 400); byte[] imageBytes = imageToBytes(image); MockMultipartFile file = new MockMultipartFile( - "file", "test.jpg", "image/jpeg", imageBytes); - - assertDoesNotThrow(() -> - fileService.createThumbnailFromFile(5L, file)); + "file", "test.jpg", "image/jpeg", imageBytes); + + assertDoesNotThrow(() -> + fileService.createThumbnailFromFile(5L, file)); assertTrue(Files.exists(Path.of(fileService.getCoverFile(5L)))); } @@ -969,49 +966,49 @@ class FileServiceTest { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "PNG", baos); MockMultipartFile file = new MockMultipartFile( - "file", "test.png", "image/png", baos.toByteArray()); - - assertDoesNotThrow(() -> - fileService.createThumbnailFromFile(6L, file)); + "file", "test.png", "image/png", baos.toByteArray()); + + assertDoesNotThrow(() -> + fileService.createThumbnailFromFile(6L, file)); } @Test void emptyFile_throwsRuntimeException() { MockMultipartFile emptyFile = new MockMultipartFile( - "file", "empty.jpg", "image/jpeg", new byte[0]); - + "file", "empty.jpg", "image/jpeg", new byte[0]); + // validateCoverFile throws IllegalArgumentException, but it's caught and wrapped in RuntimeException via ApiError RuntimeException exception = assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromFile(7L, emptyFile)); - assertTrue(exception.getMessage().contains("empty") || - exception.getCause() instanceof IllegalArgumentException, - "Exception message should indicate file is empty or wrap IllegalArgumentException"); + fileService.createThumbnailFromFile(7L, emptyFile)); + assertTrue(exception.getMessage().contains("empty") || + exception.getCause() instanceof IllegalArgumentException, + "Exception message should indicate file is empty or wrap IllegalArgumentException"); } @Test void invalidMimeType_throwsRuntimeException() { MockMultipartFile gifFile = new MockMultipartFile( - "file", "test.gif", "image/gif", "fake data".getBytes()); - + "file", "test.gif", "image/gif", "fake data".getBytes()); + RuntimeException exception = assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromFile(8L, gifFile)); + fileService.createThumbnailFromFile(8L, gifFile)); assertTrue(exception.getMessage().contains("Only JPEG and PNG files are allowed") || - exception.getCause() instanceof IllegalArgumentException, - "Exception message should indicate only JPEG and PNG are allowed or wrap IllegalArgumentException"); + exception.getCause() instanceof IllegalArgumentException, + "Exception message should indicate only JPEG and PNG are allowed or wrap IllegalArgumentException"); } @Test void fileTooLarge_throwsRuntimeException() { byte[] largeData = new byte[6 * 1024 * 1024]; // 6MB MockMultipartFile largeFile = new MockMultipartFile( - "file", "large.jpg", "image/jpeg", largeData); - + "file", "large.jpg", "image/jpeg", largeData); + // validateCoverFile throws IllegalArgumentException, but it's caught and wrapped in RuntimeException via ApiError RuntimeException exception = assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromFile(9L, largeFile)); + fileService.createThumbnailFromFile(9L, largeFile)); assertTrue(exception.getMessage().contains("5 MB") || - exception.getCause() instanceof IllegalArgumentException, - "Exception message should indicate file size limit or wrap IllegalArgumentException"); + exception.getCause() instanceof IllegalArgumentException, + "Exception message should indicate file size limit or wrap IllegalArgumentException"); } @Test @@ -1020,12 +1017,12 @@ class FileServiceTest { byte[] imageBytes = imageToBytes(image); // Ensure it's under 5MB assertTrue(imageBytes.length < 5 * 1024 * 1024); - + MockMultipartFile file = new MockMultipartFile( - "file", "valid.jpg", "image/jpeg", imageBytes); - + "file", "valid.jpg", "image/jpeg", imageBytes); + assertDoesNotThrow(() -> - fileService.createThumbnailFromFile(10L, file)); + fileService.createThumbnailFromFile(10L, file)); } @Test @@ -1033,10 +1030,10 @@ class FileServiceTest { BufferedImage image = createTestImage(100, 100); byte[] imageBytes = imageToBytes(image); MockMultipartFile file = new MockMultipartFile( - "file", "test.jpg", "IMAGE/JPEG", imageBytes); + "file", "test.jpg", "IMAGE/JPEG", imageBytes); assertDoesNotThrow(() -> - fileService.createThumbnailFromFile(11L, file)); + fileService.createThumbnailFromFile(11L, file)); } @Test @@ -1044,10 +1041,10 @@ class FileServiceTest { // Valid MIME type but corrupt image data byte[] corruptData = ("not an image but has jpeg mime type").getBytes(); MockMultipartFile corruptFile = new MockMultipartFile( - "file", "corrupt.jpg", "image/jpeg", corruptData); + "file", "corrupt.jpg", "image/jpeg", corruptData); assertDoesNotThrow(() -> - fileService.createThumbnailFromFile(12L, corruptFile)); + fileService.createThumbnailFromFile(12L, corruptFile)); assertFalse(Files.exists(Path.of(fileService.getCoverFile(12L)))); } @@ -1055,12 +1052,12 @@ class FileServiceTest { void unsupportedMimeType_gif_throwsRuntimeException() { byte[] gifData = "GIF89a...".getBytes(); // Fake GIF header MockMultipartFile gifFile = new MockMultipartFile( - "file", "test.gif", "image/gif", gifData); + "file", "test.gif", "image/gif", gifData); // validateCoverFile throws IllegalArgumentException, but it's caught and wrapped in RuntimeException via ApiError assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromFile(13L, gifFile), - "Should throw RuntimeException (wrapping IllegalArgumentException) for unsupported MIME type"); + fileService.createThumbnailFromFile(13L, gifFile), + "Should throw RuntimeException (wrapping IllegalArgumentException) for unsupported MIME type"); } @Test @@ -1068,10 +1065,10 @@ class FileServiceTest { BufferedImage image = createTestImage(100, 100); byte[] imageBytes = imageToBytes(image); MockMultipartFile file = new MockMultipartFile( - "file", "test.jpg", "image/jpeg;charset=UTF-8", imageBytes); + "file", "test.jpg", "image/jpeg;charset=UTF-8", imageBytes); assertDoesNotThrow(() -> - fileService.createThumbnailFromFile(14L, file)); + fileService.createThumbnailFromFile(14L, file)); } } @@ -1083,11 +1080,11 @@ class FileServiceTest { void setsTimestampToCurrentTime() { BookMetadataEntity entity = new BookMetadataEntity(); Instant before = Instant.now(); - + FileService.setBookCoverPath(entity); - + Instant after = Instant.now(); - + assertNotNull(entity.getCoverUpdatedOn()); assertFalse(entity.getCoverUpdatedOn().isBefore(before)); assertFalse(entity.getCoverUpdatedOn().isAfter(after)); @@ -1098,9 +1095,9 @@ class FileServiceTest { BookMetadataEntity entity = new BookMetadataEntity(); Instant oldTime = Instant.parse("2020-01-01T00:00:00Z"); entity.setCoverUpdatedOn(oldTime); - + FileService.setBookCoverPath(entity); - + assertNotEquals(oldTime, entity.getCoverUpdatedOn()); } } @@ -1114,36 +1111,36 @@ class FileServiceTest { BufferedImage image = createTestImage(100, 100); fileService.saveCoverImages(image, 10L); fileService.saveCoverImages(image, 11L); - + fileService.deleteBookCovers(Set.of(10L, 11L)); - + assertAll( - () -> assertFalse(Files.exists( - Path.of(fileService.getImagesFolder(10L)))), - () -> assertFalse(Files.exists( - Path.of(fileService.getImagesFolder(11L)))) + () -> assertFalse(Files.exists( + Path.of(fileService.getImagesFolder(10L)))), + () -> assertFalse(Files.exists( + Path.of(fileService.getImagesFolder(11L)))) ); } @Test void nonExistentCovers_doesNotThrow() { assertDoesNotThrow(() -> - fileService.deleteBookCovers(Set.of(999L, 1000L))); + fileService.deleteBookCovers(Set.of(999L, 1000L))); } @Test void emptySet_doesNothing() { assertDoesNotThrow(() -> - fileService.deleteBookCovers(Set.of())); + fileService.deleteBookCovers(Set.of())); } @Test void mixedExistingAndNonExisting_deletesExisting() throws Exception { BufferedImage image = createTestImage(100, 100); fileService.saveCoverImages(image, 20L); - + fileService.deleteBookCovers(Set.of(20L, 21L)); - + assertFalse(Files.exists(Path.of(fileService.getImagesFolder(20L)))); } @@ -1151,9 +1148,9 @@ class FileServiceTest { void singleBookId_works() throws IOException { BufferedImage image = createTestImage(100, 100); fileService.saveCoverImages(image, 30L); - + fileService.deleteBookCovers(Set.of(30L)); - + assertFalse(Files.exists(Path.of(fileService.getImagesFolder(30L)))); } } @@ -1174,7 +1171,7 @@ class FileServiceTest { @BeforeEach void setup() { lenient().when(appProperties.getPathConfig()).thenReturn(tempDir.toString()); - + CoverCroppingSettings coverCroppingSettings = CoverCroppingSettings.builder() .verticalCroppingEnabled(true) .horizontalCroppingEnabled(true) @@ -1184,7 +1181,7 @@ class FileServiceTest { .coverCroppingSettings(coverCroppingSettings) .build(); lenient().when(appSettingServiceForNetwork.getAppSettings()).thenReturn(appSettings); - + fileService = new FileService(appProperties, restTemplate, appSettingServiceForNetwork, mock(BookMetadataRepository.class)); } @@ -1206,10 +1203,10 @@ class FileServiceTest { ResponseEntity responseEntity = ResponseEntity.ok(imageBytes); when(mockRestTemplate.exchange( - eq(imageUrl), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) )).thenReturn(responseEntity); BufferedImage result = testFileService.downloadImageFromUrl(imageUrl); @@ -1226,14 +1223,14 @@ class FileServiceTest { String imageUrl = "http://example.com/image.jpg"; ResponseEntity responseEntity = ResponseEntity.ok(null); when(restTemplate.exchange( - eq(imageUrl), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) )).thenReturn(responseEntity); assertThrows(IOException.class, () -> - fileService.downloadImageFromUrl(imageUrl)); + fileService.downloadImageFromUrl(imageUrl)); } @Test @@ -1244,10 +1241,10 @@ class FileServiceTest { byte[] invalidBytes = "not an image".getBytes(); ResponseEntity responseEntity = ResponseEntity.ok(invalidBytes); when(restTemplate.exchange( - eq(imageUrl), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) )).thenReturn(responseEntity); BufferedImage result = fileService.downloadImageFromUrl(imageUrl); @@ -1261,14 +1258,14 @@ class FileServiceTest { String imageUrl = "http://example.com/image.jpg"; ResponseEntity responseEntity = ResponseEntity.notFound().build(); when(restTemplate.exchange( - eq(imageUrl), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) )).thenReturn(responseEntity); assertThrows(IOException.class, () -> - fileService.downloadImageFromUrl(imageUrl)); + fileService.downloadImageFromUrl(imageUrl)); } } @@ -1287,14 +1284,14 @@ class FileServiceTest { ResponseEntity responseEntity = ResponseEntity.ok(imageBytes); when(restTemplate.exchange( - eq(imageUrl), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) )).thenReturn(responseEntity); assertDoesNotThrow(() -> - fileService.createThumbnailFromUrl(bookId, imageUrl)); + fileService.createThumbnailFromUrl(bookId, imageUrl)); Path imagesFolder = tempDir.resolve("images").resolve(String.valueOf(bookId)); assertTrue(Files.exists(imagesFolder.resolve("cover.jpg"))); @@ -1313,231 +1310,30 @@ class FileServiceTest { long bookId = 42L; when(restTemplate.exchange( - eq(imageUrl), - eq(HttpMethod.GET), - any(HttpEntity.class), - eq(byte[].class) + eq(imageUrl), + eq(HttpMethod.GET), + any(HttpEntity.class), + eq(byte[].class) )).thenThrow(new RuntimeException("Network error")); // FileService wraps exceptions in RuntimeException via ApiError RuntimeException exception = assertThrows(RuntimeException.class, () -> - fileService.createThumbnailFromUrl(bookId, imageUrl)); - assertTrue(exception.getMessage().contains("Network error") || - exception.getMessage().contains("Failed"), - "Exception message should indicate download failure"); + fileService.createThumbnailFromUrl(bookId, imageUrl)); + assertTrue(exception.getMessage().contains("Network error") || + exception.getMessage().contains("Failed"), + "Exception message should indicate download failure"); } } } - @Nested - @DisplayName("Background Operations") - class BackgroundOperationsTests { - - @BeforeEach - void setup() { - when(appProperties.getPathConfig()).thenReturn(tempDir.toString()); - } - - @Nested - @DisplayName("saveBackgroundImage") - class SaveBackgroundImageTests { - - @Test - void userBackground_savesInUserFolder() throws IOException { - BufferedImage image = createTestImage(1920, 1080); - - fileService.saveBackgroundImage(image, "bg.jpg", 1L); - - Path expected = tempDir.resolve("backgrounds/user-1/bg.jpg"); - assertTrue(Files.exists(expected)); - } - - @Test - void globalBackground_savesInGlobalFolder() throws IOException { - BufferedImage image = createTestImage(1920, 1080); - - fileService.saveBackgroundImage(image, "global.jpg", null); - - Path expected = tempDir.resolve("backgrounds/global.jpg"); - assertTrue(Files.exists(expected)); - } - - @Test - void createsDirectoryIfNotExists() throws IOException { - BufferedImage image = createTestImage(100, 100); - - fileService.saveBackgroundImage(image, "new.jpg", 2L); - - assertTrue(Files.isDirectory( - tempDir.resolve("backgrounds/user-2"))); - } - - @Test - void overwritesExistingFile() throws IOException { - BufferedImage image1 = createTestImage(100, 100, Color.RED); - BufferedImage image2 = createTestImage(100, 100, Color.BLUE); - - fileService.saveBackgroundImage(image1, "bg.jpg", 3L); - assertTrue(Files.exists(tempDir.resolve("backgrounds/user-3/bg.jpg"))); - - fileService.saveBackgroundImage(image2, "bg.jpg", 3L); - - // File exists and was overwritten - assertTrue(Files.exists(tempDir.resolve("backgrounds/user-3/bg.jpg"))); - } - } - - @Nested - @DisplayName("deleteBackgroundFile") - class DeleteBackgroundFileTests { - - @Test - void existingFile_deletesIt() throws IOException { - BufferedImage image = createTestImage(100, 100); - fileService.saveBackgroundImage(image, "to-delete.jpg", 4L); - - fileService.deleteBackgroundFile("to-delete.jpg", 4L); - - assertFalse(Files.exists( - tempDir.resolve("backgrounds/user-4/to-delete.jpg"))); - } - - @Test - void nonExistentFile_doesNotThrow() { - assertDoesNotThrow(() -> - fileService.deleteBackgroundFile("nonexistent.jpg", 5L)); - } - - @Test - void lastFileInUserFolder_deletesEmptyFolder() throws IOException { - BufferedImage image = createTestImage(100, 100); - fileService.saveBackgroundImage(image, "only.jpg", 6L); - - fileService.deleteBackgroundFile("only.jpg", 6L); - - assertFalse(Files.exists(tempDir.resolve("backgrounds/user-6"))); - } - - @Test - void notLastFile_keepsFolder() throws IOException { - BufferedImage image = createTestImage(100, 100); - fileService.saveBackgroundImage(image, "file1.jpg", 7L); - fileService.saveBackgroundImage(image, "file2.jpg", 7L); - - fileService.deleteBackgroundFile("file1.jpg", 7L); - - assertTrue(Files.isDirectory( - tempDir.resolve("backgrounds/user-7"))); - } - - @Test - void globalBackground_deletesFile() throws IOException { - BufferedImage image = createTestImage(100, 100); - Path bgFolder = tempDir.resolve("backgrounds"); - Files.createDirectories(bgFolder); - ImageIO.write(image, "JPEG", bgFolder.resolve("global.jpg").toFile()); - - fileService.deleteBackgroundFile("global.jpg", null); - - assertFalse(Files.exists(bgFolder.resolve("global.jpg"))); - } - } - - @Nested - @DisplayName("getBackgroundResource") - class GetBackgroundResourceTests { - - @Test - void userHasBackground_returnsUserBackground() throws IOException { - createUserBackground(8L, "1.jpg"); - - Resource resource = fileService.getBackgroundResource(8L); - - assertAll( - () -> assertInstanceOf(FileSystemResource.class, resource), - () -> assertTrue(resource.exists()) - ); - } - - @Test - void userHasNoBackground_globalExists_returnsGlobal() throws IOException { - createGlobalBackground("1.jpg"); - - Resource resource = fileService.getBackgroundResource(9L); - - assertInstanceOf(FileSystemResource.class, resource); - } - - @Test - void noCustomBackgrounds_returnsDefault() { - Resource resource = fileService.getBackgroundResource(10L); - - assertInstanceOf(ClassPathResource.class, resource); - } - - @ParameterizedTest - @ValueSource(strings = {"1.jpg", "1.jpeg", "1.png"}) - void supportsMultipleFormats(String filename) throws IOException { - Path bgFolder = tempDir.resolve("backgrounds"); - Files.createDirectories(bgFolder); - Files.createFile(bgFolder.resolve(filename)); - - Resource resource = fileService.getBackgroundResource(null); - - assertTrue(resource.exists()); - } - - @Test - void userBackgroundTakesPriority_overGlobal() throws IOException { - createGlobalBackground("1.jpg"); - createUserBackground(11L, "1.jpg"); - - Resource resource = fileService.getBackgroundResource(11L); - - String path = ((FileSystemResource) resource).getPath(); - assertTrue(path.contains("user-11")); - } - - @Test - @DisplayName("Priority: user > global > default") - void checksPriorityOrder() throws IOException { - // Only global exists - createGlobalBackground("1.jpg"); - Resource globalResource = fileService.getBackgroundResource(12L); - assertTrue(globalResource.exists()); - - // Add user background - createUserBackground(12L, "1.jpg"); - Resource userResource = fileService.getBackgroundResource(12L); - String path = ((FileSystemResource) userResource).getPath(); - assertTrue(path.contains("user-12")); - } - - private void createUserBackground(Long userId, String filename) - throws IOException { - Path folder = tempDir.resolve("backgrounds/user-" + userId); - Files.createDirectories(folder); - BufferedImage img = createTestImage(100, 100); - ImageIO.write(img, "JPEG", folder.resolve(filename).toFile()); - } - - private void createGlobalBackground(String filename) throws IOException { - Path folder = tempDir.resolve("backgrounds"); - Files.createDirectories(folder); - BufferedImage img = createTestImage(100, 100); - ImageIO.write(img, "JPEG", folder.resolve(filename).toFile()); - } - } - } - private BufferedImage createTestImage(int width, int height) { return createTestImage(width, height, Color.BLUE); } private BufferedImage createTestImage(int width, int height, Color color) { BufferedImage image = new BufferedImage( - width, height, BufferedImage.TYPE_INT_RGB); + width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.setColor(color); g.fillRect(0, 0, width, height); 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 index 68dff8057..a9eb917dc 100644 --- a/booklore-ui/src/app/features/book/service/book.service.spec.ts +++ b/booklore-ui/src/app/features/book/service/book.service.spec.ts @@ -378,10 +378,11 @@ describe('BookService', () => { it('should update book metadata', async () => { httpMock.put.mockReturnValue(of({bookId: 1})); - service.handleBookMetadataUpdate = vi.fn(); + const spy = vi.spyOn(BookService.prototype, 'handleBookMetadataUpdate'); const result = await firstValueFrom(service.updateBookMetadata(1, {} as any, true)); expect(result).toEqual({bookId: 1}); - expect(service.handleBookMetadataUpdate).toHaveBeenCalledWith(1, {bookId: 1}); + expect(spy).toHaveBeenCalledWith(1, {bookId: 1}); + spy.mockRestore(); }); it('should update books metadata', async () => { @@ -445,14 +446,6 @@ describe('BookService', () => { expect(service.getUploadCoverUrl(1)).toContain('/1/metadata/cover/upload'); }); - it('should upload cover from url and handleBookMetadataUpdate', async () => { - httpMock.post.mockReturnValue(of({bookId: 1})); - service.handleBookMetadataUpdate = vi.fn(); - const result = await firstValueFrom(service.uploadCoverFromUrl(1, 'url')); - expect(result).toEqual({bookId: 1}); - expect(service.handleBookMetadataUpdate).toHaveBeenCalledWith(1, {bookId: 1}); - }); - it('should regenerate covers', async () => { httpMock.post.mockReturnValue(of(void 0)); const result = await firstValueFrom(service.regenerateCovers()); 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 d8029e2f9..e0a5297f0 100644 --- a/booklore-ui/src/app/features/book/service/book.service.ts +++ b/booklore-ui/src/app/features/book/service/book.service.ts @@ -529,13 +529,7 @@ export class BookService { } uploadCoverFromUrl(bookId: number, url: string): Observable { - return this.http - .post(`${this.url}/${bookId}/metadata/cover/from-url`, {url}) - .pipe( - tap(updatedMetadata => - this.handleBookMetadataUpdate(bookId, updatedMetadata) - ) - ); + return this.http.post(`${this.url}/${bookId}/metadata/cover/from-url`, {url}); } regenerateCovers(): Observable { diff --git a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html index 13c2a2f4f..56d9a5b1e 100644 --- a/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html +++ b/booklore-ui/src/app/features/metadata/component/book-metadata-center/metadata-editor/metadata-editor.component.html @@ -1,14 +1,14 @@ @if (book$ | async; as book) { -
+ @if (isLoading) { -
+
} @if (isLoading) { - + } -
-
-
+
+
+
@if (isUploading) { - - + } -
+
-
+
-
-
- -
- +
+
+ +
+ @if (!book.metadata!['titleLocked']) { } @@ -94,10 +92,10 @@
-
- -
- +
+ +
+ @if (!book.metadata!['subtitleLocked']) { } @@ -107,10 +105,10 @@
-
- -
- +
+ +
+ @if (!book.metadata!['languageLocked']) { } @@ -121,12 +119,11 @@
-
-
- -
+
+
+ +
-
- -
+
+ +
-
- -
+
+ +
-
-
- -
-
+
+
+ +
+
-
-
- -
-
+
+
+ +
+
-
-
- -
-
+
+
+ +
+
-
-
- -
+
+
+ +
-
- -
- +
+ +
+ @if (!book.metadata!['seriesNumberLocked']) { } @@ -315,10 +306,10 @@
-
- -
- +
+ +
+ @if (!book.metadata!['seriesTotalLocked']) { } @@ -328,10 +319,10 @@
-
- -
- +
+ +
+ @if (!book.metadata!['pageCountLocked']) { } @@ -344,11 +335,11 @@
-
-
- -
- +