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;