fix(koreader): fix bidirectional progress sync (#1687)

Co-authored-by: Wesam Jabali <wesamjabali@icloud.com>
This commit is contained in:
Zach
2026-06-09 21:00:25 -04:00
committed by GitHub
co-authored by Wesam Jabali
parent 46f4457fee
commit 590bd9eea5
7 changed files with 302 additions and 0 deletions
@@ -17,6 +17,7 @@ import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.enums.ReadStatus;
import org.booklore.repository.*;
import org.booklore.service.hardcover.HardcoverSyncService;
import org.booklore.service.koreader.KoreaderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -56,6 +57,7 @@ public class KoboReadingStateService {
private final KoboSettingsService koboSettingsService;
private final KoboReadingStateBuilder readingStateBuilder;
private final HardcoverSyncService hardcoverSyncService;
private final KoreaderService koreaderService;
@Transactional
public KoboReadingStateResponse saveReadingState(List<KoboReadingState> readingStates) {
@@ -251,6 +253,7 @@ public class KoboReadingStateService {
&& progress.getKoboProgressPercent() != null
&& (!progress.getKoboProgressPercent().equals(previousKoboProgressPercent)
|| progress.getReadStatus() != previousReadStatus)) {
koreaderService.syncProgressToKoreader(book.getId(), progress.getKoboProgressPercent(), userId);
hardcoverSyncService.syncProgressToHardcover(book.getId(), progress.getKoboProgressPercent(), userId);
}
} catch (NumberFormatException e) {
@@ -6,6 +6,7 @@ import org.booklore.config.security.userdetails.KoreaderUserDetails;
import org.booklore.exception.ApiError;
import org.booklore.model.dto.progress.KoreaderProgress;
import org.booklore.model.entity.*;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.ReadStatus;
import org.booklore.repository.*;
import org.booklore.service.hardcover.HardcoverSyncService;
@@ -92,6 +93,47 @@ public class KoreaderService {
}
}
@Transactional
public void syncProgressToKoreader(long bookId, float percentage, long userId) {
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);
if (book == null || user == null) {
log.warn("KOReader sync skipped: bookId={} or userId={} was not found", bookId, userId);
return;
}
UserBookProgressEntity progress = getOrCreateUserProgress(user, book);
float koreaderPercent = percentage / 100.0f;
progress.setKoreaderProgressPercent(koreaderPercent);
progress.setKoreaderLastSyncTime(Instant.now());
progress.setKoreaderProgress(null);
BookFileEntity primaryFile = book.getPrimaryBookFile();
if (primaryFile != null && primaryFile.getBookType() == BookFileType.EPUB
&& progress.getEpubProgress() != null) {
try {
String xpointer = epubCfiService.convertCfiToProgressXPointer(
primaryFile.getFullFilePath(), progress.getEpubProgress());
progress.setKoreaderProgress(xpointer);
} catch (Exception e) {
progress.setKoreaderProgress(null);
log.warn("Failed to convert CFI to XPointer for KOReader sync", e);
}
}
progressRepository.save(progress);
});
} catch (Exception e) {
log.warn("Failed to sync progress to KOReader for userId={} bookId={}", userId, bookId, e);
}
}
private void saveToFileProgress(BookLoreUserEntity user, BookEntity book, UserBookProgressEntity progress) {
try {
BookFileEntity primaryFile = book.getPrimaryBookFile();
@@ -20,6 +20,7 @@ import org.booklore.model.enums.UserPermission;
import org.booklore.repository.*;
import org.booklore.service.hardcover.HardcoverSyncService;
import org.booklore.service.kobo.KoboReadingStateService;
import org.booklore.service.koreader.KoreaderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
@@ -46,6 +47,7 @@ public class ReadingProgressService {
private final UserRepository userRepository;
private final AuthenticationService authenticationService;
private final KoboReadingStateService koboReadingStateService;
private final KoreaderService koreaderService;
private final HardcoverSyncService hardcoverSyncService;
// ==================== Methods from UserProgressService ====================
@@ -270,6 +272,7 @@ public class ReadingProgressService {
userBookProgressRepository.save(progress);
if (percentage != null) {
koreaderService.syncProgressToKoreader(book.getId(), percentage, user.getId());
hardcoverSyncService.syncProgressToHardcover(book.getId(), percentage, user.getId());
}
}
@@ -20,6 +20,7 @@ import org.booklore.service.hardcover.HardcoverSyncService;
import org.booklore.service.kobo.KoboReadingStateBuilder;
import org.booklore.service.kobo.KoboReadingStateService;
import org.booklore.service.kobo.KoboSettingsService;
import org.booklore.service.koreader.KoreaderService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@@ -74,6 +75,9 @@ class KoboReadingStateServiceTest {
@Mock
private HardcoverSyncService hardcoverSyncService;
@Mock
private KoreaderService koreaderService;
@Mock
private UserBookFileProgressRepository fileProgressRepository;
@@ -1229,6 +1233,7 @@ class KoboReadingStateServiceTest {
service.saveReadingState(List.of(readingState));
verify(koreaderService).syncProgressToKoreader(eq(100L), eq(50f), eq(1L));
verify(hardcoverSyncService).syncProgressToHardcover(eq(100L), eq(50f), eq(1L));
}
@@ -18,6 +18,7 @@ import org.booklore.service.hardcover.HardcoverSyncService;
import org.booklore.service.kobo.KoboReadingStateBuilder;
import org.booklore.service.kobo.KoboReadingStateService;
import org.booklore.service.kobo.KoboSettingsService;
import org.booklore.service.koreader.KoreaderService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
@@ -62,6 +63,9 @@ class KoboStatusSyncProtectionTest {
@Mock
private HardcoverSyncService hardcoverSyncService;
@Mock
private KoreaderService koreaderService;
@InjectMocks
private KoboReadingStateService service;
@@ -8,16 +8,21 @@ import org.booklore.config.security.userdetails.KoreaderUserDetails;
import org.booklore.exception.APIException;
import org.booklore.model.dto.progress.KoreaderProgress;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookFileEntity;
import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.model.entity.KoreaderUserEntity;
import org.booklore.model.entity.LibraryPathEntity;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.enums.BookFileType;
import org.booklore.model.enums.ReadStatus;
import org.booklore.repository.BookRepository;
import org.booklore.repository.UserBookFileProgressRepository;
import org.booklore.repository.UserBookProgressRepository;
import org.booklore.repository.UserRepository;
import org.booklore.repository.KoreaderUserRepository;
import org.booklore.service.hardcover.HardcoverSyncService;
import org.booklore.service.koreader.KoreaderService;
import org.booklore.util.koreader.EpubCfiService;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.*;
@@ -29,7 +34,9 @@ import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.*;
import java.lang.reflect.Method;
import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -40,6 +47,8 @@ class KoreaderServiceTest {
@Mock
UserBookProgressRepository progressRepo;
@Mock
UserBookFileProgressRepository fileProgressRepo;
@Mock
BookRepository bookRepo;
@Mock
UserRepository userRepo;
@@ -47,6 +56,8 @@ class KoreaderServiceTest {
KoreaderUserRepository koreaderUserRepo;
@Mock
HardcoverSyncService hardcoverSyncService;
@Mock
EpubCfiService epubCfiService;
@InjectMocks
KoreaderService service;
@@ -265,6 +276,103 @@ class KoreaderServiceTest {
assertThrows(APIException.class, () -> service.saveProgress("h", dto));
}
@Test
void syncProgressToKoreader_whenEnabled_updatesPercentAndXPointer() {
BookEntity book = epubBook(11L);
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(bookRepo.findById(11L)).thenReturn(Optional.of(book));
when(userRepo.findById(42L)).thenReturn(Optional.of(user));
when(progressRepo.findByUserIdAndBookId(42L, 11L)).thenReturn(Optional.of(progress));
when(epubCfiService.convertCfiToProgressXPointer(any(Path.class), eq("epubcfi(/6/8!/4/2/6)")))
.thenReturn("/6/8!/4/2/6/1:15");
service.syncProgressToKoreader(11L, 75f, 42L);
assertEquals(0.75f, progress.getKoreaderProgressPercent());
assertEquals("/6/8!/4/2/6/1:15", progress.getKoreaderProgress());
assertNotNull(progress.getKoreaderLastSyncTime());
verify(progressRepo).save(progress);
verify(epubCfiService).convertCfiToProgressXPointer(any(Path.class), eq("epubcfi(/6/8!/4/2/6)"));
}
@Test
void syncProgressToKoreader_whenConversionFails_clearsStaleXPointerButKeepsPercent() {
BookEntity book = epubBook(11L);
BookLoreUserEntity user = user(42L);
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(bookRepo.findById(11L)).thenReturn(Optional.of(book));
when(userRepo.findById(42L)).thenReturn(Optional.of(user));
when(progressRepo.findByUserIdAndBookId(42L, 11L)).thenReturn(Optional.of(progress));
when(epubCfiService.convertCfiToProgressXPointer(any(Path.class), eq("epubcfi(/6/8!/4/2/6)")))
.thenThrow(new RuntimeException("conversion failed"));
service.syncProgressToKoreader(11L, 100f, 42L);
assertEquals(1.0f, progress.getKoreaderProgressPercent());
assertNull(progress.getKoreaderProgress());
assertNotNull(progress.getKoreaderLastSyncTime());
verify(progressRepo).save(progress);
verify(epubCfiService).convertCfiToProgressXPointer(any(Path.class), eq("epubcfi(/6/8!/4/2/6)"));
}
@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)));
service.syncProgressToKoreader(11L, 75f, 42L);
verifyNoInteractions(bookRepo, userRepo, epubCfiService);
verify(progressRepo, never()).save(any());
}
@Test
void syncProgressToKoreader_whenBookOrUserMissing_logsAndSkipsSave() {
when(koreaderUserRepo.findByBookLoreUserId(42L)).thenReturn(Optional.of(koreaderUser(true, true)));
when(bookRepo.findById(11L)).thenReturn(Optional.empty());
when(userRepo.findById(42L)).thenReturn(Optional.of(user(42L)));
assertDoesNotThrow(() -> service.syncProgressToKoreader(11L, 75f, 42L));
verify(progressRepo, never()).save(any());
}
@Test
void syncProgressToKoreader_whenNotEpub_clearsStaleXPointer() {
BookEntity book = bookWithPrimaryFile(11L, BookFileType.PDF);
BookLoreUserEntity user = user(42L);
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(bookRepo.findById(11L)).thenReturn(Optional.of(book));
when(userRepo.findById(42L)).thenReturn(Optional.of(user));
when(progressRepo.findByUserIdAndBookId(42L, 11L)).thenReturn(Optional.of(progress));
service.syncProgressToKoreader(11L, 50f, 42L);
assertEquals(0.5f, progress.getKoreaderProgressPercent());
assertNull(progress.getKoreaderProgress());
assertNotNull(progress.getKoreaderLastSyncTime());
verifyNoInteractions(epubCfiService);
verify(progressRepo).save(progress);
}
@Test
void normalizeProgressPercent_handlesNullAndRanges() throws Exception {
Method method = KoreaderService.class.getDeclaredMethod("normalizeProgressPercent", Float.class);
@@ -275,4 +383,38 @@ class KoreaderServiceTest {
assertEquals(100.0f, (Float) method.invoke(service, 1.0f));
assertEquals(42.0f, (Float) method.invoke(service, 42.0f));
}
private KoreaderUserEntity koreaderUser(boolean syncEnabled, boolean syncWithWebReader) {
return KoreaderUserEntity.builder()
.syncEnabled(syncEnabled)
.syncWithWebReader(syncWithWebReader)
.build();
}
private BookLoreUserEntity user(long userId) {
BookLoreUserEntity user = new BookLoreUserEntity();
user.setId(userId);
return user;
}
private BookEntity epubBook(long bookId) {
return bookWithPrimaryFile(bookId, BookFileType.EPUB);
}
private BookEntity bookWithPrimaryFile(long bookId, BookFileType bookFileType) {
BookEntity book = new BookEntity();
book.setId(bookId);
LibraryPathEntity libraryPath = new LibraryPathEntity();
libraryPath.setPath("/library");
book.setLibraryPath(libraryPath);
BookFileEntity primaryFile = new BookFileEntity();
primaryFile.setId(1L);
primaryFile.setBook(book);
primaryFile.setBookType(bookFileType);
primaryFile.setFileSubPath("subdir");
primaryFile.setFileName("book.epub");
book.setBookFiles(List.of(primaryFile));
return book;
}
}
@@ -16,6 +16,7 @@ import org.booklore.model.enums.ResetProgressType;
import org.booklore.repository.*;
import org.booklore.service.kobo.KoboReadingStateService;
import org.booklore.service.hardcover.HardcoverSyncService;
import org.booklore.service.koreader.KoreaderService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
@@ -46,6 +47,8 @@ class ReadingProgressServiceTest {
private KoboReadingStateService koboReadingStateService;
@Mock
private HardcoverSyncService hardcoverSyncService;
@Mock
private KoreaderService koreaderService;
@InjectMocks
private ReadingProgressService readingProgressService;
@@ -286,6 +289,106 @@ class ReadingProgressServiceTest {
assertEquals(50f, progress.getPdfProgressPercent());
}
@Test
void updateReadProgress_shouldDelegateKoreaderSync() {
long bookId = 1L;
BookEntity book = new BookEntity();
book.setId(bookId);
BookFileEntity primaryFile = new BookFileEntity();
primaryFile.setId(1L);
primaryFile.setBook(book);
primaryFile.setBookType(BookFileType.EPUB);
book.setBookFiles(List.of(primaryFile));
BookLoreUser user = mock(BookLoreUser.class);
when(user.getId()).thenReturn(2L);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.of(book));
BookLoreUserEntity userEntity = new BookLoreUserEntity();
userEntity.setId(2L);
when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity));
UserBookProgressEntity progress = new UserBookProgressEntity();
when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.of(progress));
when(userBookFileProgressRepository.findByUserIdAndBookFileId(2L, 1L)).thenReturn(Optional.empty());
ReadProgressRequest req = new ReadProgressRequest();
req.setBookId(bookId);
EpubProgress epubProgress = EpubProgress.builder().cfi("cfi").percentage(100f).build();
req.setEpubProgress(epubProgress);
readingProgressService.updateReadProgress(req);
verify(koreaderService).syncProgressToKoreader(bookId, 100f, 2L);
}
@Test
void updateReadProgress_shouldDelegateKoreaderSyncWithCorrectPercentage() {
long bookId = 1L;
BookEntity book = new BookEntity();
book.setId(bookId);
BookFileEntity primaryFile = new BookFileEntity();
primaryFile.setId(1L);
primaryFile.setBook(book);
primaryFile.setBookType(BookFileType.PDF);
book.setBookFiles(List.of(primaryFile));
BookLoreUser user = mock(BookLoreUser.class);
when(user.getId()).thenReturn(2L);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.of(book));
BookLoreUserEntity userEntity = new BookLoreUserEntity();
userEntity.setId(2L);
when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity));
UserBookProgressEntity progress = new UserBookProgressEntity();
when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.of(progress));
when(userBookFileProgressRepository.findByUserIdAndBookFileId(2L, 1L)).thenReturn(Optional.empty());
ReadProgressRequest req = new ReadProgressRequest();
req.setBookId(bookId);
PdfProgress pdfProgress = PdfProgress.builder().page(10).percentage(50f).build();
req.setPdfProgress(pdfProgress);
readingProgressService.updateReadProgress(req);
verify(koreaderService).syncProgressToKoreader(bookId, 50f, 2L);
}
@Test
void updateReadProgress_shouldNotDelegateKoreaderSyncWhenPercentageNull() {
long bookId = 1L;
BookEntity book = new BookEntity();
book.setId(bookId);
BookFileEntity primaryFile = new BookFileEntity();
primaryFile.setId(1L);
primaryFile.setBook(book);
primaryFile.setBookType(BookFileType.EPUB);
book.setBookFiles(List.of(primaryFile));
BookLoreUser user = mock(BookLoreUser.class);
when(user.getId()).thenReturn(2L);
when(authenticationService.getAuthenticatedUser()).thenReturn(user);
when(bookRepository.findByIdWithBookFiles(bookId)).thenReturn(Optional.of(book));
BookLoreUserEntity userEntity = new BookLoreUserEntity();
userEntity.setId(2L);
when(userRepository.findById(2L)).thenReturn(Optional.of(userEntity));
when(userBookProgressRepository.findByUserIdAndBookId(2L, bookId)).thenReturn(Optional.empty());
ReadProgressRequest req = new ReadProgressRequest();
req.setBookId(bookId);
readingProgressService.updateReadProgress(req);
verify(koreaderService, never()).syncProgressToKoreader(anyLong(), anyFloat(), anyLong());
}
@Test
void resetProgress_booklore_shouldCallBulkReset() {
BookLoreUser user = mock(BookLoreUser.class);