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
@@ -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;