From 77bb2904e3c590e47ca203d66583418684b73522 Mon Sep 17 00:00:00 2001 From: Giancarlo Perrone Date: Thu, 8 Jan 2026 15:14:51 -0800 Subject: [PATCH] Feature/koreader hardcover sync (#2204) * feat(settings): add hardcover sync settings and integrate into device settings UI * feat(hardcover): implement Hardcover sync settings API and UI integration * test(hardcover): add unit tests for HardcoverSyncSettingsService and HardcoverSettingsComponent * fix(hardcover-settings): correct API key copy function to handle null values properly --------- Co-authored-by: akiraslingshot Co-authored-by: ACX <8075870+acx10@users.noreply.github.com> --- .../HardcoverSyncSettingsController.java | 42 ++++ .../model/dto/HardcoverSyncSettings.java | 9 + .../model/dto/settings/UserSettingKey.java | 6 +- .../repository/UserSettingRepository.java | 8 + .../booklore/service/TelemetryService.java | 5 +- .../hardcover/HardcoverSyncService.java | 147 ++++++++++-- .../HardcoverSyncSettingsService.java | 122 ++++++++++ .../service/kobo/KoboSettingsService.java | 26 ++- .../service/koreader/KoreaderService.java | 15 ++ .../booklore/service/KoreaderServiceTest.java | 15 ++ .../hardcover/HardcoverSyncServiceTest.java | 120 ++++++++-- .../HardcoverSyncSettingsServiceTest.java | 98 ++++++++ .../service/kobo/KoboSettingsServiceTest.java | 3 + .../hardcover-settings-component.html | 105 +++++++++ .../hardcover-settings-component.scss | 211 ++++++++++++++++++ .../hardcover-settings-component.spec.ts | 149 +++++++++++++ .../hardcover-settings-component.ts | 132 +++++++++++ .../hardcover-sync-settings.service.spec.ts | 107 +++++++++ .../hardcover-sync-settings.service.ts | 25 +++ .../kobo-sync-settings-component.html | 76 ------- .../kobo-sync-settings-component.ts | 21 +- .../koreader-settings-component.html | 1 + .../koreader-settings-component.ts | 3 + .../device-settings-component.html | 4 + .../device-settings-component.ts | 2 + 25 files changed, 1314 insertions(+), 138 deletions(-) create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/controller/HardcoverSyncSettingsController.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/model/dto/HardcoverSyncSettings.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/repository/UserSettingRepository.java create mode 100644 booklore-api/src/main/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncSettingsService.java create mode 100644 booklore-api/src/test/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncSettingsServiceTest.java create mode 100644 booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.html create mode 100644 booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.scss create mode 100644 booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.spec.ts create mode 100644 booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.ts create mode 100644 booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-sync-settings.service.spec.ts create mode 100644 booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-sync-settings.service.ts diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/controller/HardcoverSyncSettingsController.java b/booklore-api/src/main/java/com/adityachandel/booklore/controller/HardcoverSyncSettingsController.java new file mode 100644 index 000000000..8129a5226 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/controller/HardcoverSyncSettingsController.java @@ -0,0 +1,42 @@ +package com.adityachandel.booklore.controller; + +import com.adityachandel.booklore.model.dto.HardcoverSyncSettings; +import com.adityachandel.booklore.service.hardcover.HardcoverSyncSettingsService; +import io.swagger.v3.oas.annotations.Operation; +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.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +@RestController +@RequestMapping("/api/v1/hardcover-sync-settings") +@RequiredArgsConstructor +@Tag(name = "Hardcover Sync Settings", description = "Endpoints for managing Hardcover progress sync settings") +public class HardcoverSyncSettingsController { + + private final HardcoverSyncSettingsService hardcoverSyncSettingsService; + + @Operation(summary = "Get Hardcover sync settings", description = "Retrieve the current user's Hardcover sync settings.") + @ApiResponse(responseCode = "200", description = "Settings returned successfully") + @GetMapping + @PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.canSyncKoReader() or @securityUtil.isAdmin()") + public ResponseEntity getSettings() { + HardcoverSyncSettings settings = hardcoverSyncSettingsService.getCurrentUserSettings(); + return ResponseEntity.ok(settings); + } + + @Operation(summary = "Update Hardcover sync settings", description = "Update the current user's Hardcover sync settings.") + @ApiResponse(responseCode = "200", description = "Settings updated successfully") + @PutMapping + @PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.canSyncKoReader() or @securityUtil.isAdmin()") + public ResponseEntity updateSettings(@RequestBody HardcoverSyncSettings settings) { + HardcoverSyncSettings updated = hardcoverSyncSettingsService.updateCurrentUserSettings(settings); + return ResponseEntity.ok(updated); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/HardcoverSyncSettings.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/HardcoverSyncSettings.java new file mode 100644 index 000000000..a0bfd8ed1 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/HardcoverSyncSettings.java @@ -0,0 +1,9 @@ +package com.adityachandel.booklore.model.dto; + +import lombok.Data; + +@Data +public class HardcoverSyncSettings { + private String hardcoverApiKey; + private boolean hardcoverSyncEnabled; +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/UserSettingKey.java b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/UserSettingKey.java index b051f1504..6ce1feed5 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/UserSettingKey.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/model/dto/settings/UserSettingKey.java @@ -18,7 +18,9 @@ public enum UserSettingKey { FILTER_MODE("filterMode", false), FILTER_SORTING_MODE("filterSortingMode", false), METADATA_CENTER_VIEW_MODE("metadataCenterViewMode", false), - ENABLE_SERIES_VIEW("enableSeriesView", false); + ENABLE_SERIES_VIEW("enableSeriesView", false), + HARDCOVER_API_KEY("hardcoverApiKey", false), + HARDCOVER_SYNC_ENABLED("hardcoverSyncEnabled", false); private final String dbKey; @@ -42,4 +44,4 @@ public enum UserSettingKey { } throw new IllegalArgumentException("Unknown setting key: " + dbKey); } -} \ No newline at end of file +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserSettingRepository.java b/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserSettingRepository.java new file mode 100644 index 000000000..3794a4f6f --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/repository/UserSettingRepository.java @@ -0,0 +1,8 @@ +package com.adityachandel.booklore.repository; + +import com.adityachandel.booklore.model.entity.UserSettingEntity; +import org.springframework.data.jpa.repository.JpaRepository; + +public interface UserSettingRepository extends JpaRepository { + long countBySettingKeyAndSettingValue(String settingKey, String settingValue); +} 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 3d56df255..1105def45 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 @@ -6,6 +6,7 @@ import com.adityachandel.booklore.model.dto.InstallationPing; import com.adityachandel.booklore.model.dto.settings.AppSettings; import com.adityachandel.booklore.model.dto.settings.MetadataProviderSettings; import com.adityachandel.booklore.model.dto.settings.MetadataPublicReviewsSettings; +import com.adityachandel.booklore.model.dto.settings.UserSettingKey; import com.adityachandel.booklore.model.entity.LibraryEntity; import com.adityachandel.booklore.model.enums.BookFileType; import com.adityachandel.booklore.model.enums.MetadataProvider; @@ -42,6 +43,7 @@ public class TelemetryService { private final EmailRecipientV2Repository emailRecipientV2Repository; private final AppSettingService appSettingService; private final KoboUserSettingsRepository koboUserSettingsRepository; + private final UserSettingRepository userSettingRepository; private final KoreaderUserRepository koreaderUserRepository; private final OpdsUserV2Repository opdsUserV2Repository; private final InstallationService installationService; @@ -121,7 +123,8 @@ public class TelemetryService { .koboStatistics(BookloreTelemetry.KoboStatistics.builder() .convertToKepubEnabled(settings.getKoboSettings().isConvertToKepub()) .totalKoboUsers((int) koboUserSettingsRepository.count()) - .totalHardcoverSyncEnabled((int) koboUserSettingsRepository.countByHardcoverSyncEnabledTrue()) + .totalHardcoverSyncEnabled((int) userSettingRepository.countBySettingKeyAndSettingValue( + UserSettingKey.HARDCOVER_SYNC_ENABLED.getDbKey(), "true")) .totalAutoAddToShelf((int) koboUserSettingsRepository.countByAutoAddToShelfTrue()) .build()) .bookStatistics(bookStatistics) diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncService.java index 033ec3de6..e9b1f96b7 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncService.java @@ -1,14 +1,12 @@ package com.adityachandel.booklore.service.hardcover; -import com.adityachandel.booklore.model.dto.KoboSyncSettings; +import com.adityachandel.booklore.model.dto.HardcoverSyncSettings; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.repository.BookRepository; -import com.adityachandel.booklore.service.kobo.KoboSettingsService; import com.adityachandel.booklore.service.metadata.parser.hardcover.GraphQLRequest; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Lazy; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.scheduling.annotation.Async; @@ -25,7 +23,7 @@ import java.util.Map; /** * Service to sync reading progress to Hardcover. * Uses per-user Hardcover API tokens for reading progress sync. - * Each user can configure their own Hardcover API key in Kobo settings. + * Each user can configure their own Hardcover API key in their sync settings. */ @Slf4j @Service @@ -36,15 +34,15 @@ public class HardcoverSyncService { private static final int STATUS_READ = 3; private final RestClient restClient; - private final KoboSettingsService koboSettingsService; + private final HardcoverSyncSettingsService hardcoverSyncSettingsService; private final BookRepository bookRepository; // Thread-local to hold the current API token for GraphQL requests private final ThreadLocal currentApiToken = new ThreadLocal<>(); @Autowired - public HardcoverSyncService(@Lazy KoboSettingsService koboSettingsService, BookRepository bookRepository) { - this.koboSettingsService = koboSettingsService; + public HardcoverSyncService(HardcoverSyncSettingsService hardcoverSyncSettingsService, BookRepository bookRepository) { + this.hardcoverSyncSettingsService = hardcoverSyncSettingsService; this.bookRepository = bookRepository; this.restClient = RestClient.builder() .baseUrl(HARDCOVER_API_URL) @@ -65,7 +63,7 @@ public class HardcoverSyncService { public void syncProgressToHardcover(Long bookId, Float progressPercent, Long userId) { try { // Get user's Hardcover settings - KoboSyncSettings userSettings = koboSettingsService.getSettingsByUserId(userId); + HardcoverSyncSettings userSettings = hardcoverSyncSettingsService.getSettingsForUserId(userId); if (!isHardcoverSyncEnabledForUser(userSettings)) { log.trace("Hardcover sync skipped for user {}: not enabled or no API token configured", userId); @@ -102,6 +100,18 @@ public class HardcoverSyncService { hardcoverBook.bookId = metadata.getHardcoverBookId(); hardcoverBook.pages = metadata.getPageCount(); log.debug("Using stored Hardcover book ID: {}", hardcoverBook.bookId); + + if (hardcoverBook.bookId != null && (hardcoverBook.pages == null || hardcoverBook.pages <= 0 || hardcoverBook.editionId == null)) { + HardcoverBookInfo fetched = findHardcoverBookById(hardcoverBook.bookId); + if (fetched != null) { + if (hardcoverBook.editionId == null) { + hardcoverBook.editionId = fetched.editionId; + } + if ((hardcoverBook.pages == null || hardcoverBook.pages <= 0) && fetched.pages != null) { + hardcoverBook.pages = fetched.pages; + } + } + } } else { // Search by ISBN hardcoverBook = findHardcoverBook(metadata); @@ -152,7 +162,7 @@ public class HardcoverSyncService { /** * Check if Hardcover sync is enabled for a specific user. */ - private boolean isHardcoverSyncEnabledForUser(KoboSyncSettings userSettings) { + private boolean isHardcoverSyncEnabledForUser(HardcoverSyncSettings userSettings) { if (userSettings == null) { return false; } @@ -247,15 +257,17 @@ public class HardcoverSyncService { } // If no default edition, try to look up edition by ISBN - // This also gets the page count from the specific edition - if (info.bookId != null) { + if (info.bookId != null && info.editionId == null) { EditionInfo edition = findEditionByIsbn(info.bookId, isbn); if (edition != null) { info.editionId = edition.id; - // Prefer edition page count over book page count - if (edition.pages != null && edition.pages > 0) { - info.pages = edition.pages; - } + } + } + + if (info.editionId != null && (info.pages == null || info.pages <= 0)) { + EditionInfo edition = findEditionById(info.editionId); + if (edition != null && edition.pages != null && edition.pages > 0) { + info.pages = edition.pages; } } @@ -326,6 +338,111 @@ public class HardcoverSyncService { } } + private EditionInfo findEditionById(Integer editionId) { + String query = """ + query FindEditionById($editionId: Int!) { + editions(where: {id: {_eq: $editionId}}, limit: 1) { + id + pages + } + } + """; + + GraphQLRequest request = new GraphQLRequest(); + request.setQuery(query); + request.setVariables(Map.of("editionId", editionId)); + + try { + Map response = executeGraphQL(request); + if (response == null) return null; + + Map data = (Map) response.get("data"); + if (data == null) return null; + + List> editions = (List>) data.get("editions"); + if (editions == null || editions.isEmpty()) return null; + + Map edition = editions.getFirst(); + EditionInfo info = new EditionInfo(); + + Object idObj = edition.get("id"); + if (idObj instanceof Number) { + info.id = ((Number) idObj).intValue(); + } + + Object pagesObj = edition.get("pages"); + if (pagesObj instanceof Number) { + info.pages = ((Number) pagesObj).intValue(); + } + + return info.id != null ? info : null; + + } catch (Exception e) { + log.debug("Failed to find edition by ID: {}", e.getMessage()); + return null; + } + } + + private HardcoverBookInfo findHardcoverBookById(Integer bookId) { + String query = """ + query FindBookById($bookId: Int!) { + books(where: {id: {_eq: $bookId}}, limit: 1) { + id + default_edition_id + pages + } + } + """; + + GraphQLRequest request = new GraphQLRequest(); + request.setQuery(query); + request.setVariables(Map.of("bookId", bookId)); + + try { + Map response = executeGraphQL(request); + if (response == null) return null; + + Map data = (Map) response.get("data"); + if (data == null) return null; + + List> books = (List>) data.get("books"); + if (books == null || books.isEmpty()) return null; + + Map book = books.getFirst(); + HardcoverBookInfo info = new HardcoverBookInfo(); + info.bookId = bookId; + + Object defaultEditionObj = book.get("default_edition_id"); + if (defaultEditionObj instanceof Number) { + info.editionId = ((Number) defaultEditionObj).intValue(); + } else if (defaultEditionObj instanceof String) { + try { + info.editionId = Integer.parseInt((String) defaultEditionObj); + } catch (NumberFormatException e) { + // Ignore + } + } + + Object pagesObj = book.get("pages"); + if (pagesObj instanceof Number) { + info.pages = ((Number) pagesObj).intValue(); + } + + if (info.editionId != null && (info.pages == null || info.pages <= 0)) { + EditionInfo edition = findEditionById(info.editionId); + if (edition != null && edition.pages != null && edition.pages > 0) { + info.pages = edition.pages; + } + } + + return info.editionId != null || info.pages != null ? info : null; + + } catch (Exception e) { + log.debug("Failed to find Hardcover book by ID {}: {}", bookId, e.getMessage()); + return null; + } + } + /** * Insert a book into the user's library or get existing user_book_id. */ diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncSettingsService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncSettingsService.java new file mode 100644 index 000000000..3b12bce44 --- /dev/null +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncSettingsService.java @@ -0,0 +1,122 @@ +package com.adityachandel.booklore.service.hardcover; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.exception.ApiError; +import com.adityachandel.booklore.model.dto.BookLoreUser; +import com.adityachandel.booklore.model.dto.HardcoverSyncSettings; +import com.adityachandel.booklore.model.dto.settings.UserSettingKey; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.model.entity.KoboUserSettingsEntity; +import com.adityachandel.booklore.model.entity.UserSettingEntity; +import com.adityachandel.booklore.repository.KoboUserSettingsRepository; +import com.adityachandel.booklore.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Optional; + +@Service +@RequiredArgsConstructor +public class HardcoverSyncSettingsService { + + private final UserRepository userRepository; + private final AuthenticationService authenticationService; + private final KoboUserSettingsRepository koboUserSettingsRepository; + + @Transactional + public HardcoverSyncSettings getCurrentUserSettings() { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + return getSettingsForUserId(user.getId()); + } + + @Transactional + public HardcoverSyncSettings getSettingsForUserId(Long userId) { + BookLoreUserEntity user = userRepository.findById(userId) + .orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId)); + return readSettings(user, userId); + } + + @Transactional + public HardcoverSyncSettings updateCurrentUserSettings(HardcoverSyncSettings settings) { + BookLoreUser user = authenticationService.getAuthenticatedUser(); + return updateSettingsForUserId(user.getId(), settings); + } + + @Transactional + public HardcoverSyncSettings updateSettingsForUserId(Long userId, HardcoverSyncSettings settings) { + if (settings == null) { + throw ApiError.INVALID_INPUT.createException("Hardcover settings cannot be null."); + } + + BookLoreUserEntity user = userRepository.findById(userId) + .orElseThrow(() -> ApiError.USER_NOT_FOUND.createException(userId)); + + String apiKey = settings.getHardcoverApiKey(); + if (apiKey == null) { + apiKey = ""; + } else { + apiKey = apiKey.trim(); + } + upsertSetting(user, UserSettingKey.HARDCOVER_API_KEY, apiKey); + upsertSetting(user, UserSettingKey.HARDCOVER_SYNC_ENABLED, Boolean.toString(settings.isHardcoverSyncEnabled())); + + userRepository.save(user); + + HardcoverSyncSettings updated = new HardcoverSyncSettings(); + updated.setHardcoverApiKey(apiKey); + updated.setHardcoverSyncEnabled(settings.isHardcoverSyncEnabled()); + return updated; + } + + private HardcoverSyncSettings readSettings(BookLoreUserEntity user, Long userId) { + UserSettingEntity apiKeySetting = findSetting(user, UserSettingKey.HARDCOVER_API_KEY).orElse(null); + UserSettingEntity syncEnabledSetting = findSetting(user, UserSettingKey.HARDCOVER_SYNC_ENABLED).orElse(null); + + String apiKey = apiKeySetting != null ? apiKeySetting.getSettingValue() : null; + boolean syncEnabled = syncEnabledSetting != null && Boolean.parseBoolean(syncEnabledSetting.getSettingValue()); + + boolean shouldSave = false; + if (apiKeySetting == null || syncEnabledSetting == null) { + KoboUserSettingsEntity legacySettings = koboUserSettingsRepository.findByUserId(userId).orElse(null); + if (legacySettings != null) { + if (apiKeySetting == null && legacySettings.getHardcoverApiKey() != null && !legacySettings.getHardcoverApiKey().isBlank()) { + apiKey = legacySettings.getHardcoverApiKey(); + upsertSetting(user, UserSettingKey.HARDCOVER_API_KEY, apiKey); + shouldSave = true; + } + if (syncEnabledSetting == null && legacySettings.isHardcoverSyncEnabled()) { + syncEnabled = legacySettings.isHardcoverSyncEnabled(); + upsertSetting(user, UserSettingKey.HARDCOVER_SYNC_ENABLED, Boolean.toString(syncEnabled)); + shouldSave = true; + } + } + } + if (shouldSave) { + userRepository.save(user); + } + + HardcoverSyncSettings settings = new HardcoverSyncSettings(); + settings.setHardcoverApiKey(apiKey); + settings.setHardcoverSyncEnabled(syncEnabled); + return settings; + } + + private Optional findSetting(BookLoreUserEntity user, UserSettingKey key) { + return user.getSettings().stream() + .filter(setting -> key.getDbKey().equals(setting.getSettingKey())) + .findFirst(); + } + + private void upsertSetting(BookLoreUserEntity user, UserSettingKey key, String value) { + UserSettingEntity setting = findSetting(user, key) + .orElseGet(() -> { + UserSettingEntity newSetting = new UserSettingEntity(); + newSetting.setUser(user); + newSetting.setSettingKey(key.getDbKey()); + user.getSettings().add(newSetting); + return newSetting; + }); + setting.setSettingValue(value); + } +} diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboSettingsService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboSettingsService.java index 130a87228..cc6bd5b28 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboSettingsService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/kobo/KoboSettingsService.java @@ -2,6 +2,7 @@ package com.adityachandel.booklore.service.kobo; import com.adityachandel.booklore.config.security.service.AuthenticationService; import com.adityachandel.booklore.model.dto.BookLoreUser; +import com.adityachandel.booklore.model.dto.HardcoverSyncSettings; import com.adityachandel.booklore.model.dto.KoboSyncSettings; import com.adityachandel.booklore.model.dto.Shelf; import com.adityachandel.booklore.model.dto.request.ShelfCreateRequest; @@ -11,6 +12,7 @@ import com.adityachandel.booklore.model.enums.IconType; import com.adityachandel.booklore.model.enums.ShelfType; import com.adityachandel.booklore.repository.KoboUserSettingsRepository; import com.adityachandel.booklore.service.ShelfService; +import com.adityachandel.booklore.service.hardcover.HardcoverSyncSettingsService; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -25,6 +27,7 @@ public class KoboSettingsService { private final KoboUserSettingsRepository repository; private final AuthenticationService authenticationService; private final ShelfService shelfService; + private final HardcoverSyncSettingsService hardcoverSyncSettingsService; @Transactional(readOnly = true) public KoboSyncSettings getCurrentUserSettings() { @@ -82,12 +85,8 @@ public class KoboSettingsService { entity.setAutoAddToShelf(settings.isAutoAddToShelf()); - // Update Hardcover settings - entity.setHardcoverApiKey(settings.getHardcoverApiKey()); - entity.setHardcoverSyncEnabled(settings.isHardcoverSyncEnabled()); - repository.save(entity); - return mapToDto(entity); + return mapToDto(entity, hardcoverSyncSettingsService.getSettingsForUserId(user.getId())); } private KoboUserSettingsEntity initDefaultSettings(Long userId) { @@ -118,6 +117,11 @@ public class KoboSettingsService { } private KoboSyncSettings mapToDto(KoboUserSettingsEntity entity) { + HardcoverSyncSettings hardcoverSettings = hardcoverSyncSettingsService.getSettingsForUserId(entity.getUserId()); + return mapToDto(entity, hardcoverSettings); + } + + private KoboSyncSettings mapToDto(KoboUserSettingsEntity entity, HardcoverSyncSettings hardcoverSettings) { KoboSyncSettings dto = new KoboSyncSettings(); dto.setId(entity.getId()); dto.setUserId(entity.getUserId().toString()); @@ -126,14 +130,17 @@ public class KoboSettingsService { dto.setProgressMarkAsReadingThreshold(entity.getProgressMarkAsReadingThreshold()); dto.setProgressMarkAsFinishedThreshold(entity.getProgressMarkAsFinishedThreshold()); dto.setAutoAddToShelf(entity.isAutoAddToShelf()); - dto.setHardcoverApiKey(entity.getHardcoverApiKey()); - dto.setHardcoverSyncEnabled(entity.isHardcoverSyncEnabled()); + if (hardcoverSettings != null) { + dto.setHardcoverApiKey(hardcoverSettings.getHardcoverApiKey()); + dto.setHardcoverSyncEnabled(hardcoverSettings.isHardcoverSyncEnabled()); + } else { + dto.setHardcoverSyncEnabled(false); + } return dto; } /** - * Get Hardcover settings for a specific user by ID. - * Used by HardcoverSyncService to get user-specific API key. + * Get Kobo settings for a specific user by ID. */ @Transactional(readOnly = true) public KoboSyncSettings getSettingsByUserId(Long userId) { @@ -141,4 +148,5 @@ public class KoboSettingsService { .map(this::mapToDto) .orElse(null); } + } diff --git a/booklore-api/src/main/java/com/adityachandel/booklore/service/koreader/KoreaderService.java b/booklore-api/src/main/java/com/adityachandel/booklore/service/koreader/KoreaderService.java index 130dc1ab6..7b4af12e7 100644 --- a/booklore-api/src/main/java/com/adityachandel/booklore/service/koreader/KoreaderService.java +++ b/booklore-api/src/main/java/com/adityachandel/booklore/service/koreader/KoreaderService.java @@ -22,6 +22,7 @@ import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.KoreaderUserRepository; import com.adityachandel.booklore.repository.UserBookProgressRepository; import com.adityachandel.booklore.repository.UserRepository; +import com.adityachandel.booklore.service.hardcover.HardcoverSyncService; @Slf4j @AllArgsConstructor @@ -32,6 +33,7 @@ public class KoreaderService { private final BookRepository bookRepository; private final UserRepository userRepository; private final KoreaderUserRepository koreaderUserRepository; + private final HardcoverSyncService hardcoverSyncService; public ResponseEntity> authorizeUser() { KoreaderUserDetails authDetails = getAuthDetails(); @@ -76,6 +78,9 @@ public class KoreaderService { progressRepository.save(userProgress); log.info("saveProgress: saved progress='{}' percentage={} for userId={} bookHash={}", koProgress.getProgress(), koProgress.getPercentage(), authDetails.getBookLoreUserId(), bookHash); + + Float progressPercent = normalizeProgressPercent(koProgress.getPercentage()); + hardcoverSyncService.syncProgressToHardcover(book.getId(), progressPercent, authDetails.getBookLoreUserId()); } private void updateProgressData(UserBookProgressEntity userProgress, KoreaderProgress koProgress) { @@ -101,6 +106,16 @@ public class KoreaderService { } } + private Float normalizeProgressPercent(Float progress) { + if (progress == null) { + return null; + } + if (progress <= 1.0f) { + return progress * 100.0f; + } + return progress; + } + private KoreaderUserDetails getAuthDetails() { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (!(principal instanceof KoreaderUserDetails details)) { diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/KoreaderServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/KoreaderServiceTest.java index 30dae2c78..f100a90bd 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/KoreaderServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/KoreaderServiceTest.java @@ -13,6 +13,7 @@ import com.adityachandel.booklore.repository.BookRepository; import com.adityachandel.booklore.repository.UserBookProgressRepository; import com.adityachandel.booklore.repository.UserRepository; import com.adityachandel.booklore.repository.KoreaderUserRepository; +import com.adityachandel.booklore.service.hardcover.HardcoverSyncService; import com.adityachandel.booklore.service.koreader.KoreaderService; import org.junit.jupiter.api.*; import org.junit.jupiter.api.extension.ExtendWith; @@ -24,6 +25,7 @@ import org.springframework.http.ResponseEntity; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.*; +import java.lang.reflect.Method; import java.time.Instant; import java.util.Map; import java.util.Optional; @@ -40,6 +42,8 @@ class KoreaderServiceTest { UserRepository userRepo; @Mock KoreaderUserRepository koreaderUserRepo; + @Mock + HardcoverSyncService hardcoverSyncService; @InjectMocks KoreaderService service; @@ -232,4 +236,15 @@ class KoreaderServiceTest { var dto = KoreaderProgress.builder().document("h").build(); assertThrows(APIException.class, () -> service.saveProgress("h", dto)); } + + @Test + void normalizeProgressPercent_handlesNullAndRanges() throws Exception { + Method method = KoreaderService.class.getDeclaredMethod("normalizeProgressPercent", Float.class); + method.setAccessible(true); + + assertNull(method.invoke(service, new Object[]{null})); + assertEquals(50.0f, (Float) method.invoke(service, 0.5f)); + assertEquals(100.0f, (Float) method.invoke(service, 1.0f)); + assertEquals(42.0f, (Float) method.invoke(service, 42.0f)); + } } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncServiceTest.java index eeac23f93..25ef5a30b 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncServiceTest.java @@ -1,10 +1,9 @@ package com.adityachandel.booklore.service.hardcover; -import com.adityachandel.booklore.model.dto.KoboSyncSettings; +import com.adityachandel.booklore.model.dto.HardcoverSyncSettings; import com.adityachandel.booklore.model.entity.BookEntity; import com.adityachandel.booklore.model.entity.BookMetadataEntity; import com.adityachandel.booklore.repository.BookRepository; -import com.adityachandel.booklore.service.kobo.KoboSettingsService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -14,8 +13,10 @@ import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import org.springframework.web.client.RestClient; +import org.mockito.ArgumentMatchers; import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -29,7 +30,7 @@ import static org.mockito.Mockito.*; class HardcoverSyncServiceTest { @Mock - private KoboSettingsService koboSettingsService; + private HardcoverSyncSettingsService hardcoverSyncSettingsService; @Mock private BookRepository bookRepository; @@ -50,7 +51,7 @@ class HardcoverSyncServiceTest { private BookEntity testBook; private BookMetadataEntity testMetadata; - private KoboSyncSettings koboSyncSettings; + private HardcoverSyncSettings hardcoverSyncSettings; private static final Long TEST_BOOK_ID = 100L; private static final Long TEST_USER_ID = 1L; @@ -58,7 +59,7 @@ class HardcoverSyncServiceTest { @BeforeEach void setUp() throws Exception { // Create service with mocked dependencies - service = new HardcoverSyncService(koboSettingsService, bookRepository); + service = new HardcoverSyncService(hardcoverSyncSettingsService, bookRepository); // Inject our mocked restClient using reflection Field restClientField = HardcoverSyncService.class.getDeclaredField("restClient"); @@ -73,19 +74,19 @@ class HardcoverSyncServiceTest { testMetadata.setPageCount(300); testBook.setMetadata(testMetadata); - // Setup Kobo sync settings with Hardcover enabled - koboSyncSettings = new KoboSyncSettings(); - koboSyncSettings.setHardcoverSyncEnabled(true); - koboSyncSettings.setHardcoverApiKey("test-api-key"); + // Setup Hardcover sync settings + hardcoverSyncSettings = new HardcoverSyncSettings(); + hardcoverSyncSettings.setHardcoverSyncEnabled(true); + hardcoverSyncSettings.setHardcoverApiKey("test-api-key"); - when(koboSettingsService.getSettingsByUserId(TEST_USER_ID)).thenReturn(koboSyncSettings); + when(hardcoverSyncSettingsService.getSettingsForUserId(TEST_USER_ID)).thenReturn(hardcoverSyncSettings); when(bookRepository.findById(TEST_BOOK_ID)).thenReturn(Optional.of(testBook)); // Setup RestClient mock chain - handles multiple calls when(restClient.post()).thenReturn(requestBodyUriSpec); when(requestBodyUriSpec.uri(anyString())).thenReturn(requestBodySpec); when(requestBodySpec.header(anyString(), anyString())).thenReturn(requestBodySpec); - when(requestBodySpec.body(any())).thenReturn(requestBodySpec); + doReturn(requestBodySpec).when(requestBodySpec).body(ArgumentMatchers.any(Object.class)); when(requestBodySpec.retrieve()).thenReturn(responseSpec); } @@ -94,7 +95,7 @@ class HardcoverSyncServiceTest { @Test @DisplayName("Should skip sync when Hardcover sync is not enabled for user") void syncProgressToHardcover_whenHardcoverDisabled_shouldSkip() { - koboSyncSettings.setHardcoverSyncEnabled(false); + hardcoverSyncSettings.setHardcoverSyncEnabled(false); service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID); @@ -104,7 +105,7 @@ class HardcoverSyncServiceTest { @Test @DisplayName("Should skip sync when API key is missing") void syncProgressToHardcover_whenApiKeyMissing_shouldSkip() { - koboSyncSettings.setHardcoverApiKey(null); + hardcoverSyncSettings.setHardcoverApiKey(null); service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID); @@ -114,7 +115,7 @@ class HardcoverSyncServiceTest { @Test @DisplayName("Should skip sync when API key is blank") void syncProgressToHardcover_whenApiKeyBlank_shouldSkip() { - koboSyncSettings.setHardcoverApiKey(" "); + hardcoverSyncSettings.setHardcoverApiKey(" "); service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID); @@ -244,6 +245,7 @@ class HardcoverSyncServiceTest { @DisplayName("Should handle existing user_book gracefully") void syncProgressToHardcover_whenUserBookExists_shouldFindExisting() { testMetadata.setHardcoverBookId(12345); + testMetadata.setPageCount(300); // Mock: insert_user_book returns error, then find existing, then create progress when(responseSpec.body(Map.class)) @@ -261,6 +263,7 @@ class HardcoverSyncServiceTest { @DisplayName("Should update existing reading progress") void syncProgressToHardcover_whenProgressExists_shouldUpdate() { testMetadata.setHardcoverBookId(12345); + testMetadata.setPageCount(300); // Mock: insert_user_book -> find existing read -> update read when(responseSpec.body(Map.class)) @@ -296,6 +299,7 @@ class HardcoverSyncServiceTest { @DisplayName("Should handle API errors gracefully") void syncProgressToHardcover_whenApiError_shouldNotThrow() { testMetadata.setHardcoverBookId(12345); + testMetadata.setPageCount(300); when(responseSpec.body(Map.class)).thenReturn(Map.of("errors", List.of(Map.of("message", "Unauthorized")))); @@ -306,6 +310,7 @@ class HardcoverSyncServiceTest { @DisplayName("Should handle null response gracefully") void syncProgressToHardcover_whenResponseNull_shouldNotThrow() { testMetadata.setHardcoverBookId(12345); + testMetadata.setPageCount(300); when(responseSpec.body(Map.class)).thenReturn(null); @@ -315,7 +320,7 @@ class HardcoverSyncServiceTest { @Test @DisplayName("Should skip sync when user settings not found") void syncProgressToHardcover_whenUserSettingsNotFound_shouldSkip() { - when(koboSettingsService.getSettingsByUserId(TEST_USER_ID)).thenReturn(null); + when(hardcoverSyncSettingsService.getSettingsForUserId(TEST_USER_ID)).thenReturn(null); service.syncProgressToHardcover(TEST_BOOK_ID, 50.0f, TEST_USER_ID); @@ -441,4 +446,89 @@ class HardcoverSyncServiceTest { return response; } + + @Test + @DisplayName("findEditionById should return null on null response") + void findEditionById_nullResponse_shouldReturnNull() throws Exception { + when(responseSpec.body(ArgumentMatchers.>eq(Map.class))).thenReturn(null); + + Method method = HardcoverSyncService.class.getDeclaredMethod("findEditionById", Integer.class); + method.setAccessible(true); + + Object result = method.invoke(service, 123); + assertNull(result); + } + + @Test + @DisplayName("findEditionById should parse edition info when present") + void findEditionById_withData_shouldParse() throws Exception { + Map response = new HashMap<>(); + Map data = new HashMap<>(); + Map edition = new HashMap<>(); + edition.put("id", 77); + edition.put("pages", 250); + data.put("editions", List.of(edition)); + response.put("data", data); + + when(responseSpec.body(ArgumentMatchers.>eq(Map.class))).thenReturn(response); + + Method method = HardcoverSyncService.class.getDeclaredMethod("findEditionById", Integer.class); + method.setAccessible(true); + + Object result = method.invoke(service, 77); + assertNotNull(result); + assertEquals(77, readPrivateField(result, "id")); + assertEquals(250, readPrivateField(result, "pages")); + } + + @Test + @DisplayName("findHardcoverBookById should return null on empty response") + void findHardcoverBookById_emptyResponse_shouldReturnNull() throws Exception { + when(responseSpec.body(ArgumentMatchers.>eq(Map.class))) + .thenReturn(Map.of("data", Map.of("books", List.of()))); + + Method method = HardcoverSyncService.class.getDeclaredMethod("findHardcoverBookById", Integer.class); + method.setAccessible(true); + + Object result = method.invoke(service, 123); + assertNull(result); + } + + @Test + @DisplayName("findHardcoverBookById should use default edition and edition pages") + void findHardcoverBookById_withDefaultEdition_shouldUseEditionPages() throws Exception { + Map bookResponse = new HashMap<>(); + Map bookData = new HashMap<>(); + Map book = new HashMap<>(); + book.put("default_edition_id", "88"); + bookData.put("books", List.of(book)); + bookResponse.put("data", bookData); + + Map editionResponse = new HashMap<>(); + Map editionData = new HashMap<>(); + Map edition = new HashMap<>(); + edition.put("id", 88); + edition.put("pages", 320); + editionData.put("editions", List.of(edition)); + editionResponse.put("data", editionData); + + when(responseSpec.body(ArgumentMatchers.>eq(Map.class))) + .thenReturn(bookResponse) + .thenReturn(editionResponse); + + Method method = HardcoverSyncService.class.getDeclaredMethod("findHardcoverBookById", Integer.class); + method.setAccessible(true); + + Object result = method.invoke(service, 123); + assertNotNull(result); + assertEquals(123, readPrivateField(result, "bookId")); + assertEquals(88, readPrivateField(result, "editionId")); + assertEquals(320, readPrivateField(result, "pages")); + } + + private Integer readPrivateField(Object target, String fieldName) throws Exception { + Field field = target.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + return (Integer) field.get(target); + } } diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncSettingsServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncSettingsServiceTest.java new file mode 100644 index 000000000..55df61ac8 --- /dev/null +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/hardcover/HardcoverSyncSettingsServiceTest.java @@ -0,0 +1,98 @@ +package com.adityachandel.booklore.service.hardcover; + +import com.adityachandel.booklore.config.security.service.AuthenticationService; +import com.adityachandel.booklore.model.dto.HardcoverSyncSettings; +import com.adityachandel.booklore.model.dto.settings.UserSettingKey; +import com.adityachandel.booklore.model.entity.BookLoreUserEntity; +import com.adityachandel.booklore.model.entity.KoboUserSettingsEntity; +import com.adityachandel.booklore.model.entity.UserSettingEntity; +import com.adityachandel.booklore.repository.KoboUserSettingsRepository; +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.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.HashSet; +import java.util.Optional; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class HardcoverSyncSettingsServiceTest { + + @Mock + private UserRepository userRepository; + + @Mock + private AuthenticationService authenticationService; + + @Mock + private KoboUserSettingsRepository koboUserSettingsRepository; + + private HardcoverSyncSettingsService service; + + @BeforeEach + void setUp() { + service = new HardcoverSyncSettingsService(userRepository, authenticationService, koboUserSettingsRepository); + } + + @Test + @DisplayName("Should fallback to legacy Kobo settings and persist user settings") + void getSettingsForUserId_whenLegacyPresent_shouldPersistUserSettings() { + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(1L); + user.setSettings(new HashSet<>()); + + KoboUserSettingsEntity legacy = KoboUserSettingsEntity.builder() + .userId(1L) + .hardcoverApiKey("legacy-key") + .hardcoverSyncEnabled(true) + .build(); + + when(userRepository.findById(1L)).thenReturn(Optional.of(user)); + when(koboUserSettingsRepository.findByUserId(1L)).thenReturn(Optional.of(legacy)); + + HardcoverSyncSettings settings = service.getSettingsForUserId(1L); + + assertEquals("legacy-key", settings.getHardcoverApiKey()); + assertTrue(settings.isHardcoverSyncEnabled()); + assertTrue(user.getSettings().stream() + .anyMatch(setting -> UserSettingKey.HARDCOVER_API_KEY.getDbKey().equals(setting.getSettingKey()))); + assertTrue(user.getSettings().stream() + .anyMatch(setting -> UserSettingKey.HARDCOVER_SYNC_ENABLED.getDbKey().equals(setting.getSettingKey()))); + verify(userRepository).save(user); + } + + @Test + @DisplayName("Should trim API key when updating settings") + void updateSettingsForUserId_shouldTrimApiKey() { + BookLoreUserEntity user = new BookLoreUserEntity(); + user.setId(1L); + user.setSettings(new HashSet<>()); + user.getSettings().add(UserSettingEntity.builder() + .user(user) + .settingKey(UserSettingKey.HARDCOVER_API_KEY.getDbKey()) + .settingValue("old") + .build()); + + when(userRepository.findById(1L)).thenReturn(Optional.of(user)); + + HardcoverSyncSettings update = new HardcoverSyncSettings(); + update.setHardcoverApiKey(" new-key "); + update.setHardcoverSyncEnabled(false); + + HardcoverSyncSettings result = service.updateSettingsForUserId(1L, update); + + assertEquals("new-key", result.getHardcoverApiKey()); + assertTrue(user.getSettings().stream() + .anyMatch(setting -> UserSettingKey.HARDCOVER_API_KEY.getDbKey().equals(setting.getSettingKey()) + && "new-key".equals(setting.getSettingValue()))); + verify(userRepository).save(user); + } +} diff --git a/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboSettingsServiceTest.java b/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboSettingsServiceTest.java index acf2d862b..6176e9bcf 100644 --- a/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboSettingsServiceTest.java +++ b/booklore-api/src/test/java/com/adityachandel/booklore/service/kobo/KoboSettingsServiceTest.java @@ -10,6 +10,7 @@ import com.adityachandel.booklore.model.entity.ShelfEntity; import com.adityachandel.booklore.model.enums.ShelfType; import com.adityachandel.booklore.repository.KoboUserSettingsRepository; import com.adityachandel.booklore.service.ShelfService; +import com.adityachandel.booklore.service.hardcover.HardcoverSyncSettingsService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -30,6 +31,8 @@ class KoboSettingsServiceTest { private AuthenticationService authenticationService; @Mock private ShelfService shelfService; + @Mock + private HardcoverSyncSettingsService hardcoverSyncSettingsService; @InjectMocks private KoboSettingsService service; diff --git a/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.html b/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.html new file mode 100644 index 000000000..254a4b444 --- /dev/null +++ b/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.html @@ -0,0 +1,105 @@ + + +
+
+

+ + Hardcover Integration + +

+

+ Sync your reading progress from Booklore to your Hardcover account. +

+
+ + @if (hasPermission) { +
+
+
+

+ + Sync Configuration +

+

+ Enable and configure synchronization between Booklore and Hardcover. +

+
+ +
+
+
+
+ + + +
+

+ When enabled, your reading progress will be automatically synced to your Hardcover account. +

+
+
+ + @if (hardcoverSyncEnabled) { +
+
+
+ +
+ + + + + +
+
+

+ Your personal Hardcover API key. Get it from + hardcover.app/account/api. + This key is used only for syncing your reading progress and is not shared with other users. +

+
+
+ } +
+
+
+ } @else { +
+
+ +
+

Access Restricted

+

+ Access to Hardcover sync is restricted. +
+ Please contact your administrator to request permission. +

+
+
+
+ } +
diff --git a/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.scss b/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.scss new file mode 100644 index 000000000..82c6385eb --- /dev/null +++ b/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.scss @@ -0,0 +1,211 @@ +.main-container { + width: 100%; + padding: 1rem; + overflow-y: auto; +} + +.enclosing-container { + border-color: var(--p-content-border-color); + background: var(--p-content-background); +} + +.settings-header { + margin-top: 1rem; + margin-bottom: 2rem; +} + +.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: 1rem; +} + +.settings-content { + display: flex; + flex-direction: column; + gap: 2rem; + + @media (max-width: 768px) { + padding-left: 0; + } +} + +.preferences-section { + @media (max-width: 768px) { + padding: 0; + } +} + +.section-header { + margin-bottom: 1rem; + margin-left: 1rem; + margin-right: 1rem; +} + +.section-title { + display: flex; + align-items: center; + gap: 0.5rem; + font-size: 1.125rem; + font-weight: 600; + color: var(--p-text-color); + margin: 0 0 0.5rem 0; + + .pi { + color: var(--p-primary-color); + } +} + +.section-description { + 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: 1rem 1.5rem 1.5rem 1.5rem; + margin-left: 1rem; + margin-right: 1rem; + display: flex; + flex-direction: column; + gap: 2rem; + + @media (max-width: 768px) { + padding: 1rem; + margin-left: 0; + margin-right: 0; + } +} + +.setting-item { + display: flex; + align-items: flex-start; + gap: 2rem; + padding: 0.5rem 0; + + &:last-child { + border-bottom: none; + padding-bottom: 0; + } + + @media (max-width: 768px) { + flex-direction: column; + gap: 1rem; + padding: 0.5rem 0; + } +} + +.setting-info { + flex: 1; + min-width: 0; + + .setting-label { + display: block; + font-weight: 600; + color: var(--p-text-color); + font-size: 1rem; + margin-bottom: 0.5rem; + } + + .setting-label-row { + display: flex; + align-items: center; + gap: 1rem; + margin-bottom: 0.5rem; + flex-wrap: wrap; + + .setting-label { + margin-bottom: 0; + flex-shrink: 0; + min-width: 150px; + } + + .token-input-group { + flex: 1; + min-width: 300px; + max-width: 500px; + + @media (max-width: 768px) { + min-width: 250px; + max-width: 100%; + } + } + } + + .setting-description { + color: var(--p-text-muted-color); + font-size: 0.875rem; + line-height: 1.5; + margin: 0; + } +} + +.token-input-group { + display: flex; + align-items: center; + gap: 0.75rem; + width: 100%; + + .token-input { + flex: 1; + min-width: 200px; + + @media (max-width: 768px) { + min-width: 150px; + } + } +} + +.access-denied-card { + display: flex; + align-items: center; + gap: 1rem; + border: 1px solid var(--p-content-border-color); + border-radius: 8px; + padding: 1rem; + background: var(--p-content-background); + margin: 0 1rem; + + @media (max-width: 768px) { + margin: 0; + } + + .pi { + font-size: 1.5rem; + color: var(--p-text-muted-color); + } +} + +.access-denied-content { + h3 { + margin: 0 0 0.25rem 0; + font-size: 1rem; + color: var(--p-text-color); + } + + p { + margin: 0; + color: var(--p-text-muted-color); + font-size: 0.875rem; + } +} diff --git a/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.spec.ts b/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.spec.ts new file mode 100644 index 000000000..6dbe4eff8 --- /dev/null +++ b/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.spec.ts @@ -0,0 +1,149 @@ +import {beforeEach, describe, expect, it, vi} from 'vitest'; +import {ComponentFixture, TestBed} from '@angular/core/testing'; +import {BehaviorSubject, of, throwError} from 'rxjs'; +import {MessageService} from 'primeng/api'; +import {NO_ERRORS_SCHEMA} from '@angular/core'; +import {HardcoverSettingsComponent} from './hardcover-settings-component'; +import {HardcoverSyncSettingsService} from './hardcover-sync-settings.service'; +import {UserService, UserState} from '../../../user-management/user.service'; + +describe('HardcoverSettingsComponent', () => { + let fixture: ComponentFixture; + let component: HardcoverSettingsComponent; + let settingsServiceMock: any; + let messageServiceMock: any; + let userState$: BehaviorSubject; + + const makeState = (permissions: Partial = {}): UserState => ({ + loaded: true, + error: null, + user: { + id: 1, + username: 'u', + name: 'User', + email: 'u@example.com', + assignedLibraries: [], + provisioningMethod: 'LOCAL', + 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: {} as any, + ...permissions + } + }); + + beforeEach(async () => { + settingsServiceMock = { + getSettings: vi.fn(), + updateSettings: vi.fn() + }; + messageServiceMock = { + add: vi.fn() + }; + userState$ = new BehaviorSubject(makeState()); + + await TestBed.configureTestingModule({ + imports: [HardcoverSettingsComponent], + providers: [ + {provide: HardcoverSyncSettingsService, useValue: settingsServiceMock}, + {provide: MessageService, useValue: messageServiceMock}, + {provide: UserService, useValue: {userState$: userState$}} + ], + schemas: [NO_ERRORS_SCHEMA] + }).compileComponents(); + + fixture = TestBed.createComponent(HardcoverSettingsComponent); + component = fixture.componentInstance; + }); + + it('should load settings when user has permission', () => { + settingsServiceMock.getSettings.mockReturnValue(of({hardcoverSyncEnabled: true, hardcoverApiKey: 'key'})); + userState$.next(makeState({ + permissions: { + ...makeState().user!.permissions, + canSyncKobo: true + } + }) as UserState); + + fixture.detectChanges(); + + expect(settingsServiceMock.getSettings).toHaveBeenCalled(); + expect(component.hardcoverSyncEnabled).toBe(true); + expect(component.hardcoverApiKey).toBe('key'); + }); + + it('should not load settings without permission', () => { + settingsServiceMock.getSettings.mockReturnValue(of({})); + userState$.next(makeState()); + fixture.detectChanges(); + expect(settingsServiceMock.getSettings).not.toHaveBeenCalled(); + }); + + it('should update settings on toggle', () => { + settingsServiceMock.updateSettings.mockReturnValue(of({hardcoverSyncEnabled: false, hardcoverApiKey: 'k'})); + component.hardcoverSyncEnabled = false; + component.hardcoverApiKey = 'k'; + + component.onHardcoverSyncToggle(); + + expect(settingsServiceMock.updateSettings).toHaveBeenCalledWith({ + hardcoverSyncEnabled: false, + hardcoverApiKey: 'k' + }); + expect(messageServiceMock.add).toHaveBeenCalled(); + }); + + it('should handle update error', () => { + settingsServiceMock.updateSettings.mockReturnValue(throwError(() => new Error('fail'))); + component.hardcoverSyncEnabled = true; + component.hardcoverApiKey = 'k'; + + component.onHardcoverApiKeyChange(); + + expect(settingsServiceMock.updateSettings).toHaveBeenCalled(); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'error' + })); + }); + + it('should handle load error', () => { + settingsServiceMock.getSettings.mockReturnValue(throwError(() => new Error('fail'))); + userState$.next(makeState({ + permissions: { + ...makeState().user!.permissions, + admin: true + } + }) as UserState); + + fixture.detectChanges(); + + expect(settingsServiceMock.getSettings).toHaveBeenCalled(); + expect(messageServiceMock.add).toHaveBeenCalledWith(expect.objectContaining({ + severity: 'error' + })); + }); +}); diff --git a/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.ts b/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.ts new file mode 100644 index 000000000..14b7b0683 --- /dev/null +++ b/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-settings-component.ts @@ -0,0 +1,132 @@ +import {Component, inject, OnDestroy, OnInit} from '@angular/core'; +import {FormsModule} from '@angular/forms'; +import {InputText} from 'primeng/inputtext'; +import {ToggleSwitch} from 'primeng/toggleswitch'; +import {Button} from 'primeng/button'; +import {ToastModule} from 'primeng/toast'; +import {MessageService} from 'primeng/api'; +import {Subject} from 'rxjs'; +import {filter, takeUntil} from 'rxjs/operators'; +import {ExternalDocLinkComponent} from '../../../../../shared/components/external-doc-link/external-doc-link.component'; +import {UserService} from '../../../user-management/user.service'; +import {HardcoverSyncSettingsService} from './hardcover-sync-settings.service'; + +@Component({ + standalone: true, + selector: 'app-hardcover-settings-component', + imports: [ + FormsModule, + InputText, + ToggleSwitch, + Button, + ToastModule, + ExternalDocLinkComponent + ], + providers: [MessageService], + templateUrl: './hardcover-settings-component.html', + styleUrls: ['./hardcover-settings-component.scss'] +}) +export class HardcoverSettingsComponent implements OnInit, OnDestroy { + private readonly messageService = inject(MessageService); + private readonly hardcoverSyncSettingsService = inject(HardcoverSyncSettingsService); + private readonly userService = inject(UserService); + private readonly destroy$ = new Subject(); + + hasPermission = false; + hardcoverSyncEnabled = false; + hardcoverApiKey = ''; + showHardcoverApiKey = false; + + ngOnInit() { + let prevHasPermission = false; + this.userService.userState$.pipe( + filter(userState => !!userState?.user && userState.loaded), + takeUntil(this.destroy$) + ).subscribe(userState => { + const currHasPermission = (userState.user?.permissions.canSyncKoReader + || userState.user?.permissions.canSyncKobo + || userState.user?.permissions.admin) ?? false; + this.hasPermission = currHasPermission; + if (currHasPermission && !prevHasPermission) { + this.loadHardcoverSettings(); + } + prevHasPermission = currHasPermission; + }); + } + + private loadHardcoverSettings() { + this.hardcoverSyncSettingsService.getSettings().subscribe({ + next: settings => { + this.hardcoverSyncEnabled = settings.hardcoverSyncEnabled ?? false; + this.hardcoverApiKey = settings.hardcoverApiKey ?? ''; + }, + error: () => { + this.messageService.add({ + severity: 'error', + summary: 'Load Error', + detail: 'Unable to retrieve Hardcover sync settings. Please try again.' + }); + } + }); + } + + toggleShowHardcoverApiKey() { + this.showHardcoverApiKey = !this.showHardcoverApiKey; + } + + onHardcoverSyncToggle() { + const message = this.hardcoverSyncEnabled + ? 'Hardcover sync enabled' + : 'Hardcover sync disabled'; + this.updateHardcoverSettings(message); + } + + onHardcoverApiKeyChange() { + this.updateHardcoverSettings('Hardcover API key updated'); + } + + private updateHardcoverSettings(successMessage: string) { + this.hardcoverSyncSettingsService.updateSettings({ + hardcoverSyncEnabled: this.hardcoverSyncEnabled, + hardcoverApiKey: this.hardcoverApiKey + }).subscribe({ + next: settings => { + this.hardcoverSyncEnabled = settings.hardcoverSyncEnabled ?? false; + this.hardcoverApiKey = settings.hardcoverApiKey ?? ''; + this.messageService.add({severity: 'success', summary: 'Settings Updated', detail: successMessage}); + }, + error: () => { + this.messageService.add({ + severity: 'error', + summary: 'Update Failed', + detail: 'Unable to update Hardcover sync settings. Please try again.' + }); + } + }); + } + + copyText(text: string, label: string = 'Text') { + if (!text) { + return; + } + navigator.clipboard.writeText(text).then(() => { + this.messageService.add({ + severity: 'success', + summary: 'Copied', + detail: `${label} copied to clipboard` + }); + }).catch(err => { + console.error('Copy failed', err); + this.messageService.add({ + severity: 'error', + summary: 'Copy Failed', + detail: `Unable to copy ${label.toLowerCase()} to clipboard` + }); + }); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); + } +} diff --git a/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-sync-settings.service.spec.ts b/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-sync-settings.service.spec.ts new file mode 100644 index 000000000..62bc92474 --- /dev/null +++ b/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-sync-settings.service.spec.ts @@ -0,0 +1,107 @@ +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 {HardcoverSyncSettingsService, HardcoverSyncSettings} from './hardcover-sync-settings.service'; + +describe('HardcoverSyncSettingsService', () => { + let service: HardcoverSyncSettingsService; + let httpClientMock: any; + + const mockSettings: HardcoverSyncSettings = { + hardcoverApiKey: 'hardcover-key', + hardcoverSyncEnabled: true + }; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + put: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + HardcoverSyncSettingsService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(HardcoverSyncSettingsService)); + }); + + it('should get Hardcover sync settings', () => { + httpClientMock.get.mockReturnValue(of(mockSettings)); + service.getSettings().subscribe(settings => { + expect(settings).toEqual(mockSettings); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringContaining('/api/v1/hardcover-sync-settings')); + }); + }); + + it('should update Hardcover sync settings', () => { + httpClientMock.put.mockReturnValue(of(mockSettings)); + service.updateSettings(mockSettings).subscribe(settings => { + expect(settings).toEqual(mockSettings); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringContaining('/api/v1/hardcover-sync-settings'), mockSettings); + }); + }); + + it('should handle getSettings error', () => { + httpClientMock.get.mockReturnValue(throwError(() => new Error('fail'))); + service.getSettings().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('HardcoverSyncSettingsService - API Contract Tests', () => { + let service: HardcoverSyncSettingsService; + let httpClientMock: any; + + beforeEach(() => { + httpClientMock = { + get: vi.fn(), + put: vi.fn() + }; + + TestBed.configureTestingModule({ + providers: [ + HardcoverSyncSettingsService, + {provide: HttpClient, useValue: httpClientMock} + ] + }); + + const injector = TestBed.inject(EnvironmentInjector); + service = runInInjectionContext(injector, () => TestBed.inject(HardcoverSyncSettingsService)); + }); + + it('should call correct endpoint for getSettings', () => { + httpClientMock.get.mockReturnValue(of({})); + service.getSettings().subscribe(); + expect(httpClientMock.get).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/hardcover-sync-settings$/)); + }); + + it('should call correct endpoint for updateSettings', () => { + httpClientMock.put.mockReturnValue(of({})); + const settings: HardcoverSyncSettings = { + hardcoverApiKey: 'key', + hardcoverSyncEnabled: false + }; + service.updateSettings(settings).subscribe(); + expect(httpClientMock.put).toHaveBeenCalledWith(expect.stringMatching(/\/api\/v1\/hardcover-sync-settings$/), settings); + }); +}); diff --git a/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-sync-settings.service.ts b/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-sync-settings.service.ts new file mode 100644 index 000000000..a937644c3 --- /dev/null +++ b/booklore-ui/src/app/features/settings/device-settings/component/hardcover-settings/hardcover-sync-settings.service.ts @@ -0,0 +1,25 @@ +import {inject, Injectable} from '@angular/core'; +import {HttpClient} from '@angular/common/http'; +import {Observable} from 'rxjs'; +import {API_CONFIG} from '../../../../../core/config/api-config'; + +export interface HardcoverSyncSettings { + hardcoverApiKey?: string; + hardcoverSyncEnabled?: boolean; +} + +@Injectable({ + providedIn: 'root' +}) +export class HardcoverSyncSettingsService { + private readonly http = inject(HttpClient); + private readonly baseUrl = `${API_CONFIG.BASE_URL}/api/v1/hardcover-sync-settings`; + + getSettings(): Observable { + return this.http.get(this.baseUrl); + } + + updateSettings(settings: HardcoverSyncSettings): Observable { + return this.http.put(this.baseUrl, settings); + } +} diff --git a/booklore-ui/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.html b/booklore-ui/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.html index 1a80d4007..134a73282 100644 --- a/booklore-ui/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.html +++ b/booklore-ui/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.html @@ -174,82 +174,6 @@ - @if (koboSyncSettings.syncEnabled) { -
-
-

- - Hardcover Integration -

-

- Sync your Kobo reading progress to your personal Hardcover account. -

-
- -
-
-
-
- - - -
-

- When enabled, your reading progress from Kobo will be automatically synced to your Hardcover account. - Each user can configure their own Hardcover account. -

-
-
- - @if (koboSyncSettings.hardcoverSyncEnabled) { -
-
-
- -
- - - - - -
-
-

- Your personal Hardcover API key. Get it from - hardcover.app/account/api. - This key is used only for syncing your reading progress and is not shared with other users. -

-
-
- } -
-
- } - @if (isAdmin) {
diff --git a/booklore-ui/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.ts b/booklore-ui/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.ts index 0dac94b4d..334eebc85 100644 --- a/booklore-ui/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.ts +++ b/booklore-ui/src/app/features/settings/device-settings/component/kobo-sync-settings/kobo-sync-settings-component.ts @@ -43,7 +43,6 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy { isAdmin = false; credentialsSaved = false; showToken = false; - showHardcoverApiKey = false; koboSettings: KoboSettings = { convertToKepub: false, @@ -59,9 +58,7 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy { syncEnabled: false, progressMarkAsReadingThreshold: 1, progressMarkAsFinishedThreshold: 99, - autoAddToShelf: true, - hardcoverApiKey: '', - hardcoverSyncEnabled: false + autoAddToShelf: true } ngOnInit() { @@ -122,8 +119,6 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy { this.koboSyncSettings.progressMarkAsReadingThreshold = settings.progressMarkAsReadingThreshold ?? 1; this.koboSyncSettings.progressMarkAsFinishedThreshold = settings.progressMarkAsFinishedThreshold ?? 99; this.koboSyncSettings.autoAddToShelf = settings.autoAddToShelf ?? false; - this.koboSyncSettings.hardcoverApiKey = settings.hardcoverApiKey ?? ''; - this.koboSyncSettings.hardcoverSyncEnabled = settings.hardcoverSyncEnabled ?? false; this.credentialsSaved = !!settings.token; }, error: () => { @@ -172,20 +167,6 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy { this.showToken = !this.showToken; } - toggleShowHardcoverApiKey() { - this.showHardcoverApiKey = !this.showHardcoverApiKey; - } - - onHardcoverSyncToggle() { - const message = this.koboSyncSettings.hardcoverSyncEnabled - ? 'Hardcover sync enabled' - : 'Hardcover sync disabled'; - this.updateKoboSettings(message); - } - - onHardcoverApiKeyChange() { - this.updateKoboSettings('Hardcover API key updated'); - } confirmRegenerateToken() { this.confirmationService.confirm({ diff --git a/booklore-ui/src/app/features/settings/device-settings/component/koreader-settings/koreader-settings-component.html b/booklore-ui/src/app/features/settings/device-settings/component/koreader-settings/koreader-settings-component.html index 5842f46be..cfd31ec0d 100644 --- a/booklore-ui/src/app/features/settings/device-settings/component/koreader-settings/koreader-settings-component.html +++ b/booklore-ui/src/app/features/settings/device-settings/component/koreader-settings/koreader-settings-component.html @@ -176,6 +176,7 @@
+ } @else {
diff --git a/booklore-ui/src/app/features/settings/device-settings/component/koreader-settings/koreader-settings-component.ts b/booklore-ui/src/app/features/settings/device-settings/component/koreader-settings/koreader-settings-component.ts index d902d02ac..080b84744 100644 --- a/booklore-ui/src/app/features/settings/device-settings/component/koreader-settings/koreader-settings-component.ts +++ b/booklore-ui/src/app/features/settings/device-settings/component/koreader-settings/koreader-settings-component.ts @@ -78,6 +78,7 @@ export class KoreaderSettingsComponent implements OnInit, OnDestroy { }); } + get canSave(): boolean { const u = this.koReaderUsername?.trim() ?? ''; const p = this.koReaderPassword ?? ''; @@ -107,6 +108,7 @@ export class KoreaderSettingsComponent implements OnInit, OnDestroy { this.showPassword = !this.showPassword; } + saveCredentials() { this.koreaderService.createUser(this.koReaderUsername, this.koReaderPassword) .subscribe({ @@ -119,6 +121,7 @@ export class KoreaderSettingsComponent implements OnInit, OnDestroy { }); } + copyText(text: string, label: string = 'Text') { if (!text) { return; diff --git a/booklore-ui/src/app/features/settings/device-settings/device-settings-component.html b/booklore-ui/src/app/features/settings/device-settings/device-settings-component.html index f1dd2b616..554ea7f3b 100644 --- a/booklore-ui/src/app/features/settings/device-settings/device-settings-component.html +++ b/booklore-ui/src/app/features/settings/device-settings/device-settings-component.html @@ -3,6 +3,10 @@
+
+ +
+
diff --git a/booklore-ui/src/app/features/settings/device-settings/device-settings-component.ts b/booklore-ui/src/app/features/settings/device-settings/device-settings-component.ts index 5767f27bb..7a496722e 100644 --- a/booklore-ui/src/app/features/settings/device-settings/device-settings-component.ts +++ b/booklore-ui/src/app/features/settings/device-settings/device-settings-component.ts @@ -2,12 +2,14 @@ import {Component} from '@angular/core'; import {Divider} from 'primeng/divider'; import {KoreaderSettingsComponent} from './component/koreader-settings/koreader-settings-component'; import {KoboSyncSettingsComponent} from './component/kobo-sync-settings/kobo-sync-settings-component'; +import {HardcoverSettingsComponent} from './component/hardcover-settings/hardcover-settings-component'; @Component({ selector: 'app-device-settings-component', imports: [ KoreaderSettingsComponent, KoboSyncSettingsComponent, + HardcoverSettingsComponent, Divider ], templateUrl: './device-settings-component.html',