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 <akiraslingshot@gmail.com>
Co-authored-by: ACX <8075870+acx10@users.noreply.github.com>
This commit is contained in:
Giancarlo Perrone
2026-01-08 16:14:51 -07:00
committed by GitHub
co-authored by akiraslingshot ACX
parent 20ed3e5b25
commit 77bb2904e3
25 changed files with 1314 additions and 138 deletions
@@ -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<HardcoverSyncSettings> 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<HardcoverSyncSettings> updateSettings(@RequestBody HardcoverSyncSettings settings) {
HardcoverSyncSettings updated = hardcoverSyncSettingsService.updateCurrentUserSettings(settings);
return ResponseEntity.ok(updated);
}
}
@@ -0,0 +1,9 @@
package com.adityachandel.booklore.model.dto;
import lombok.Data;
@Data
public class HardcoverSyncSettings {
private String hardcoverApiKey;
private boolean hardcoverSyncEnabled;
}
@@ -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);
}
}
}
@@ -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<UserSettingEntity, Long> {
long countBySettingKeyAndSettingValue(String settingKey, String settingValue);
}
@@ -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)
@@ -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<String> 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<String, Object> response = executeGraphQL(request);
if (response == null) return null;
Map<String, Object> data = (Map<String, Object>) response.get("data");
if (data == null) return null;
List<Map<String, Object>> editions = (List<Map<String, Object>>) data.get("editions");
if (editions == null || editions.isEmpty()) return null;
Map<String, Object> 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<String, Object> response = executeGraphQL(request);
if (response == null) return null;
Map<String, Object> data = (Map<String, Object>) response.get("data");
if (data == null) return null;
List<Map<String, Object>> books = (List<Map<String, Object>>) data.get("books");
if (books == null || books.isEmpty()) return null;
Map<String, Object> 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.
*/
@@ -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<UserSettingEntity> 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);
}
}
@@ -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);
}
}
@@ -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<Map<String, String>> 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)) {
@@ -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));
}
}
@@ -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.<Class<Map>>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<String, Object> response = new HashMap<>();
Map<String, Object> data = new HashMap<>();
Map<String, Object> 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.<Class<Map>>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.<Class<Map>>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<String, Object> bookResponse = new HashMap<>();
Map<String, Object> bookData = new HashMap<>();
Map<String, Object> book = new HashMap<>();
book.put("default_edition_id", "88");
bookData.put("books", List.of(book));
bookResponse.put("data", bookData);
Map<String, Object> editionResponse = new HashMap<>();
Map<String, Object> editionData = new HashMap<>();
Map<String, Object> 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.<Class<Map>>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);
}
}
@@ -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);
}
}
@@ -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;
@@ -0,0 +1,105 @@
<p-toast position="top-right"></p-toast>
<div class="main-container enclosing-container">
<div class="settings-header">
<h2 class="settings-title">
<i class="pi pi-book"></i>
Hardcover Integration
<app-external-doc-link docType="hardcover"></app-external-doc-link>
</h2>
<p class="settings-description">
Sync your reading progress from Booklore to your Hardcover account.
</p>
</div>
@if (hasPermission) {
<div class="settings-content">
<div class="preferences-section">
<div class="section-header">
<h3 class="section-title">
<i class="pi pi-sync"></i>
Sync Configuration
</h3>
<p class="section-description">
Enable and configure synchronization between Booklore and Hardcover.
</p>
</div>
<div class="settings-card">
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Sync Reading Progress to Hardcover</label>
<p-toggle-switch
id="hardcoverSyncEnabled"
name="hardcoverSyncEnabled"
[(ngModel)]="hardcoverSyncEnabled"
(ngModelChange)="onHardcoverSyncToggle()">
</p-toggle-switch>
</div>
<p class="setting-description">
When enabled, your reading progress will be automatically synced to your Hardcover account.
</p>
</div>
</div>
@if (hardcoverSyncEnabled) {
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Hardcover API Key</label>
<div class="token-input-group">
<input
pInputText
id="hardcoverApiKey"
[(ngModel)]="hardcoverApiKey"
[type]="showHardcoverApiKey ? 'text' : 'password'"
name="hardcoverApiKey"
class="token-input"
placeholder="Enter your Hardcover API key"
(blur)="onHardcoverApiKeyChange()"
/>
<p-button
icon="pi pi-copy"
outlined="true"
severity="info"
size="small"
(onClick)="copyText(hardcoverApiKey, 'API Key')"
[disabled]="!hardcoverApiKey">
</p-button>
<p-button
[icon]="showHardcoverApiKey ? 'pi pi-eye-slash' : 'pi pi-eye'"
outlined="true"
severity="info"
size="small"
(onClick)="toggleShowHardcoverApiKey()">
</p-button>
</div>
</div>
<p class="setting-description">
Your personal Hardcover API key. Get it from
<a href="https://hardcover.app/account/api" target="_blank" rel="noopener">hardcover.app/account/api</a>.
This key is used only for syncing your reading progress and is not shared with other users.
</p>
</div>
</div>
}
</div>
</div>
</div>
} @else {
<div class="settings-content">
<div class="access-denied-card">
<i class="pi pi-lock"></i>
<div class="access-denied-content">
<h3>Access Restricted</h3>
<p>
Access to Hardcover sync is restricted.
<br>
Please contact your administrator to request permission.
</p>
</div>
</div>
</div>
}
</div>
@@ -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;
}
}
@@ -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<HardcoverSettingsComponent>;
let component: HardcoverSettingsComponent;
let settingsServiceMock: any;
let messageServiceMock: any;
let userState$: BehaviorSubject<UserState>;
const makeState = (permissions: Partial<UserState['user']> = {}): 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<UserState>(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'
}));
});
});
@@ -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<void>();
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();
}
}
@@ -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);
});
});
@@ -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<HardcoverSyncSettings> {
return this.http.get<HardcoverSyncSettings>(this.baseUrl);
}
updateSettings(settings: HardcoverSyncSettings): Observable<HardcoverSyncSettings> {
return this.http.put<HardcoverSyncSettings>(this.baseUrl, settings);
}
}
@@ -174,82 +174,6 @@
</div>
</div>
@if (koboSyncSettings.syncEnabled) {
<div class="preferences-section">
<div class="section-header">
<h3 class="section-title">
<i class="pi pi-book"></i>
Hardcover Integration
</h3>
<p class="section-description">
Sync your Kobo reading progress to your personal Hardcover account.
</p>
</div>
<div class="settings-card">
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Sync Reading Progress to Hardcover</label>
<p-toggle-switch
id="hardcoverSyncEnabled"
name="hardcoverSyncEnabled"
[(ngModel)]="koboSyncSettings.hardcoverSyncEnabled"
(ngModelChange)="onHardcoverSyncToggle()">
</p-toggle-switch>
</div>
<p class="setting-description">
When enabled, your reading progress from Kobo will be automatically synced to your Hardcover account.
Each user can configure their own Hardcover account.
</p>
</div>
</div>
@if (koboSyncSettings.hardcoverSyncEnabled) {
<div class="setting-item">
<div class="setting-info">
<div class="setting-label-row">
<label class="setting-label">Hardcover API Key</label>
<div class="token-input-group">
<input
pInputText
id="hardcoverApiKey"
[(ngModel)]="koboSyncSettings.hardcoverApiKey"
[type]="showHardcoverApiKey ? 'text' : 'password'"
name="hardcoverApiKey"
class="token-input"
placeholder="Enter your Hardcover API key"
(blur)="onHardcoverApiKeyChange()"
/>
<p-button
icon="pi pi-copy"
outlined="true"
severity="info"
size="small"
(onClick)="copyText(koboSyncSettings.hardcoverApiKey ?? '', 'API Key')"
[disabled]="!koboSyncSettings.hardcoverApiKey">
</p-button>
<p-button
[icon]="showHardcoverApiKey ? 'pi pi-eye-slash' : 'pi pi-eye'"
outlined="true"
severity="info"
size="small"
(onClick)="toggleShowHardcoverApiKey()">
</p-button>
</div>
</div>
<p class="setting-description">
Your personal Hardcover API key. Get it from
<a href="https://hardcover.app/account/api" target="_blank" rel="noopener">hardcover.app/account/api</a>.
This key is used only for syncing your reading progress and is not shared with other users.
</p>
</div>
</div>
}
</div>
</div>
}
@if (isAdmin) {
<div class="preferences-section">
<div class="section-header">
@@ -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({
@@ -176,6 +176,7 @@
</form>
</div>
</div>
</div>
} @else {
<div class="settings-content">
@@ -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;
@@ -3,6 +3,10 @@
<app-koreader-settings-component></app-koreader-settings-component>
</div>
<p-divider></p-divider>
<div class="py-4">
<app-hardcover-settings-component></app-hardcover-settings-component>
</div>
<p-divider></p-divider>
<div class="py-4">
<app-kobo-sync-setting-component></app-kobo-sync-setting-component>
</div>
@@ -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',