chore: make two-way progress sync always-on (#2734)

This commit is contained in:
James Ward
2026-09-26 11:23:26 -04:00
committed by GitHub
parent 4923b62f88
commit 18b0c8cfbc
34 changed files with 54 additions and 470 deletions
@@ -71,7 +71,6 @@ public class KoreaderAuthFilter extends OncePerRequestFilter {
user.getUsername(),
user.getPasswordMD5(),
user.isSyncEnabled(),
user.isSyncWithWebReader(),
bookLoreUserId,
List.of(new SimpleGrantedAuthority("ROLE_USER"))
);
@@ -13,16 +13,13 @@ public class KoreaderUserDetails implements UserDetails {
@Getter
private final boolean syncEnabled;
@Getter
private final boolean syncWithWebReader;
@Getter
private final Long bookLoreUserId;
private final Collection<? extends GrantedAuthority> authorities;
public KoreaderUserDetails(String username, String password, boolean syncEnabled, boolean syncWithWebReader, Long bookLoreUserId, Collection<? extends GrantedAuthority> authorities) {
public KoreaderUserDetails(String username, String password, boolean syncEnabled, Long bookLoreUserId, Collection<? extends GrantedAuthority> authorities) {
this.username = username;
this.password = password;
this.syncEnabled = syncEnabled;
this.syncWithWebReader = syncWithWebReader;
this.bookLoreUserId = bookLoreUserId;
this.authorities = authorities;
}
@@ -50,27 +50,4 @@ public class KoreaderUserController {
koreaderUserService.toggleSync(enabled);
return ResponseEntity.noContent().build();
}
@Operation(summary = "Toggle sync progress with web reader", description = "Enable or disable syncing reading progress with the web reader.")
@ApiResponse(responseCode = "204", description = "Sync progress toggled successfully")
@PatchMapping("/me/sync-progress-with-grimmory")
@PreAuthorize("@securityUtil.canSyncKoReader() or @securityUtil.isAdmin()")
public ResponseEntity<Void> toggleSyncProgressWithWebReader(
@Parameter(description = "Enable or disable sync progress") @RequestParam boolean enabled) {
koreaderUserService.toggleSyncProgressWithWebReader(enabled);
return ResponseEntity.noContent().build();
}
@Operation(
summary = "[Deprecated] Toggle sync progress with web reader",
description = "Deprecated alias for /me/sync-progress-with-grimmory. Use the new endpoint; this one will be removed in a future release.",
deprecated = true)
@ApiResponse(responseCode = "204", description = "Sync progress toggled successfully")
@PatchMapping("/me/sync-progress-with-booklore")
@PreAuthorize("@securityUtil.canSyncKoReader() or @securityUtil.isAdmin()")
@Deprecated(forRemoval = true)
public ResponseEntity<Void> toggleSyncProgressWithBooklore(
@Parameter(description = "Enable or disable sync progress") @RequestParam boolean enabled) {
return toggleSyncProgressWithWebReader(enabled);
}
}
@@ -14,5 +14,4 @@ public class KoboSyncSettings {
private boolean autoAddToShelf;
private String hardcoverApiKey;
private boolean hardcoverSyncEnabled;
private boolean twoWayProgressSync;
}
@@ -12,5 +12,4 @@ public class KoreaderUser {
private String password;
private String passwordMD5;
private boolean syncEnabled;
private boolean syncWithWebReader;
}
@@ -44,8 +44,4 @@ public class KoboUserSettingsEntity {
@Column(name = "hardcover_sync_enabled")
@Builder.Default
private boolean hardcoverSyncEnabled = false;
@Column(name = "two_way_progress_sync")
@Builder.Default
private boolean twoWayProgressSync = false;
}
@@ -38,10 +38,6 @@ public class KoreaderUserEntity {
@Builder.Default
private boolean syncEnabled = false;
@Column(name = "sync_with_booklore_reader", nullable = false)
@Builder.Default
private boolean syncWithWebReader = false;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "booklore_user_id")
private BookLoreUserEntity bookLoreUser;
@@ -221,8 +221,7 @@ public class KoboEntitlementService {
Map<Long, KoboSpanPositionMap> preloadedMaps) {
String entitlementId = String.valueOf(progress.getBook().getId());
boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync();
KoboReadingState.CurrentBookmark bookmark = (progress.getKoboProgressPercent() != null || (twoWaySync && progress.getEpubProgressPercent() != null))
KoboReadingState.CurrentBookmark bookmark = (progress.getKoboProgressPercent() != null || (progress.getEpubProgressPercent() != null))
? readingStateBuilder.buildBookmarkFromProgress(progress, fileProgress, now, preloadedMaps)
: readingStateBuilder.buildEmptyBookmark(now);
@@ -259,21 +258,17 @@ public class KoboEntitlementService {
.findByUserIdAndBookIdForKoboSync(userId, book.getId());
UserBookFileProgressEntity fileProgress = findSyncedEpubFileProgress(userId, book).orElse(null);
boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync();
KoboReadingState.CurrentBookmark webReaderBookmark = twoWaySync
? userProgress
KoboReadingState.CurrentBookmark webReaderBookmark = userProgress
.filter(readingStateBuilder::shouldUseWebReaderProgress)
.map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, fileProgress, now))
.orElse(null)
: null;
.orElse(null);
KoboReadingState.CurrentBookmark bookmark = webReaderBookmark != null
? webReaderBookmark
: existingState != null && existingState.getCurrentBookmark() != null
? existingState.getCurrentBookmark()
: userProgress
.filter(progress -> progress.getKoboProgressPercent() != null || (twoWaySync && progress.getEpubProgressPercent() != null))
.filter(progress -> progress.getKoboProgressPercent() != null || (progress.getEpubProgressPercent() != null))
.map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, fileProgress, now))
.orElseGet(() -> readingStateBuilder.buildEmptyBookmark(now));
@@ -38,7 +38,6 @@ public class KoboLibrarySyncService {
private final UserBookProgressRepository userBookProgressRepository;
private final KoboServerProxy koboServerProxy;
private final ObjectMapper objectMapper;
private final KoboSettingsService koboSettingsService;
private final AppSettingService appSettingService;
private Collection<Entitlement> getEntitlementsFromKoboStoreResponse(ResponseEntity<JsonNode> koboStoreResponse) {
@@ -182,12 +181,6 @@ public class KoboLibrarySyncService {
List<UserBookProgressEntity> booksNeedingSync =
userBookProgressRepository.findAllBooksNeedingKoboSync(userId, snapshotId);
if (!koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()) {
booksNeedingSync = booksNeedingSync.stream()
.filter(p -> needsStatusSync(p) || needsKoboProgressSync(p))
.toList();
}
if (booksNeedingSync.isEmpty()) {
return Collections.emptyList();
}
@@ -229,8 +222,7 @@ public class KoboLibrarySyncService {
return true;
}
if (koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()
&& progress.getEpubProgressPercent() != null) {
if (progress.getEpubProgressPercent() != null) {
Instant sentTime = progress.getKoboProgressSentTime();
Instant lastReadTime = progress.getLastReadTime();
if (lastReadTime != null && (sentTime == null || lastReadTime.isAfter(sentTime))) {
@@ -55,9 +55,6 @@ public class KoboReadingStateBuilder {
}
public boolean shouldUseWebReaderProgress(UserBookProgressEntity progress) {
if (!koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()) {
return false;
}
if (progress.getEpubProgressPercent() == null) {
return false;
}
@@ -151,9 +151,6 @@ public class KoboReadingStateService {
}
private void overlayWebReaderBookmark(KoboReadingState state, String entitlementId, Long userId) {
if (!koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()) {
return;
}
try {
Long bookId = Long.parseLong(entitlementId);
UserBookFileProgressEntity fileProgress = findSyncedEpubFileProgress(userId, bookId).orElse(null);
@@ -171,9 +168,8 @@ public class KoboReadingStateService {
Long bookId = Long.parseLong(entitlementId);
BookLoreUser user = authenticationService.getAuthenticatedUser();
boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync();
return progressRepository.findByUserIdAndBookIdForKoboSync(user.getId(), bookId)
.filter(progress -> progress.getKoboProgressPercent() != null || progress.getKoboLocation() != null || (twoWaySync && progress.getEpubProgressPercent() != null))
.filter(progress -> progress.getKoboProgressPercent() != null || progress.getKoboLocation() != null || (progress.getEpubProgressPercent() != null))
.map(progress -> readingStateBuilder.buildReadingStateFromProgress(
entitlementId,
progress,
@@ -271,10 +267,6 @@ public class KoboReadingStateService {
return false;
}
if (!koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()) {
return false;
}
boolean webReaderIsNewer = existingFileProgress != null
&& existingFileProgress.getLastReadTime() != null
&& bookmarkTime != null
@@ -326,7 +318,7 @@ public class KoboReadingStateService {
}
private boolean isWebReaderNewerThanBookmark(UserBookFileProgressEntity fileProgress, Instant bookmarkTime) {
if (bookmarkTime == null || !koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()) {
if (bookmarkTime == null) {
return false;
}
return fileProgress != null
@@ -84,7 +84,6 @@ public class KoboSettingsService {
}
entity.setAutoAddToShelf(settings.isAutoAddToShelf());
entity.setTwoWayProgressSync(settings.isTwoWayProgressSync());
repository.save(entity);
return mapToDto(entity, hardcoverSyncSettingsService.getSettingsForUserId(user.getId()));
@@ -131,7 +130,6 @@ public class KoboSettingsService {
dto.setProgressMarkAsReadingThreshold(entity.getProgressMarkAsReadingThreshold());
dto.setProgressMarkAsFinishedThreshold(entity.getProgressMarkAsFinishedThreshold());
dto.setAutoAddToShelf(entity.isAutoAddToShelf());
dto.setTwoWayProgressSync(entity.isTwoWayProgressSync());
if (hardcoverSettings != null) {
dto.setHardcoverApiKey(hardcoverSettings.getHardcoverApiKey());
dto.setHardcoverSyncEnabled(hardcoverSettings.isHardcoverSyncEnabled());
@@ -85,7 +85,7 @@ public class KoreaderService {
UserBookProgressEntity userProgress = getOrCreateUserProgress(user, book);
Float previousProgressPercent = userProgress.getKoreaderProgressPercent();
ReadStatus previousReadStatus = userProgress.getReadStatus();
updateProgressData(userProgress, koProgress, authDetails.isSyncWithWebReader(), book);
updateProgressData(userProgress, koProgress, book);
progressRepository.save(userProgress);
@@ -108,7 +108,6 @@ public class KoreaderService {
try {
koreaderUserRepository.findByBookLoreUserId(userId)
.filter(KoreaderUserEntity::isSyncEnabled)
.filter(KoreaderUserEntity::isSyncWithWebReader)
.ifPresent(koreaderUser -> {
BookEntity book = bookRepository.findById(bookId).orElse(null);
BookLoreUserEntity user = userRepository.findById(userId).orElse(null);
@@ -183,14 +182,14 @@ public class KoreaderService {
}
}
private void updateProgressData(UserBookProgressEntity userProgress, KoreaderProgress koProgress, boolean syncWithWebReader, BookEntity book) {
private void updateProgressData(UserBookProgressEntity userProgress, KoreaderProgress koProgress, BookEntity book) {
userProgress.setKoreaderProgress(koProgress.getProgress());
userProgress.setKoreaderProgressPercent(koProgress.getPercentage());
userProgress.setKoreaderDevice(koProgress.getDevice());
userProgress.setKoreaderDeviceId(koProgress.getDevice_id());
userProgress.setKoreaderLastSyncTime(Instant.now());
userProgress.setLastReadTime(Instant.now());
if (syncWithWebReader && koProgress.getProgress() != null) {
if (koProgress.getProgress() != null) {
try {
String cfi = epubCfiService.convertXPointerToCfi(book.getFullFilePath(), koProgress.getProgress());
@@ -70,13 +70,4 @@ public class KoreaderUserService {
user.setSyncEnabled(enabled);
koreaderUserRepository.save(user);
}
@Transactional
public void toggleSyncProgressWithWebReader(boolean enabled) {
Long id = authService.getAuthenticatedUser().getId();
KoreaderUserEntity user = koreaderUserRepository.findByBookLoreUserId(id)
.orElseThrow(() -> ApiError.GENERIC_NOT_FOUND.createException("Koreader user not found for BookLore user ID: " + id));
user.setSyncWithWebReader(enabled);
koreaderUserRepository.save(user);
}
}
@@ -0,0 +1,3 @@
ALTER TABLE koreader_user DROP COLUMN sync_with_booklore_reader;
ALTER TABLE kobo_user_settings DROP COLUMN two_way_progress_sync;
@@ -30,7 +30,7 @@ class KoreaderUserControllerTest {
@BeforeEach
void setUp() {
try (AutoCloseable mocks = MockitoAnnotations.openMocks(this)) {
user = new KoreaderUser(1L, "testuser", "pass", "md5", true, true);
user = new KoreaderUser(1L, "testuser", "pass", "md5", true);
} catch (Exception e) {
throw new RuntimeException(e);
}
@@ -60,20 +60,4 @@ class KoreaderUserControllerTest {
assertEquals(HttpStatus.NO_CONTENT, resp.getStatusCode());
assertNull(resp.getBody());
}
@Test
void toggleSyncProgressWithWebReader_returnsNoContent() {
doNothing().when(koreaderUserService).toggleSyncProgressWithWebReader(true);
ResponseEntity<Void> resp = controller.toggleSyncProgressWithWebReader(true);
assertEquals(HttpStatus.NO_CONTENT, resp.getStatusCode());
assertNull(resp.getBody());
}
@Test
void toggleSyncProgressWithBooklore_delegatesToWebReader_andReturnsNoContent() {
doNothing().when(koreaderUserService).toggleSyncProgressWithWebReader(true);
ResponseEntity<Void> resp = controller.toggleSyncProgressWithBooklore(true);
assertEquals(HttpStatus.NO_CONTENT, resp.getStatusCode());
assertNull(resp.getBody());
}
}
@@ -611,7 +611,6 @@ class KoboEntitlementServiceTest {
.build();
KoboSyncSettings settings = new KoboSyncSettings();
settings.setTwoWayProgressSync(true);
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
when(koboCompatibilityService.isBookSupportedForKobo(book)).thenReturn(true);
@@ -674,7 +673,6 @@ class KoboEntitlementServiceTest {
KoboReadingStateEntity existingEntity = new KoboReadingStateEntity();
KoboSyncSettings settings = new KoboSyncSettings();
settings.setTwoWayProgressSync(true);
when(bookQueryService.findAllWithMetadataByIds(Set.of(1L))).thenReturn(List.of(book));
when(koboCompatibilityService.isBookSupportedForKobo(book)).thenReturn(true);
@@ -775,7 +773,6 @@ class KoboEntitlementServiceTest {
progress.setReadStatus(ReadStatus.READING);
KoboSyncSettings settings = new KoboSyncSettings();
settings.setTwoWayProgressSync(true);
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
UserBookFileProgressEntity fileProgress = new UserBookFileProgressEntity();
@@ -830,7 +827,6 @@ class KoboEntitlementServiceTest {
progress.setReadStatus(ReadStatus.READING);
KoboSyncSettings settings = new KoboSyncSettings();
settings.setTwoWayProgressSync(true);
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
UserBookFileProgressEntity epubFileProgress = new UserBookFileProgressEntity();
@@ -891,7 +887,7 @@ class KoboEntitlementServiceTest {
}
@Test
@DisplayName("Should include epub progress in bookmark when two-way sync ON")
@DisplayName("Should include epub progress in bookmark")
void generateChangedReadingStates_twoWaySync() {
BookEntity book = new BookEntity();
book.setId(1L);
@@ -902,7 +898,6 @@ class KoboEntitlementServiceTest {
progress.setReadStatus(ReadStatus.READING);
KoboSyncSettings settings = new KoboSyncSettings();
settings.setTwoWayProgressSync(true);
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
@@ -922,35 +917,5 @@ class KoboEntitlementServiceTest {
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));
}
}
}
@@ -49,7 +49,6 @@ class KoboReadingStateBuilderTest {
@BeforeEach
void setUp() {
KoboSyncSettings settings = new KoboSyncSettings();
settings.setTwoWayProgressSync(true);
when(koboSettingsService.getCurrentUserSettings()).thenReturn(settings);
when(bookmarkLocationResolver.resolve(any(), any(), any())).thenReturn(Optional.empty());
builder = new KoboReadingStateBuilder(koboSettingsService, bookmarkLocationResolver);
@@ -581,9 +581,8 @@ class KoboReadingStateServiceTest {
}
@Test
@DisplayName("Should overlay web reader bookmark when two-way sync is ON and web reader data exists")
@DisplayName("Should overlay web reader bookmark when web reader data exists")
void testGetReadingState_overlayWebReaderBookmark() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
BookFileEntity primaryFile = setPrimaryEpub(10L);
@@ -629,35 +628,9 @@ class KoboReadingStateServiceTest {
assertNull(bookmark.getLocation());
}
@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(), any());
}
@Test
@DisplayName("Should overlay web reader location when available")
void testGetReadingState_overlayWebReaderBookmark_replacesLocation() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
BookFileEntity primaryFile = setPrimaryEpub(10L);
@@ -716,7 +689,6 @@ class KoboReadingStateServiceTest {
@Test
@DisplayName("Should keep stored Kobo bookmark when mirrored EPUB progress is not newer")
void testGetReadingState_preservesStoredKoboBookmarkWhenKoboIsFreshest() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
BookFileEntity primaryFile = setPrimaryEpub(10L);
@@ -767,9 +739,8 @@ class KoboReadingStateServiceTest {
}
@Test
@DisplayName("Should cross-populate chapter-aware EPUB fields from Kobo when two-way sync is ON")
@DisplayName("Should cross-populate chapter-aware EPUB fields from Kobo")
void testSyncKoboProgress_crossPopulateEpubFields() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
BookFileEntity primaryFile = setPrimaryEpub(10L);
@@ -830,48 +801,9 @@ class KoboReadingStateServiceTest {
assertEquals(Instant.parse("2025-06-15T12:00:00Z"), savedFileProgress.getLastReadTime());
}
@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 clear stale EPUB CFI but keep chapter source when Kobo sends newer KoboSpan")
void testSyncKoboProgress_clearEpubCfiWhenKoboSendsKoboSpan() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
BookFileEntity primaryFile = setPrimaryEpub(10L);
@@ -938,7 +870,6 @@ class KoboReadingStateServiceTest {
@Test
@DisplayName("Should clear stale chapter progress when Kobo bookmark omits content source progress")
void testSyncKoboProgress_clearStaleContentSourceProgressPercent() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
BookFileEntity primaryFile = setPrimaryEpub(10L);
@@ -993,7 +924,6 @@ class KoboReadingStateServiceTest {
@Test
@DisplayName("Should not cross-populate when web reader has newer progress")
void testSyncKoboProgress_skipCrossPopulateWhenWebReaderNewer() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
BookFileEntity primaryFile = setPrimaryEpub(10L);
@@ -1040,9 +970,8 @@ class KoboReadingStateServiceTest {
}
@Test
@DisplayName("Should construct reading state from web reader progress when toggle ON and no Kobo data")
@DisplayName("Should construct reading state from web reader progress when no Kobo data")
void testGetReadingState_constructFromWebReaderProgress_whenToggleOn() {
testSettings.setTwoWayProgressSync(true);
String entitlementId = "100";
UserBookProgressEntity progress = new UserBookProgressEntity();
@@ -1080,26 +1009,6 @@ class KoboReadingStateServiceTest {
verify(readingStateBuilder).buildReadingStateFromProgress(entitlementId, progress, fileProgress);
}
@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(), any());
}
@Test
@DisplayName("Should sync location data from Kobo bookmark")
void testSyncKoboProgress_locationData() {
@@ -346,7 +346,7 @@ class KoreaderServiceTest {
BookLoreUserEntity user = user(42L);
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setEpubProgress("epubcfi(/6/8!/4/2/6)");
when(koreaderUserRepo.findByBookLoreUserId(42L)).thenReturn(Optional.of(koreaderUser(true, true)));
when(koreaderUserRepo.findByBookLoreUserId(42L)).thenReturn(Optional.of(koreaderUser(true)));
when(bookRepo.findById(11L)).thenReturn(Optional.of(book));
when(userRepo.findById(42L)).thenReturn(Optional.of(user));
when(progressRepo.findByUserIdAndBookId(42L, 11L)).thenReturn(Optional.of(progress));
@@ -369,7 +369,7 @@ class KoreaderServiceTest {
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setEpubProgress("epubcfi(/6/8!/4/2/6)");
progress.setKoreaderProgress("/old/xpointer");
when(koreaderUserRepo.findByBookLoreUserId(42L)).thenReturn(Optional.of(koreaderUser(true, true)));
when(koreaderUserRepo.findByBookLoreUserId(42L)).thenReturn(Optional.of(koreaderUser(true)));
when(bookRepo.findById(11L)).thenReturn(Optional.of(book));
when(userRepo.findById(42L)).thenReturn(Optional.of(user));
when(progressRepo.findByUserIdAndBookId(42L, 11L)).thenReturn(Optional.of(progress));
@@ -387,17 +387,7 @@ class KoreaderServiceTest {
@Test
void syncProgressToKoreader_whenGlobalSyncDisabled_skipsUpdate() {
when(koreaderUserRepo.findByBookLoreUserId(42L)).thenReturn(Optional.of(koreaderUser(false, true)));
service.syncProgressToKoreader(11L, 75f, 42L);
verifyNoInteractions(bookRepo, userRepo, epubCfiService);
verify(progressRepo, never()).save(any());
}
@Test
void syncProgressToKoreader_whenWebReaderSyncDisabled_skipsUpdate() {
when(koreaderUserRepo.findByBookLoreUserId(42L)).thenReturn(Optional.of(koreaderUser(true, false)));
when(koreaderUserRepo.findByBookLoreUserId(42L)).thenReturn(Optional.of(koreaderUser(false)));
service.syncProgressToKoreader(11L, 75f, 42L);
@@ -407,7 +397,7 @@ class KoreaderServiceTest {
@Test
void syncProgressToKoreader_whenBookOrUserMissing_logsAndSkipsSave() {
when(koreaderUserRepo.findByBookLoreUserId(42L)).thenReturn(Optional.of(koreaderUser(true, true)));
when(koreaderUserRepo.findByBookLoreUserId(42L)).thenReturn(Optional.of(koreaderUser(true)));
when(bookRepo.findById(11L)).thenReturn(Optional.empty());
when(userRepo.findById(42L)).thenReturn(Optional.of(user(42L)));
@@ -423,7 +413,7 @@ class KoreaderServiceTest {
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setEpubProgress("epubcfi(/6/8!/4/2/6)");
progress.setKoreaderProgress("/old/xpointer");
when(koreaderUserRepo.findByBookLoreUserId(42L)).thenReturn(Optional.of(koreaderUser(true, true)));
when(koreaderUserRepo.findByBookLoreUserId(42L)).thenReturn(Optional.of(koreaderUser(true)));
when(bookRepo.findById(11L)).thenReturn(Optional.of(book));
when(userRepo.findById(42L)).thenReturn(Optional.of(user));
when(progressRepo.findByUserIdAndBookId(42L, 11L)).thenReturn(Optional.of(progress));
@@ -444,7 +434,7 @@ class KoreaderServiceTest {
UserBookProgressEntity progress = new UserBookProgressEntity();
progress.setKoreaderDeviceId("EXAMPLE-ID");
progress.setKoreaderDevice("EXAMPLE-DEVICE");
when(koreaderUserRepo.findByBookLoreUserId(42L)).thenReturn(Optional.of(koreaderUser(true, true)));
when(koreaderUserRepo.findByBookLoreUserId(42L)).thenReturn(Optional.of(koreaderUser(true)));
when(bookRepo.findById(11L)).thenReturn(Optional.of(book));
when(userRepo.findById(42L)).thenReturn(Optional.of(user));
when(progressRepo.findByUserIdAndBookId(42L, 11L)).thenReturn(Optional.of(progress));
@@ -467,10 +457,9 @@ class KoreaderServiceTest {
assertEquals(42.0f, (Float) method.invoke(service, 42.0f));
}
private KoreaderUserEntity koreaderUser(boolean syncEnabled, boolean syncWithWebReader) {
private KoreaderUserEntity koreaderUser(boolean syncEnabled) {
return KoreaderUserEntity.builder()
.syncEnabled(syncEnabled)
.syncWithWebReader(syncWithWebReader)
.build();
}
@@ -55,7 +55,7 @@ class KoreaderUserServiceTest {
entity.setBookLoreUser(ownerEntity);
entity.setUsername("kvUser");
dto = new KoreaderUser(10L, "kvUser", null, null, false, true);
dto = new KoreaderUser(10L, "kvUser", null, null, false);
when(koreaderUserMapper.toDto(any(KoreaderUserEntity.class))).thenReturn(dto);
}
@@ -71,7 +71,7 @@ class KoreaderUserServiceTest {
when(koreaderUserMapper.toDto(any(KoreaderUserEntity.class))).thenAnswer(invocation -> {
KoreaderUserEntity u = invocation.getArgument(0);
return new KoreaderUser(u.getId(), u.getUsername(), u.getPassword(), u.getPasswordMD5(), u.isSyncEnabled(), u.isSyncWithWebReader());
return new KoreaderUser(u.getId(), u.getUsername(), u.getPassword(), u.getPasswordMD5(), u.isSyncEnabled());
});
KoreaderUser result = service.upsertUser("userA", "passA");
@@ -1,11 +1,8 @@
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;
@@ -22,7 +19,6 @@ 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.*;
@@ -57,72 +53,9 @@ class KoboLibrarySyncServiceTest {
@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 {
@@ -212,14 +145,12 @@ class KoboLibrarySyncServiceTest {
}
@Nested
@DisplayName("Web Reader Progress Sync (Two-Way)")
@DisplayName("Web Reader Progress Sync")
class WebReaderProgressSync {
@Test
@DisplayName("Should detect web reader progress needing sync when toggle ON and lastReadTime after sent")
@DisplayName("Should detect web reader progress needing sync when lastReadTime after sent")
void needsProgressSync_webReaderNewer() {
testSettings.setTwoWayProgressSync(true);
UserBookProgressEntity progress = createProgress(1L);
progress.setEpubProgress("epubcfi(/6/4)");
progress.setEpubProgressPercent(65f);
@@ -231,10 +162,8 @@ class KoboLibrarySyncServiceTest {
}
@Test
@DisplayName("Should detect href-only web reader progress when toggle ON and lastReadTime after sent")
@DisplayName("Should detect href-only web reader progress when lastReadTime after sent")
void needsProgressSync_webReaderHrefOnly() {
testSettings.setTwoWayProgressSync(true);
UserBookProgressEntity progress = createProgress(1L);
progress.setEpubProgressHref("OPS/chapter3.xhtml");
progress.setEpubProgressPercent(65f);
@@ -245,26 +174,9 @@ class KoboLibrarySyncServiceTest {
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);
@@ -300,8 +212,7 @@ class KoboLibrarySyncServiceTest {
private boolean needsProgressSync(UserBookProgressEntity progress) {
if (needsKoboProgressSync(progress)) return true;
if (testSettings.isTwoWayProgressSync()
&& progress.getEpubProgressPercent() != null) {
if (progress.getEpubProgressPercent() != null) {
Instant sentTime = progress.getKoboProgressSentTime();
Instant lastReadTime = progress.getLastReadTime();
if (lastReadTime != null && (sentTime == null || lastReadTime.isAfter(sentTime))) {
@@ -312,7 +223,6 @@ class KoboLibrarySyncServiceTest {
}
private boolean needsProgressSyncWebReader(UserBookProgressEntity progress) {
if (!testSettings.isTwoWayProgressSync()) return false;
if (progress.getEpubProgress() == null || progress.getEpubProgressPercent() == null) return false;
Instant lastReadTime = progress.getLastReadTime();