feat(kobo-sync): add user scoped 2 way kobo sync (#2452)

* fix(kobo-sync): Kobo reading state sync by returning the device expected shape and improve management with new DTOs and timestamp normalization

- Introduced `KoboReadingStateList` and `KoboReadingStateRequest` DTOs for improved handling of reading states.
- Updated `KoboController` to utilize the new DTOs and log request bodies.
- Enhanced `KoboReadingStateService` to normalize timestamps during reading state updates and merges.
- Adjusted repository queries to include user ID for better data integrity.
- Updated tests to reflect changes in DTOs and repository interactions.

* feat(kobo-sync): Enhance Kobo reading state management with user ID integration

* feat(kobo-sync): Add JSON annotations to KoboReadingStateList for improved serialization

* refactor(kobo-sync): Update repository and service methods to enhance reading state retrieval logic

- Replaced the existing method for fetching reading states with a new query that orders results by priority and timestamps.
- Updated service classes to utilize the new repository method for improved data handling.
- Adjusted unit tests to reflect changes in repository interactions.

* Enhance KoboReadingStateService and add database migration for user_id

- Added a new column `user_id` to the `kobo_reading_state` table with a foreign key constraint referencing the `users` table.
- Updated the `KoboReadingStateService` class by adding a new method to check for blank values, improving code readability and maintainability.
This commit is contained in:
Ben Szabo
2026-02-02 10:27:58 -07:00
committed by GitHub
parent cb5f703c7e
commit a77cecdf21
11 changed files with 478 additions and 52 deletions
@@ -5,12 +5,12 @@ import org.booklore.mapper.KoboReadingStateMapper;
import org.booklore.model.dto.BookLoreUser;
import org.booklore.model.dto.KoboSyncSettings;
import org.booklore.model.dto.kobo.KoboReadingState;
import org.booklore.model.dto.kobo.KoboReadingStateWrapper;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.model.entity.KoboReadingStateEntity;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.enums.ReadStatus;
import org.booklore.model.enums.KoboReadStatus;
import org.booklore.repository.BookRepository;
import org.booklore.repository.KoboReadingStateRepository;
import org.booklore.repository.UserBookProgressRepository;
@@ -30,6 +30,8 @@ import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
@@ -96,6 +98,12 @@ class KoboReadingStateServiceTest {
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
when(koboSettingsService.getCurrentUserSettings()).thenReturn(testSettings);
lenient().when(repository
.findFirstByEntitlementIdAndUserIdIsNullOrderByPriorityTimestampDescLastModifiedStringDescIdDesc(
anyString()))
.thenReturn(Optional.empty());
lenient().when(mapper.toJson(any())).thenCallRealMethod();
lenient().when(mapper.cleanString(any())).thenCallRealMethod();
}
@Test
@@ -124,7 +132,7 @@ class KoboReadingStateServiceTest {
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
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));
@@ -154,7 +162,7 @@ class KoboReadingStateServiceTest {
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(repository.save(any())).thenReturn(entity);
assertDoesNotThrow(() -> service.saveReadingState(List.of(readingState)));
@@ -175,7 +183,7 @@ class KoboReadingStateServiceTest {
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(repository.save(any())).thenReturn(entity);
when(bookRepository.findById(999L)).thenReturn(Optional.empty());
@@ -206,18 +214,17 @@ class KoboReadingStateServiceTest {
.build())
.build();
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
when(readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress)).thenReturn(expectedState);
KoboReadingStateWrapper result = service.getReadingState(entitlementId);
List<KoboReadingState> result = service.getReadingState(entitlementId);
assertNotNull(result);
assertNotNull(result.getReadingStates());
assertEquals(1, result.getReadingStates().size());
assertEquals(1, result.size());
KoboReadingState state = result.getReadingStates().getFirst();
KoboReadingState state = result.getFirst();
assertEquals(entitlementId, state.getEntitlementId());
assertNotNull(state.getCurrentBookmark());
assertEquals(75, state.getCurrentBookmark().getProgressPercent());
@@ -226,7 +233,7 @@ class KoboReadingStateServiceTest {
assertEquals("EpubCfi", state.getCurrentBookmark().getLocation().getType());
assertEquals("Kobo", state.getCurrentBookmark().getLocation().getSource());
verify(repository).findByEntitlementId(entitlementId);
verify(repository).findByEntitlementIdAndUserId(entitlementId, 1L);
verify(progressRepository).findByUserIdAndBookId(1L, 100L);
verify(readingStateBuilder).buildReadingStateFromProgress(entitlementId, progress);
}
@@ -239,14 +246,15 @@ class KoboReadingStateServiceTest {
progress.setKoboProgressPercent(null);
progress.setKoboLocation(null);
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
KoboReadingStateWrapper result = service.getReadingState(entitlementId);
List<KoboReadingState> result = service.getReadingState(entitlementId);
assertNull(result);
verify(repository).findByEntitlementId(entitlementId);
assertNotNull(result);
assertTrue(result.isEmpty());
verify(repository).findByEntitlementIdAndUserId(entitlementId, 1L);
verify(progressRepository).findByUserIdAndBookId(1L, 100L);
}
@@ -254,13 +262,14 @@ class KoboReadingStateServiceTest {
@DisplayName("Should return null when no Kobo state and no UserBookProgress exists")
void testGetReadingState_NoDataExists() {
String entitlementId = "100";
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.empty());
KoboReadingStateWrapper result = service.getReadingState(entitlementId);
List<KoboReadingState> result = service.getReadingState(entitlementId);
assertNull(result);
assertNotNull(result);
assertTrue(result.isEmpty());
verify(progressRepository).findByUserIdAndBookId(1L, 100L);
}
@@ -273,14 +282,14 @@ class KoboReadingStateServiceTest {
.build();
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.of(entity));
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.of(entity));
when(mapper.toDto(entity)).thenReturn(existingState);
KoboReadingStateWrapper result = service.getReadingState(entitlementId);
List<KoboReadingState> result = service.getReadingState(entitlementId);
assertNotNull(result);
assertEquals(1, result.getReadingStates().size());
assertEquals(entitlementId, result.getReadingStates().getFirst().getEntitlementId());
assertEquals(1, result.size());
assertEquals(entitlementId, result.getFirst().getEntitlementId());
verify(progressRepository, never()).findByUserIdAndBookId(anyLong(), anyLong());
}
@@ -296,7 +305,7 @@ class KoboReadingStateServiceTest {
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
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));
@@ -328,7 +337,7 @@ class KoboReadingStateServiceTest {
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
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));
@@ -342,4 +351,132 @@ class KoboReadingStateServiceTest {
UserBookProgressEntity savedProgress = progressCaptor.getValue();
assertNull(savedProgress.getKoboProgressPercent());
}
@Test
@DisplayName("Should merge per-field updates based on lastModified")
void testSaveReadingState_PerFieldMerge() throws Exception {
String entitlementId = "100";
String existingTimestamp = "2025-01-01T00:00:00.0000000Z";
String newerTimestamp = "2025-01-04T00:00:00.0000000Z";
String midTimestamp = "2025-01-03T00:00:00.0000000Z";
String olderTimestamp = "2025-01-02T00:00:00.0000000Z";
KoboReadingState.StatusInfo existingStatus = KoboReadingState.StatusInfo.builder()
.lastModified(existingTimestamp)
.status(KoboReadStatus.READING)
.timesStartedReading(1)
.build();
KoboReadingState.Statistics existingStats = KoboReadingState.Statistics.builder()
.lastModified(existingTimestamp)
.spentReadingMinutes(5)
.remainingTimeMinutes(20)
.build();
KoboReadingState.CurrentBookmark existingBookmark = KoboReadingState.CurrentBookmark.builder()
.lastModified(midTimestamp)
.progressPercent(25)
.build();
KoboReadingState existingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.created(existingTimestamp)
.lastModified(midTimestamp)
.statusInfo(existingStatus)
.statistics(existingStats)
.currentBookmark(existingBookmark)
.priorityTimestamp(midTimestamp)
.build();
KoboReadingState.StatusInfo incomingStatus = KoboReadingState.StatusInfo.builder()
.lastModified(newerTimestamp)
.status(KoboReadStatus.FINISHED)
.timesStartedReading(2)
.build();
KoboReadingState.CurrentBookmark incomingBookmark = KoboReadingState.CurrentBookmark.builder()
.lastModified(olderTimestamp)
.progressPercent(10)
.build();
KoboReadingState incomingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.lastModified(newerTimestamp)
.statusInfo(incomingStatus)
.currentBookmark(incomingBookmark)
.build();
KoboReadingStateEntity existingEntity = new KoboReadingStateEntity();
existingEntity.setEntitlementId(entitlementId);
existingEntity.setUserId(1L);
when(mapper.toDto(existingEntity)).thenReturn(existingState);
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.of(existingEntity));
when(repository.save(any())).thenAnswer(invocation -> invocation.getArgument(0));
ArgumentCaptor<KoboReadingStateEntity> entityCaptor = ArgumentCaptor.forClass(KoboReadingStateEntity.class);
service.saveReadingState(List.of(incomingState));
verify(repository).save(entityCaptor.capture());
KoboReadingStateEntity saved = entityCaptor.getValue();
ObjectMapper objectMapper = new ObjectMapper();
KoboReadingState.StatusInfo savedStatus = objectMapper.readValue(saved.getStatusInfoJson(), KoboReadingState.StatusInfo.class);
KoboReadingState.CurrentBookmark savedBookmark = objectMapper.readValue(saved.getCurrentBookmarkJson(), KoboReadingState.CurrentBookmark.class);
KoboReadingState.Statistics savedStatistics = objectMapper.readValue(saved.getStatisticsJson(), KoboReadingState.Statistics.class);
assertEquals(incomingStatus.getStatus(), savedStatus.getStatus());
assertEquals(existingBookmark.getProgressPercent(), savedBookmark.getProgressPercent());
assertEquals(existingStats.getSpentReadingMinutes(), savedStatistics.getSpentReadingMinutes());
assertEquals(newerTimestamp, saved.getLastModifiedString());
assertEquals(newerTimestamp, saved.getPriorityTimestamp());
}
@Test
@DisplayName("Should not update fields when timestamps are equal")
void testSaveReadingState_EqualTimestampNoUpdate() throws Exception {
String entitlementId = "100";
String timestamp = "2025-01-01T00:00:00.0000000Z";
KoboReadingState.StatusInfo existingStatus = KoboReadingState.StatusInfo.builder()
.lastModified(timestamp)
.status(KoboReadStatus.READING)
.timesStartedReading(1)
.build();
KoboReadingState existingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.created(timestamp)
.lastModified(timestamp)
.statusInfo(existingStatus)
.priorityTimestamp(timestamp)
.build();
KoboReadingState.StatusInfo incomingStatus = KoboReadingState.StatusInfo.builder()
.lastModified(timestamp)
.status(KoboReadStatus.FINISHED)
.timesStartedReading(2)
.build();
KoboReadingState incomingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.lastModified(timestamp)
.statusInfo(incomingStatus)
.build();
KoboReadingStateEntity existingEntity = new KoboReadingStateEntity();
existingEntity.setEntitlementId(entitlementId);
existingEntity.setUserId(1L);
when(mapper.toDto(existingEntity)).thenReturn(existingState);
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.of(existingEntity));
when(repository.save(any())).thenAnswer(invocation -> invocation.getArgument(0));
ArgumentCaptor<KoboReadingStateEntity> entityCaptor = ArgumentCaptor.forClass(KoboReadingStateEntity.class);
service.saveReadingState(List.of(incomingState));
verify(repository).save(entityCaptor.capture());
KoboReadingStateEntity saved = entityCaptor.getValue();
ObjectMapper objectMapper = new ObjectMapper();
KoboReadingState.StatusInfo savedStatus = objectMapper.readValue(saved.getStatusInfoJson(), KoboReadingState.StatusInfo.class);
assertEquals(existingStatus.getStatus(), savedStatus.getStatus());
assertEquals(timestamp, saved.getLastModifiedString());
}
}
@@ -86,13 +86,19 @@ class KoboStatusSyncProtectionTest {
when(koboSettingsService.getCurrentUserSettings()).thenReturn(testSettings);
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
when(userRepository.findById(1L)).thenReturn(Optional.of(testUserEntity));
lenient().when(repository
.findFirstByEntitlementIdAndUserIdIsNullOrderByPriorityTimestampDescLastModifiedStringDescIdDesc(
anyString()))
.thenReturn(Optional.empty());
lenient().when(mapper.toJson(any())).thenCallRealMethod();
lenient().when(mapper.cleanString(any())).thenCallRealMethod();
}
private void setupMocksForSave(String entitlementId, KoboReadingState readingState) {
KoboReadingStateEntity entity = new KoboReadingStateEntity();
when(mapper.toEntity(any())).thenReturn(entity);
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
when(repository.save(any())).thenReturn(entity);
}