Add bidirectional Kobo reading progress sync (#2791)

* Add bidirectional Kobo reading progress sync

* Gate all two-way sync paths behind the toggle

* Add comprehensive unit tests for Kobo services

---------

Co-authored-by: acx10 <acx10@users.noreply.github.com>
This commit is contained in:
ACX
2026-02-18 13:32:12 -07:00
committed by GitHub
co-authored by acx10
parent 78f60f0c60
commit bb0609a78a
23 changed files with 1692 additions and 90 deletions
@@ -21,19 +21,36 @@ import org.booklore.repository.ShelfRepository;
import org.booklore.service.appsettings.AppSettingService;
import org.booklore.service.book.BookQueryService;
import org.booklore.service.kobo.KoboCompatibilityService;
import org.booklore.mapper.KoboReadingStateMapper;
import org.booklore.model.dto.KoboSyncSettings;
import org.booklore.model.dto.kobo.*;
import org.booklore.model.entity.KoboReadingStateEntity;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.enums.KoboReadStatus;
import org.booklore.model.enums.ReadStatus;
import org.booklore.repository.KoboReadingStateRepository;
import org.booklore.repository.UserBookProgressRepository;
import org.booklore.service.kobo.KoboEntitlementService;
import org.booklore.service.kobo.KoboReadingStateBuilder;
import org.booklore.service.kobo.KoboSettingsService;
import org.booklore.service.opds.MagicShelfBookService;
import org.booklore.util.kobo.KoboUrlBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.data.domain.PageImpl;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.HashSet;
import java.util.List;
@@ -45,6 +62,7 @@ import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class KoboEntitlementServiceTest {
@Mock
@@ -71,6 +89,21 @@ class KoboEntitlementServiceTest {
@Mock
private MagicShelfBookService magicShelfBookService;
@Mock
private UserBookProgressRepository progressRepository;
@Mock
private KoboReadingStateRepository readingStateRepository;
@Mock
private KoboReadingStateMapper readingStateMapper;
@Mock
private KoboReadingStateBuilder readingStateBuilder;
@Mock
private KoboSettingsService koboSettingsService;
@InjectMocks
private KoboEntitlementService koboEntitlementService;
@@ -406,4 +439,226 @@ class KoboEntitlementServiceTest {
return book;
}
@Nested
@DisplayName("Generate New Entitlements")
class GenerateNewEntitlements {
@Test
@DisplayName("Should generate new entitlements for supported books")
void generateNewEntitlements_supportedBooks() {
BookEntity book = createEpubBookEntity(1L);
book.setAddedOn(Instant.parse("2025-01-01T00:00:00Z"));
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
when(koboCompatibilityService.isBookSupportedForKobo(book)).thenReturn(true);
when(koboUrlBuilder.downloadUrl("token1", 1L)).thenReturn("http://test.com/download/1");
when(appSettingService.getAppSettings()).thenReturn(createAppSettingsWithKoboSettings());
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(progressRepository.findByUserIdAndBookId(any(), eq(1L))).thenReturn(Optional.empty());
when(readingStateRepository.findByEntitlementIdAndUserId(anyString(), any())).thenReturn(Optional.empty());
when(readingStateRepository.findFirstByEntitlementIdAndUserIdIsNullOrderByPriorityTimestampDescLastModifiedStringDescIdDesc(anyString()))
.thenReturn(Optional.empty());
KoboSyncSettings settings = new KoboSyncSettings();
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
when(readingStateBuilder.buildEmptyBookmark(any(OffsetDateTime.class)))
.thenReturn(KoboReadingState.CurrentBookmark.builder().build());
List<NewEntitlement> result = koboEntitlementService.generateNewEntitlements(Set.of(1L), "token1");
assertEquals(1, result.size());
assertNotNull(result.getFirst().getNewEntitlement());
assertNotNull(result.getFirst().getNewEntitlement().getBookMetadata());
assertEquals("Test EPUB Book 1", result.getFirst().getNewEntitlement().getBookMetadata().getTitle());
}
@Test
@DisplayName("Should filter out unsupported books")
void generateNewEntitlements_filterUnsupported() {
BookEntity book = createEpubBookEntity(1L);
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
when(koboCompatibilityService.isBookSupportedForKobo(book)).thenReturn(false);
List<NewEntitlement> result = koboEntitlementService.generateNewEntitlements(Set.of(1L), "token1");
assertTrue(result.isEmpty());
}
@Test
@DisplayName("Should handle empty book IDs")
void generateNewEntitlements_emptyIds() {
when(bookQueryService.findAllWithMetadataByIds(Set.of())).thenReturn(List.of());
List<NewEntitlement> result = koboEntitlementService.generateNewEntitlements(Set.of(), "token1");
assertTrue(result.isEmpty());
}
}
@Nested
@DisplayName("Generate Changed Entitlements")
class GenerateChangedEntitlements {
@Test
@DisplayName("Should generate removed entitlements with minimal metadata")
void generateChangedEntitlements_removed() {
BookEntity book = createEpubBookEntity(1L);
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
when(koboCompatibilityService.isBookSupportedForKobo(book)).thenReturn(true);
List<? extends Entitlement> result = koboEntitlementService.generateChangedEntitlements(Set.of(1L), "token1", true);
assertEquals(1, result.size());
assertTrue(result.getFirst() instanceof ChangedEntitlement);
ChangedEntitlement changed = (ChangedEntitlement) result.getFirst();
assertTrue(changed.getChangedEntitlement().getBookEntitlement().getRemoved());
}
@Test
@DisplayName("Should generate changed product metadata for non-removed EPUB books")
void generateChangedEntitlements_changed() {
BookEntity book = createEpubBookEntity(1L);
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
when(koboCompatibilityService.isBookSupportedForKobo(book)).thenReturn(true);
when(koboUrlBuilder.downloadUrl("token1", 1L)).thenReturn("http://test.com/download/1");
when(appSettingService.getAppSettings()).thenReturn(createAppSettingsWithKoboSettings());
List<? extends Entitlement> result = koboEntitlementService.generateChangedEntitlements(Set.of(1L), "token1", false);
assertEquals(1, result.size());
assertTrue(result.getFirst() instanceof ChangedProductMetadata);
}
}
@Nested
@DisplayName("Generate Changed Reading States")
class GenerateChangedReadingStates {
@Test
@DisplayName("Should generate changed reading states from progress entries")
void generateChangedReadingStates_fromProgress() {
BookEntity book = new BookEntity();
book.setId(1L);
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setBook(book);
progress.setKoboProgressPercent(50f);
progress.setReadStatus(ReadStatus.READING);
KoboSyncSettings settings = new KoboSyncSettings();
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(50)
.build();
when(readingStateBuilder.buildBookmarkFromProgress(eq(progress), any(OffsetDateTime.class)))
.thenReturn(bookmark);
when(readingStateBuilder.buildStatusInfoFromProgress(eq(progress), anyString()))
.thenReturn(KoboReadingState.StatusInfo.builder()
.status(KoboReadStatus.READING)
.timesStartedReading(1)
.build());
List<ChangedReadingState> result = koboEntitlementService.generateChangedReadingStates(List.of(progress));
assertEquals(1, result.size());
assertNotNull(result.getFirst().getChangedReadingState());
KoboReadingState state = result.getFirst().getChangedReadingState().getReadingState();
assertEquals("1", state.getEntitlementId());
assertNotNull(state.getCurrentBookmark());
assertNotNull(state.getStatusInfo());
}
@Test
@DisplayName("Should use empty bookmark when no progress data exists")
void generateChangedReadingStates_emptyBookmark() {
BookEntity book = new BookEntity();
book.setId(1L);
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setBook(book);
progress.setReadStatus(ReadStatus.UNREAD);
KoboSyncSettings settings = new KoboSyncSettings();
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
KoboReadingState.CurrentBookmark emptyBookmark = KoboReadingState.CurrentBookmark.builder().build();
when(readingStateBuilder.buildEmptyBookmark(any(OffsetDateTime.class))).thenReturn(emptyBookmark);
when(readingStateBuilder.buildStatusInfoFromProgress(eq(progress), anyString()))
.thenReturn(KoboReadingState.StatusInfo.builder()
.status(KoboReadStatus.READY_TO_READ)
.timesStartedReading(0)
.build());
List<ChangedReadingState> result = koboEntitlementService.generateChangedReadingStates(List.of(progress));
assertEquals(1, result.size());
}
@Test
@DisplayName("Should include epub progress in bookmark when two-way sync ON")
void generateChangedReadingStates_twoWaySync() {
BookEntity book = new BookEntity();
book.setId(1L);
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setBook(book);
progress.setEpubProgressPercent(70f);
progress.setReadStatus(ReadStatus.READING);
KoboSyncSettings settings = new KoboSyncSettings();
settings.setTwoWayProgressSync(true);
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(70)
.build();
when(readingStateBuilder.buildBookmarkFromProgress(eq(progress), any(OffsetDateTime.class)))
.thenReturn(bookmark);
when(readingStateBuilder.buildStatusInfoFromProgress(eq(progress), anyString()))
.thenReturn(KoboReadingState.StatusInfo.builder()
.status(KoboReadStatus.READING)
.timesStartedReading(1)
.build());
List<ChangedReadingState> result = koboEntitlementService.generateChangedReadingStates(List.of(progress));
assertEquals(1, result.size());
assertEquals(70, result.getFirst().getChangedReadingState().getReadingState()
.getCurrentBookmark().getProgressPercent());
}
@Test
@DisplayName("Should NOT include epub progress in bookmark when two-way sync OFF")
void generateChangedReadingStates_twoWaySyncOff() {
BookEntity book = new BookEntity();
book.setId(1L);
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setBook(book);
progress.setKoboProgressPercent(null);
progress.setEpubProgressPercent(70f);
progress.setReadStatus(ReadStatus.READING);
KoboSyncSettings settings = new KoboSyncSettings();
settings.setTwoWayProgressSync(false);
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
KoboReadingState.CurrentBookmark emptyBookmark = KoboReadingState.CurrentBookmark.builder().build();
when(readingStateBuilder.buildEmptyBookmark(any(OffsetDateTime.class))).thenReturn(emptyBookmark);
when(readingStateBuilder.buildStatusInfoFromProgress(eq(progress), anyString()))
.thenReturn(KoboReadingState.StatusInfo.builder()
.status(KoboReadStatus.READING)
.timesStartedReading(1)
.build());
List<ChangedReadingState> result = koboEntitlementService.generateChangedReadingStates(List.of(progress));
assertEquals(1, result.size());
verify(readingStateBuilder).buildEmptyBookmark(any(OffsetDateTime.class));
}
}
}
@@ -1,18 +1,25 @@
package org.booklore.service;
import org.booklore.model.dto.KoboSyncSettings;
import org.booklore.model.dto.kobo.KoboReadingState;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.enums.KoboReadStatus;
import org.booklore.model.enums.ReadStatus;
import org.booklore.service.kobo.KoboReadingStateBuilder;
import org.booklore.service.kobo.KoboSettingsService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.time.Instant;
import java.time.OffsetDateTime;
@@ -20,15 +27,24 @@ import java.time.ZoneOffset;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.when;
@DisplayName("KoboReadingStateBuilder Tests")
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class KoboReadingStateBuilderTest {
@Mock
private KoboSettingsService koboSettingsService;
private KoboReadingStateBuilder builder;
@BeforeEach
void setUp() {
builder = new KoboReadingStateBuilder();
KoboSyncSettings settings = new KoboSyncSettings();
settings.setTwoWayProgressSync(true);
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
builder = new KoboReadingStateBuilder(koboSettingsService);
}
@Nested
@@ -31,6 +31,10 @@ import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import tools.jackson.databind.ObjectMapper;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.UserBookFileProgressEntity;
import org.booklore.repository.UserBookFileProgressRepository;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
@@ -69,6 +73,9 @@ class KoboReadingStateServiceTest {
@Mock
private HardcoverSyncService hardcoverSyncService;
@Mock
private UserBookFileProgressRepository fileProgressRepository;
@InjectMocks
private KoboReadingStateService service;
@@ -278,7 +285,7 @@ class KoboReadingStateServiceTest {
assertEquals("Kobo", state.getCurrentBookmark().getLocation().getSource());
verify(repository).findByEntitlementIdAndUserId(entitlementId, 1L);
verify(progressRepository).findByUserIdAndBookId(1L, 100L);
verify(progressRepository, atLeastOnce()).findByUserIdAndBookId(1L, 100L);
verify(readingStateBuilder).buildReadingStateFromProgress(entitlementId, progress);
}
@@ -328,13 +335,13 @@ class KoboReadingStateServiceTest {
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.of(entity));
when(mapper.toDto(entity)).thenReturn(existingState);
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.empty());
List<KoboReadingState> result = service.getReadingState(entitlementId);
assertNotNull(result);
assertEquals(1, result.size());
assertEquals(entitlementId, result.getFirst().getEntitlementId());
verify(progressRepository, never()).findByUserIdAndBookId(anyLong(), anyLong());
}
@Test
@@ -523,4 +530,453 @@ class KoboReadingStateServiceTest {
assertEquals(existingStatus.getStatus(), savedStatus.getStatus());
assertEquals(timestamp, saved.getLastModifiedString());
}
@Test
@DisplayName("Should delete reading state for authenticated user")
void testDeleteReadingState() {
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(repository.findByEntitlementIdAndUserId("100", 1L)).thenReturn(Optional.of(entity));
service.deleteReadingState(100L);
verify(repository).delete(entity);
}
@Test
@DisplayName("Should not throw when deleting non-existent reading state")
void testDeleteReadingState_notFound() {
when(repository.findByEntitlementIdAndUserId("100", 1L)).thenReturn(Optional.empty());
assertDoesNotThrow(() -> service.deleteReadingState(100L));
verify(repository, never()).delete(any());
}
@Test
@DisplayName("Should overlay web reader bookmark when two-way sync is ON and web reader data exists")
void testGetReadingState_overlayWebReaderBookmark() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
KoboReadingState existingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
.progressPercent(30)
.contentSourceProgressPercent(45)
.location(KoboReadingState.CurrentBookmark.Location.builder()
.value("epubcfi(/6/10)")
.type("EpubCfi")
.source("Kobo")
.build())
.lastModified("2025-01-01T00:00:00Z")
.build())
.build();
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.of(entity));
when(mapper.toDto(entity)).thenReturn(existingState);
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setEpubProgress("epubcfi(/6/20)");
progress.setEpubProgressPercent(65f);
progress.setLastReadTime(Instant.parse("2025-06-01T10:00:00Z"));
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
KoboReadingState.CurrentBookmark webBookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(65)
.lastModified("2025-06-01T10:00:00Z")
.build();
when(readingStateBuilder.buildBookmarkFromProgress(progress)).thenReturn(webBookmark);
List<KoboReadingState> result = service.getReadingState(entitlementId);
assertEquals(1, result.size());
KoboReadingState.CurrentBookmark bookmark = result.getFirst().getCurrentBookmark();
assertEquals(65, bookmark.getProgressPercent());
assertEquals(45, bookmark.getContentSourceProgressPercent());
assertNotNull(bookmark.getLocation());
assertEquals("epubcfi(/6/10)", bookmark.getLocation().getValue());
}
@Test
@DisplayName("Should NOT overlay web reader bookmark when two-way sync is OFF")
void testGetReadingState_noOverlayWhenToggleOff() {
testSettings.setTwoWayProgressSync(false);
String entitlementId = "100";
KoboReadingState existingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
.progressPercent(30)
.lastModified("2025-01-01T00:00:00Z")
.build())
.build();
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.of(entity));
when(mapper.toDto(entity)).thenReturn(existingState);
List<KoboReadingState> result = service.getReadingState(entitlementId);
assertEquals(1, result.size());
assertEquals(30, result.getFirst().getCurrentBookmark().getProgressPercent());
verify(readingStateBuilder, never()).buildBookmarkFromProgress(any());
}
@Test
@DisplayName("Should cross-populate epub fields from Kobo when two-way sync is ON")
void testSyncKoboProgress_crossPopulateEpubFields() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
BookFileEntity primaryFile = BookFileEntity.builder().id(10L).build();
testBook.setBookFiles(List.of(primaryFile));
UserBookProgressEntity existingProgress = new UserBookProgressEntity();
existingProgress.setUser(testUserEntity);
existingProgress.setBook(testBook);
KoboReadingState.CurrentBookmark.Location location = KoboReadingState.CurrentBookmark.Location.builder()
.value("epubcfi(/6/8)")
.type("EpubCfi")
.source("chapter3.xhtml")
.build();
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(55)
.location(location)
.lastModified("2025-06-15T12:00:00Z")
.build();
KoboReadingState readingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(bookmark)
.build();
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(repository.save(any())).thenReturn(entity);
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
when(userRepository.findById(1L)).thenReturn(Optional.of(testUserEntity));
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(existingProgress));
when(fileProgressRepository.findByUserIdAndBookFileId(1L, 10L)).thenReturn(Optional.empty());
ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
when(progressRepository.save(captor.capture())).thenReturn(existingProgress);
service.saveReadingState(List.of(readingState));
UserBookProgressEntity saved = captor.getValue();
assertEquals(55f, saved.getEpubProgressPercent());
assertEquals("chapter3.xhtml", saved.getEpubProgressHref());
assertNull(saved.getEpubProgress());
}
@Test
@DisplayName("Should NOT cross-populate epub fields when two-way sync is OFF")
void testSyncKoboProgress_noCrossPopulateWhenToggleOff() {
testSettings.setTwoWayProgressSync(false);
String entitlementId = "100";
UserBookProgressEntity existingProgress = new UserBookProgressEntity();
existingProgress.setUser(testUserEntity);
existingProgress.setBook(testBook);
existingProgress.setEpubProgressPercent(40f);
existingProgress.setEpubProgress("epubcfi(/6/4)");
KoboReadingState readingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
.progressPercent(70)
.build())
.build();
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(repository.save(any())).thenReturn(entity);
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
when(userRepository.findById(1L)).thenReturn(Optional.of(testUserEntity));
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(existingProgress));
ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
when(progressRepository.save(captor.capture())).thenReturn(existingProgress);
service.saveReadingState(List.of(readingState));
UserBookProgressEntity saved = captor.getValue();
assertEquals(40f, saved.getEpubProgressPercent());
assertEquals("epubcfi(/6/4)", saved.getEpubProgress());
}
@Test
@DisplayName("Should not cross-populate when web reader has newer progress")
void testSyncKoboProgress_skipCrossPopulateWhenWebReaderNewer() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
BookFileEntity primaryFile = BookFileEntity.builder().id(10L).build();
testBook.setBookFiles(List.of(primaryFile));
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
fileProgress.setLastReadTime(Instant.now().plusSeconds(3600));
UserBookProgressEntity existingProgress = new UserBookProgressEntity();
existingProgress.setUser(testUserEntity);
existingProgress.setBook(testBook);
existingProgress.setEpubProgressPercent(80f);
existingProgress.setEpubProgress("epubcfi(/6/20)");
KoboReadingState readingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
.progressPercent(50)
.lastModified("2025-01-01T00:00:00Z")
.build())
.build();
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(repository.save(any())).thenReturn(entity);
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
when(userRepository.findById(1L)).thenReturn(Optional.of(testUserEntity));
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(existingProgress));
when(fileProgressRepository.findByUserIdAndBookFileId(1L, 10L)).thenReturn(Optional.of(fileProgress));
ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
when(progressRepository.save(captor.capture())).thenReturn(existingProgress);
service.saveReadingState(List.of(readingState));
UserBookProgressEntity saved = captor.getValue();
assertEquals(80f, saved.getEpubProgressPercent());
assertEquals("epubcfi(/6/20)", saved.getEpubProgress());
}
@Test
@DisplayName("Should construct reading state from web reader progress when toggle ON and no Kobo data")
void testGetReadingState_constructFromWebReaderProgress_whenToggleOn() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setKoboProgressPercent(null);
progress.setKoboLocation(null);
progress.setEpubProgressPercent(60f);
progress.setEpubProgress("epubcfi(/6/12)");
KoboReadingState expectedState = KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
.progressPercent(60)
.build())
.build();
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
when(readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress)).thenReturn(expectedState);
KoboReadingState.CurrentBookmark webBookmark = KoboReadingState.CurrentBookmark.builder()
.progressPercent(60)
.lastModified("2025-06-01T10:00:00Z")
.build();
when(readingStateBuilder.buildBookmarkFromProgress(progress)).thenReturn(webBookmark);
List<KoboReadingState> result = service.getReadingState(entitlementId);
assertEquals(1, result.size());
verify(readingStateBuilder).buildReadingStateFromProgress(entitlementId, progress);
}
@Test
@DisplayName("Should NOT construct reading state from web reader progress when toggle OFF")
void testGetReadingState_noConstructFromWebReaderProgress_whenToggleOff() {
testSettings.setTwoWayProgressSync(false);
String entitlementId = "100";
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setKoboProgressPercent(null);
progress.setKoboLocation(null);
progress.setEpubProgressPercent(60f);
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
List<KoboReadingState> result = service.getReadingState(entitlementId);
assertTrue(result.isEmpty());
verify(readingStateBuilder, never()).buildReadingStateFromProgress(any(), any());
}
@Test
@DisplayName("Should sync location data from Kobo bookmark")
void testSyncKoboProgress_locationData() {
String entitlementId = "100";
KoboReadingState.CurrentBookmark.Location location = KoboReadingState.CurrentBookmark.Location.builder()
.value("epubcfi(/6/4[chap01ref]!/4/2/1:3)")
.type("EpubCfi")
.source("Kobo")
.build();
KoboReadingState readingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
.progressPercent(42)
.location(location)
.build())
.build();
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(repository.save(any())).thenReturn(entity);
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
when(userRepository.findById(1L)).thenReturn(Optional.of(testUserEntity));
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.empty());
ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
when(progressRepository.save(captor.capture())).thenReturn(new UserBookProgressEntity());
service.saveReadingState(List.of(readingState));
UserBookProgressEntity saved = captor.getValue();
assertEquals("epubcfi(/6/4[chap01ref]!/4/2/1:3)", saved.getKoboLocation());
assertEquals("EpubCfi", saved.getKoboLocationType());
assertEquals("Kobo", saved.getKoboLocationSource());
assertEquals(42f, saved.getKoboProgressPercent());
}
@Test
@DisplayName("Should set finished date when progress reaches threshold for new book")
void testSyncKoboProgress_setsFinishedDate() {
testSettings.setProgressMarkAsFinishedThreshold(99f);
String entitlementId = "100";
KoboReadingState readingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
.progressPercent(100)
.build())
.build();
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(repository.save(any())).thenReturn(entity);
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
when(userRepository.findById(1L)).thenReturn(Optional.of(testUserEntity));
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.empty());
ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
when(progressRepository.save(captor.capture())).thenReturn(new UserBookProgressEntity());
service.saveReadingState(List.of(readingState));
UserBookProgressEntity saved = captor.getValue();
assertEquals(ReadStatus.READ, saved.getReadStatus());
assertNotNull(saved.getDateFinished());
}
@Test
@DisplayName("Should use configurable thresholds for status derivation")
void testSyncKoboProgress_configurableThresholds() {
testSettings.setProgressMarkAsReadingThreshold(10f);
testSettings.setProgressMarkAsFinishedThreshold(95f);
String entitlementId = "100";
KoboReadingState readingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
.progressPercent(5)
.build())
.build();
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(repository.save(any())).thenReturn(entity);
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
when(userRepository.findById(1L)).thenReturn(Optional.of(testUserEntity));
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.empty());
ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
when(progressRepository.save(captor.capture())).thenReturn(new UserBookProgressEntity());
service.saveReadingState(List.of(readingState));
assertEquals(ReadStatus.UNREAD, captor.getValue().getReadStatus());
}
@Test
@DisplayName("Should trigger Hardcover sync when progress changes")
void testSyncKoboProgress_triggersHardcover() {
String entitlementId = "100";
UserBookProgressEntity existingProgress = new UserBookProgressEntity();
existingProgress.setUser(testUserEntity);
existingProgress.setBook(testBook);
existingProgress.setKoboProgressPercent(30f);
KoboReadingState readingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
.progressPercent(50)
.build())
.build();
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(repository.save(any())).thenReturn(entity);
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
when(userRepository.findById(1L)).thenReturn(Optional.of(testUserEntity));
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(existingProgress));
ArgumentCaptor<UserBookProgressEntity> captor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
when(progressRepository.save(captor.capture())).thenReturn(existingProgress);
service.saveReadingState(List.of(readingState));
verify(hardcoverSyncService).syncProgressToHardcover(eq(100L), eq(50f), eq(1L));
}
@Test
@DisplayName("Should handle multiple reading states in a single save call")
void testSaveReadingState_multipleStates() {
KoboReadingState state1 = KoboReadingState.builder()
.entitlementId("100")
.currentBookmark(KoboReadingState.CurrentBookmark.builder().progressPercent(25).build())
.build();
KoboReadingState state2 = KoboReadingState.builder()
.entitlementId("200")
.currentBookmark(KoboReadingState.CurrentBookmark.builder().progressPercent(75).build())
.build();
BookEntity book2 = new BookEntity();
book2.setId(200L);
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(state1, state2);
when(repository.findByEntitlementIdAndUserId(anyString(), eq(1L))).thenReturn(Optional.empty());
when(repository.save(any())).thenReturn(entity);
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
when(bookRepository.findById(200L)).thenReturn(Optional.of(book2));
when(userRepository.findById(1L)).thenReturn(Optional.of(testUserEntity));
when(progressRepository.findByUserIdAndBookId(eq(1L), anyLong())).thenReturn(Optional.empty());
when(progressRepository.save(any())).thenReturn(new UserBookProgressEntity());
assertDoesNotThrow(() -> service.saveReadingState(List.of(state1, state2)));
verify(progressRepository, times(2)).save(any());
}
}
@@ -0,0 +1,131 @@
package org.booklore.service.kobo;
import org.booklore.model.dto.kobo.KoboAuthentication;
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.junit.jupiter.MockitoExtension;
import org.springframework.http.ResponseEntity;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
import tools.jackson.databind.node.ObjectNode;
import static org.junit.jupiter.api.Assertions.*;
@ExtendWith(MockitoExtension.class)
@DisplayName("KoboDeviceAuthService Tests")
class KoboDeviceAuthServiceTest {
private KoboDeviceAuthService service;
private ObjectMapper objectMapper;
@BeforeEach
void setUp() {
objectMapper = JsonMapper.builder().build();
service = new KoboDeviceAuthService(objectMapper);
}
@Test
@DisplayName("Should authenticate device with valid UserKey")
void authenticateDevice_validUserKey() {
ObjectNode body = objectMapper.createObjectNode();
body.put("UserKey", "test-user-key-123");
ResponseEntity<KoboAuthentication> response = service.authenticateDevice(body);
assertEquals(200, response.getStatusCode().value());
KoboAuthentication auth = response.getBody();
assertNotNull(auth);
assertEquals("test-user-key-123", auth.getUserKey());
assertNotNull(auth.getAccessToken());
assertNotNull(auth.getRefreshToken());
assertNotNull(auth.getTrackingId());
assertEquals(24, auth.getAccessToken().length());
assertEquals(24, auth.getRefreshToken().length());
}
@Test
@DisplayName("Should generate unique tokens per request")
void authenticateDevice_uniqueTokens() {
ObjectNode body = objectMapper.createObjectNode();
body.put("UserKey", "user1");
KoboAuthentication first = service.authenticateDevice(body).getBody();
KoboAuthentication second = service.authenticateDevice(body).getBody();
assertNotEquals(first.getAccessToken(), second.getAccessToken());
assertNotEquals(first.getRefreshToken(), second.getRefreshToken());
assertNotEquals(first.getTrackingId(), second.getTrackingId());
}
@Test
@DisplayName("Should throw when request body is null")
void authenticateDevice_nullBody() {
assertThrows(IllegalArgumentException.class, () -> service.authenticateDevice(null));
}
@Test
@DisplayName("Should throw when UserKey is missing")
void authenticateDevice_missingUserKey() {
ObjectNode body = objectMapper.createObjectNode();
body.put("SomeOtherField", "value");
assertThrows(IllegalArgumentException.class, () -> service.authenticateDevice(body));
}
@Test
@DisplayName("Should set correct Content-Type header")
void authenticateDevice_contentTypeHeader() {
ObjectNode body = objectMapper.createObjectNode();
body.put("UserKey", "user1");
ResponseEntity<KoboAuthentication> response = service.authenticateDevice(body);
assertTrue(response.getHeaders().getFirst("Content-Type").contains("application/json"));
}
@Test
@DisplayName("Should set Content-Length header")
void authenticateDevice_contentLengthHeader() {
ObjectNode body = objectMapper.createObjectNode();
body.put("UserKey", "user1");
ResponseEntity<KoboAuthentication> response = service.authenticateDevice(body);
String contentLength = response.getHeaders().getFirst("Content-Length");
assertNotNull(contentLength);
assertTrue(Integer.parseInt(contentLength) > 0);
}
@Test
@DisplayName("Should serialize KoboAuthentication to JSON bytes")
void toJsonBytes_validAuth() {
KoboAuthentication auth = KoboAuthentication.builder()
.accessToken("abc123")
.refreshToken("def456")
.trackingId("track-1")
.userKey("user-key")
.build();
byte[] bytes = service.toJsonBytes(auth);
assertNotNull(bytes);
assertTrue(bytes.length > 0);
String json = new String(bytes);
assertTrue(json.contains("abc123"));
assertTrue(json.contains("user-key"));
}
@Test
@DisplayName("Should preserve UserKey value exactly as received")
void authenticateDevice_preservesUserKey() {
String userKey = "special-chars_123.ABC@domain";
ObjectNode body = objectMapper.createObjectNode();
body.put("UserKey", userKey);
KoboAuthentication auth = service.authenticateDevice(body).getBody();
assertEquals(userKey, auth.getUserKey());
}
}
@@ -0,0 +1,202 @@
package org.booklore.service.kobo;
import org.booklore.model.dto.kobo.KoboResources;
import org.booklore.util.kobo.KoboUrlBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.ResponseEntity;
import org.springframework.web.util.UriComponentsBuilder;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
import tools.jackson.databind.node.ObjectNode;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@DisplayName("KoboInitializationService Tests")
class KoboInitializationServiceTest {
@Mock
private KoboServerProxy koboServerProxy;
@Mock
private KoboResourcesComponent koboResourcesComponent;
@Mock
private KoboUrlBuilder koboUrlBuilder;
@InjectMocks
private KoboInitializationService service;
private final ObjectMapper objectMapper = JsonMapper.builder().build();
@BeforeEach
void setUp() {
when(koboUrlBuilder.baseBuilder()).thenReturn(UriComponentsBuilder.fromUriString("http://localhost:8080"));
when(koboUrlBuilder.imageUrlTemplate("test-token")).thenReturn("http://localhost:8080/kobo/test-token/image/{ImageId}/{Width}/{Height}/false/image.jpg");
when(koboUrlBuilder.imageUrlQualityTemplate("test-token")).thenReturn("http://localhost:8080/kobo/test-token/image/{ImageId}/{Width}/{Height}/{Quality}/{IsGreyscale}/image.jpg");
when(koboUrlBuilder.librarySyncUrl("test-token")).thenReturn("http://localhost:8080/kobo/test-token/v1/library/sync");
}
@Nested
@DisplayName("When Kobo proxy returns Resources")
class WithProxyResources {
@Test
@DisplayName("Should use Resources from Kobo proxy response")
void initialize_usesProxyResources() throws Exception {
ObjectNode resources = objectMapper.createObjectNode();
resources.put("library_sync", "https://storeapi.kobo.com/v1/library/sync");
resources.put("image_host", "https://cdn.kobo.com/book-images/");
ObjectNode body = objectMapper.createObjectNode();
body.set("Resources", resources);
when(koboServerProxy.proxyCurrentRequest(null, false))
.thenReturn(ResponseEntity.ok(body));
ResponseEntity<KoboResources> response = service.initialize("test-token");
assertEquals(200, response.getStatusCode().value());
assertNotNull(response.getBody());
JsonNode result = response.getBody().getResources();
assertEquals("http://localhost:8080/kobo/test-token/v1/library/sync", result.get("library_sync").asText());
}
@Test
@DisplayName("Should override image_host with local base URL")
void initialize_overridesImageHost() throws Exception {
ObjectNode resources = objectMapper.createObjectNode();
resources.put("image_host", "https://cdn.kobo.com/book-images/");
ObjectNode body = objectMapper.createObjectNode();
body.set("Resources", resources);
when(koboServerProxy.proxyCurrentRequest(null, false))
.thenReturn(ResponseEntity.ok(body));
ResponseEntity<KoboResources> response = service.initialize("test-token");
JsonNode result = response.getBody().getResources();
assertEquals("http://localhost:8080", result.get("image_host").asText());
}
@Test
@DisplayName("Should override image_url_template with local URL")
void initialize_overridesImageUrlTemplate() throws Exception {
ObjectNode resources = objectMapper.createObjectNode();
resources.put("image_url_template", "https://cdn.kobo.com/book-images/{ImageId}/{Width}/{Height}/false/image.jpg");
ObjectNode body = objectMapper.createObjectNode();
body.set("Resources", resources);
when(koboServerProxy.proxyCurrentRequest(null, false))
.thenReturn(ResponseEntity.ok(body));
ResponseEntity<KoboResources> response = service.initialize("test-token");
JsonNode result = response.getBody().getResources();
assertTrue(result.get("image_url_template").asText().contains("localhost:8080"));
}
}
@Nested
@DisplayName("When Kobo proxy fails or returns no Resources")
class WithoutProxyResources {
@Test
@DisplayName("Should fall back to local resources when proxy returns null body")
void initialize_fallsBackOnNullBody() throws Exception {
when(koboServerProxy.proxyCurrentRequest(null, false))
.thenReturn(ResponseEntity.ok(null));
ObjectNode fallbackResources = objectMapper.createObjectNode();
fallbackResources.put("library_sync", "https://storeapi.kobo.com/v1/library/sync");
when(koboResourcesComponent.getResources()).thenReturn(fallbackResources);
ResponseEntity<KoboResources> response = service.initialize("test-token");
assertEquals(200, response.getStatusCode().value());
verify(koboResourcesComponent).getResources();
}
@Test
@DisplayName("Should fall back to local resources when proxy throws exception")
void initialize_fallsBackOnProxyException() throws Exception {
when(koboServerProxy.proxyCurrentRequest(null, false))
.thenThrow(new RuntimeException("Connection refused"));
ObjectNode fallbackResources = objectMapper.createObjectNode();
fallbackResources.put("library_sync", "https://storeapi.kobo.com/v1/library/sync");
when(koboResourcesComponent.getResources()).thenReturn(fallbackResources);
ResponseEntity<KoboResources> response = service.initialize("test-token");
assertEquals(200, response.getStatusCode().value());
verify(koboResourcesComponent).getResources();
}
@Test
@DisplayName("Should fall back when proxy response has no Resources key")
void initialize_fallsBackOnMissingResourcesKey() throws Exception {
ObjectNode body = objectMapper.createObjectNode();
body.put("SomeOtherKey", "value");
when(koboServerProxy.proxyCurrentRequest(null, false))
.thenReturn(ResponseEntity.ok(body));
ObjectNode fallbackResources = objectMapper.createObjectNode();
fallbackResources.put("library_sync", "https://storeapi.kobo.com/v1/library/sync");
when(koboResourcesComponent.getResources()).thenReturn(fallbackResources);
ResponseEntity<KoboResources> response = service.initialize("test-token");
verify(koboResourcesComponent).getResources();
assertEquals("http://localhost:8080/kobo/test-token/v1/library/sync",
response.getBody().getResources().get("library_sync").asText());
}
@Test
@DisplayName("Should fall back when proxy returns null response")
void initialize_fallsBackOnNullResponse() throws Exception {
when(koboServerProxy.proxyCurrentRequest(null, false)).thenReturn(null);
ObjectNode fallbackResources = objectMapper.createObjectNode();
fallbackResources.put("library_sync", "https://storeapi.kobo.com/v1/library/sync");
when(koboResourcesComponent.getResources()).thenReturn(fallbackResources);
ResponseEntity<KoboResources> response = service.initialize("test-token");
assertEquals(200, response.getStatusCode().value());
verify(koboResourcesComponent).getResources();
}
}
@Nested
@DisplayName("Response Headers")
class ResponseHeaders {
@Test
@DisplayName("Should include x-kobo-apitoken header")
void initialize_includesApiTokenHeader() throws Exception {
ObjectNode resources = objectMapper.createObjectNode();
ObjectNode body = objectMapper.createObjectNode();
body.set("Resources", resources);
when(koboServerProxy.proxyCurrentRequest(null, false))
.thenReturn(ResponseEntity.ok(body));
ResponseEntity<KoboResources> response = service.initialize("test-token");
assertEquals("e30=", response.getHeaders().getFirst("x-kobo-apitoken"));
}
}
}
@@ -0,0 +1,311 @@
package org.booklore.service.kobo;
import org.booklore.model.dto.KoboSyncSettings;
import org.booklore.model.dto.kobo.ChangedReadingState;
import org.booklore.model.dto.kobo.KoboReadingState;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.enums.ReadStatus;
import org.booklore.repository.KoboDeletedBookProgressRepository;
import org.booklore.repository.UserBookProgressRepository;
import org.booklore.util.kobo.BookloreSyncTokenGenerator;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import tools.jackson.databind.ObjectMapper;
import java.time.Instant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("KoboLibrarySyncService Tests")
class KoboLibrarySyncServiceTest {
@Mock
private BookloreSyncTokenGenerator tokenGenerator;
@Mock
private KoboLibrarySnapshotService koboLibrarySnapshotService;
@Mock
private KoboEntitlementService entitlementService;
@Mock
private KoboDeletedBookProgressRepository koboDeletedBookProgressRepository;
@Mock
private UserBookProgressRepository userBookProgressRepository;
@Mock
private KoboServerProxy koboServerProxy;
@Mock
private ObjectMapper objectMapper;
@Mock
private KoboSettingsService koboSettingsService;
@InjectMocks
private KoboLibrarySyncService service;
private KoboSyncSettings testSettings;
@BeforeEach
void setUp() {
testSettings = new KoboSyncSettings();
testSettings.setTwoWayProgressSync(false);
when(koboSettingsService.getCurrentUserSettings()).thenReturn(testSettings);
}
@Nested
@DisplayName("Sync Filtering - Two-Way Toggle Gating")
class TwoWaySyncFiltering {
@Test
@DisplayName("Should filter out web-reader-only entries when two-way sync is OFF")
void filterWebReaderOnlyEntries_whenToggleOff() {
testSettings.setTwoWayProgressSync(false);
UserBookProgressEntity webReaderOnly = createProgress(1L);
webReaderOnly.setEpubProgress("epubcfi(/6/4)");
webReaderOnly.setEpubProgressPercent(50f);
webReaderOnly.setLastReadTime(Instant.now());
webReaderOnly.setKoboProgressPercent(null);
webReaderOnly.setKoboProgressReceivedTime(null);
webReaderOnly.setReadStatusModifiedTime(null);
assertFalse(needsStatusSync(webReaderOnly));
assertFalse(needsKoboProgressSync(webReaderOnly));
}
@Test
@DisplayName("Should include Kobo progress entries regardless of toggle state")
void includeKoboProgressEntries_alwaysIncluded() {
testSettings.setTwoWayProgressSync(false);
UserBookProgressEntity koboProgress = createProgress(1L);
koboProgress.setKoboProgressPercent(75f);
koboProgress.setKoboProgressReceivedTime(Instant.now());
koboProgress.setKoboProgressSentTime(null);
assertTrue(needsKoboProgressSync(koboProgress));
}
@Test
@DisplayName("Should include status sync entries regardless of toggle state")
void includeStatusEntries_alwaysIncluded() {
testSettings.setTwoWayProgressSync(false);
UserBookProgressEntity statusProgress = createProgress(1L);
statusProgress.setReadStatus(ReadStatus.READ);
statusProgress.setReadStatusModifiedTime(Instant.now());
statusProgress.setKoboStatusSentTime(null);
assertTrue(needsStatusSync(statusProgress));
}
@Test
@DisplayName("Should not filter web-reader entries when two-way sync is ON")
void includeWebReaderEntries_whenToggleOn() {
testSettings.setTwoWayProgressSync(true);
UserBookProgressEntity webReaderProgress = createProgress(1L);
webReaderProgress.setEpubProgress("epubcfi(/6/4)");
webReaderProgress.setEpubProgressPercent(50f);
webReaderProgress.setLastReadTime(Instant.now());
assertNotNull(webReaderProgress.getEpubProgressPercent());
assertNotNull(webReaderProgress.getLastReadTime());
}
}
@Nested
@DisplayName("Progress Sync Detection")
class ProgressSyncDetection {
@Test
@DisplayName("Should detect unsynced Kobo progress when never sent")
void needsKoboProgressSync_neverSent() {
UserBookProgressEntity progress = createProgress(1L);
progress.setKoboProgressReceivedTime(Instant.now());
progress.setKoboProgressSentTime(null);
assertTrue(needsKoboProgressSync(progress));
}
@Test
@DisplayName("Should detect unsynced Kobo progress when received after sent")
void needsKoboProgressSync_receivedAfterSent() {
UserBookProgressEntity progress = createProgress(1L);
progress.setKoboProgressReceivedTime(Instant.now());
progress.setKoboProgressSentTime(Instant.now().minusSeconds(60));
assertTrue(needsKoboProgressSync(progress));
}
@Test
@DisplayName("Should not detect sync needed when sent after received")
void needsKoboProgressSync_alreadySynced() {
UserBookProgressEntity progress = createProgress(1L);
progress.setKoboProgressReceivedTime(Instant.now().minusSeconds(60));
progress.setKoboProgressSentTime(Instant.now());
assertFalse(needsKoboProgressSync(progress));
}
@Test
@DisplayName("Should not detect sync needed when no progress received")
void needsKoboProgressSync_noProgressReceived() {
UserBookProgressEntity progress = createProgress(1L);
progress.setKoboProgressReceivedTime(null);
assertFalse(needsKoboProgressSync(progress));
}
}
@Nested
@DisplayName("Status Sync Detection")
class StatusSyncDetection {
@Test
@DisplayName("Should detect unsynced status when never sent")
void needsStatusSync_neverSent() {
UserBookProgressEntity progress = createProgress(1L);
progress.setReadStatusModifiedTime(Instant.now());
progress.setKoboStatusSentTime(null);
assertTrue(needsStatusSync(progress));
}
@Test
@DisplayName("Should detect unsynced status when modified after sent")
void needsStatusSync_modifiedAfterSent() {
UserBookProgressEntity progress = createProgress(1L);
progress.setReadStatusModifiedTime(Instant.now());
progress.setKoboStatusSentTime(Instant.now().minusSeconds(60));
assertTrue(needsStatusSync(progress));
}
@Test
@DisplayName("Should not detect status sync when already sent")
void needsStatusSync_alreadySynced() {
UserBookProgressEntity progress = createProgress(1L);
progress.setReadStatusModifiedTime(Instant.now().minusSeconds(60));
progress.setKoboStatusSentTime(Instant.now());
assertFalse(needsStatusSync(progress));
}
@Test
@DisplayName("Should not detect status sync when no modification time")
void needsStatusSync_noModificationTime() {
UserBookProgressEntity progress = createProgress(1L);
progress.setReadStatusModifiedTime(null);
assertFalse(needsStatusSync(progress));
}
}
@Nested
@DisplayName("Web Reader Progress Sync (Two-Way)")
class WebReaderProgressSync {
@Test
@DisplayName("Should detect web reader progress needing sync when toggle ON and lastReadTime after sent")
void needsProgressSync_webReaderNewer() {
testSettings.setTwoWayProgressSync(true);
UserBookProgressEntity progress = createProgress(1L);
progress.setEpubProgress("epubcfi(/6/4)");
progress.setEpubProgressPercent(65f);
progress.setLastReadTime(Instant.now());
progress.setKoboProgressSentTime(Instant.now().minusSeconds(60));
progress.setKoboProgressReceivedTime(Instant.now().minusSeconds(120));
assertTrue(needsProgressSync(progress));
}
@Test
@DisplayName("Should not sync web reader progress when toggle OFF")
void needsProgressSync_toggleOff() {
testSettings.setTwoWayProgressSync(false);
UserBookProgressEntity progress = createProgress(1L);
progress.setEpubProgress("epubcfi(/6/4)");
progress.setEpubProgressPercent(65f);
progress.setLastReadTime(Instant.now());
progress.setKoboProgressSentTime(Instant.now().minusSeconds(60));
progress.setKoboProgressReceivedTime(null);
assertFalse(needsProgressSync(progress));
}
@Test
@DisplayName("Should not bounce Kobo progress back immediately")
void needsProgressSync_preventBounce() {
testSettings.setTwoWayProgressSync(true);
UserBookProgressEntity progress = createProgress(1L);
progress.setEpubProgress("epubcfi(/6/4)");
progress.setEpubProgressPercent(65f);
progress.setLastReadTime(Instant.now().minusSeconds(120));
progress.setKoboProgressSentTime(Instant.now().minusSeconds(60));
progress.setKoboProgressReceivedTime(Instant.now());
assertFalse(needsProgressSyncWebReader(progress));
}
}
private UserBookProgressEntity createProgress(Long bookId) {
BookEntity book = new BookEntity();
book.setId(bookId);
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setBook(book);
return progress;
}
private boolean needsStatusSync(UserBookProgressEntity progress) {
Instant modifiedTime = progress.getReadStatusModifiedTime();
if (modifiedTime == null) return false;
Instant sentTime = progress.getKoboStatusSentTime();
return sentTime == null || modifiedTime.isAfter(sentTime);
}
private boolean needsKoboProgressSync(UserBookProgressEntity progress) {
Instant sentTime = progress.getKoboProgressSentTime();
Instant receivedTime = progress.getKoboProgressReceivedTime();
return receivedTime != null && (sentTime == null || receivedTime.isAfter(sentTime));
}
private boolean needsProgressSync(UserBookProgressEntity progress) {
if (needsKoboProgressSync(progress)) return true;
if (testSettings.isTwoWayProgressSync()
&& progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null) {
Instant sentTime = progress.getKoboProgressSentTime();
Instant lastReadTime = progress.getLastReadTime();
if (lastReadTime != null && (sentTime == null || lastReadTime.isAfter(sentTime))) {
return true;
}
}
return false;
}
private boolean needsProgressSyncWebReader(UserBookProgressEntity progress) {
if (!testSettings.isTwoWayProgressSync()) return false;
if (progress.getEpubProgress() == null || progress.getEpubProgressPercent() == null) return false;
Instant lastReadTime = progress.getLastReadTime();
Instant sentTime = progress.getKoboProgressSentTime();
Instant receivedTime = progress.getKoboProgressReceivedTime();
if (lastReadTime == null) return false;
if (sentTime != null && !lastReadTime.isAfter(sentTime)) return false;
return receivedTime == null || lastReadTime.isAfter(receivedTime);
}
}
@@ -0,0 +1,80 @@
package org.booklore.service.kobo;
import org.booklore.service.book.BookService;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
@DisplayName("KoboThumbnailService Tests")
class KoboThumbnailServiceTest {
@Mock
private BookService bookService;
@InjectMocks
private KoboThumbnailService thumbnailService;
@Test
@DisplayName("Should return thumbnail with JPEG content type when image exists")
void getThumbnail_existingImage() {
String coverHash = "abc123hash";
Resource image = new ByteArrayResource(new byte[]{1, 2, 3}) {
@Override
public boolean exists() {
return true;
}
};
when(bookService.getBookCover(coverHash)).thenReturn(image);
ResponseEntity<Resource> response = thumbnailService.getThumbnail(coverHash);
assertEquals(200, response.getStatusCode().value());
assertEquals("image/jpeg", response.getHeaders().getFirst(HttpHeaders.CONTENT_TYPE));
assertNotNull(response.getBody());
}
@Test
@DisplayName("Should return 404 when image is null")
void getThumbnail_nullImage() {
when(bookService.getBookCover("nonexistent")).thenReturn(null);
ResponseEntity<Resource> response = thumbnailService.getThumbnail("nonexistent");
assertEquals(404, response.getStatusCode().value());
assertNull(response.getBody());
}
@Test
@DisplayName("Should return 404 when image does not exist")
void getThumbnail_imageNotExists() {
Resource image = mock(Resource.class);
when(image.exists()).thenReturn(false);
when(bookService.getBookCover("missing")).thenReturn(image);
ResponseEntity<Resource> response = thumbnailService.getThumbnail("missing");
assertEquals(404, response.getStatusCode().value());
}
@Test
@DisplayName("Should pass cover hash to book service")
void getThumbnail_passesCorrectHash() {
String coverHash = "unique-hash-456";
when(bookService.getBookCover(coverHash)).thenReturn(null);
thumbnailService.getThumbnail(coverHash);
verify(bookService).getBookCover(coverHash);
}
}