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
@@ -14,4 +14,5 @@ public class KoboSyncSettings {
private boolean autoAddToShelf;
private String hardcoverApiKey;
private boolean hardcoverSyncEnabled;
private boolean twoWayProgressSync;
}
@@ -33,7 +33,7 @@ public class KoboReadingState {
public static class StatusInfo {
private String lastModified;
private KoboReadStatus status;
private int timesStartedReading;
private Integer timesStartedReading;
private String lastTimeStartedReading;
private String lastTimeFinished;
}
@@ -44,4 +44,8 @@ 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;
}
@@ -46,6 +46,10 @@ public interface UserBookProgressRepository extends JpaRepository<UserBookProgre
ubp.koboProgressSentTime IS NULL
OR ubp.koboProgressReceivedTime > ubp.koboProgressSentTime
))
OR
(ubp.epubProgressPercent IS NOT NULL
AND ubp.epubProgress IS NOT NULL
AND (ubp.koboProgressSentTime IS NULL OR ubp.lastReadTime > ubp.koboProgressSentTime))
)
""")
List<UserBookProgressEntity> findAllBooksNeedingKoboSync(
@@ -47,6 +47,7 @@ public class KoboEntitlementService {
private final ShelfRepository shelfRepository;
private final MagicShelfRepository magicShelfRepository;
private final MagicShelfBookService magicShelfBookService;
private final KoboSettingsService koboSettingsService;
public List<NewEntitlement> generateNewEntitlements(Set<Long> bookIds, String token) {
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds);
@@ -178,7 +179,8 @@ public class KoboEntitlementService {
private ChangedReadingState buildChangedReadingState(UserBookProgressEntity progress, String timestamp, OffsetDateTime now) {
String entitlementId = String.valueOf(progress.getBook().getId());
KoboReadingState.CurrentBookmark bookmark = progress.getKoboProgressPercent() != null
boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync();
KoboReadingState.CurrentBookmark bookmark = (progress.getKoboProgressPercent() != null || (twoWaySync && progress.getEpubProgressPercent() != null))
? readingStateBuilder.buildBookmarkFromProgress(progress, now)
: readingStateBuilder.buildEmptyBookmark(now);
@@ -214,10 +216,21 @@ public class KoboEntitlementService {
Optional<UserBookProgressEntity> userProgress = progressRepository
.findByUserIdAndBookId(authenticationService.getAuthenticatedUser().getId(), book.getId());
KoboReadingState.CurrentBookmark bookmark = existingState != null && existingState.getCurrentBookmark() != null
boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync();
KoboReadingState.CurrentBookmark webReaderBookmark = twoWaySync
? userProgress
.filter(progress -> progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null)
.map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, now))
.orElse(null)
: null;
KoboReadingState.CurrentBookmark bookmark = webReaderBookmark != null
? webReaderBookmark
: existingState != null && existingState.getCurrentBookmark() != null
? existingState.getCurrentBookmark()
: userProgress
.filter(progress -> progress.getKoboProgressPercent() != null)
.filter(progress -> progress.getKoboProgressPercent() != null || (twoWaySync && progress.getEpubProgressPercent() != null))
.map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, now))
.orElseGet(() -> readingStateBuilder.buildEmptyBookmark(now));
@@ -37,6 +37,7 @@ public class KoboLibrarySyncService {
private final UserBookProgressRepository userBookProgressRepository;
private final KoboServerProxy koboServerProxy;
private final ObjectMapper objectMapper;
private final KoboSettingsService koboSettingsService;
@Transactional
public ResponseEntity<?> syncLibrary(BookLoreUser user, String token) {
@@ -162,6 +163,12 @@ 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();
}
@@ -192,12 +199,26 @@ public class KoboLibrarySyncService {
return sentTime == null || modifiedTime.isAfter(sentTime);
}
private boolean needsProgressSync(UserBookProgressEntity progress) {
Instant receivedTime = progress.getKoboProgressReceivedTime();
if (receivedTime == null) {
return false;
}
private boolean needsKoboProgressSync(UserBookProgressEntity progress) {
Instant sentTime = progress.getKoboProgressSentTime();
return sentTime == null || receivedTime.isAfter(sentTime);
Instant receivedTime = progress.getKoboProgressReceivedTime();
return receivedTime != null && (sentTime == null || receivedTime.isAfter(sentTime));
}
private boolean needsProgressSync(UserBookProgressEntity progress) {
if (needsKoboProgressSync(progress)) {
return true;
}
if (koboSettingsService.getCurrentUserSettings().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;
}
}
@@ -1,5 +1,6 @@
package org.booklore.service.kobo;
import lombok.RequiredArgsConstructor;
import org.booklore.model.dto.kobo.KoboReadingState;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.enums.KoboReadStatus;
@@ -12,8 +13,11 @@ import java.time.ZoneOffset;
import java.util.Optional;
@Component
@RequiredArgsConstructor
public class KoboReadingStateBuilder {
private final KoboSettingsService koboSettingsService;
public KoboReadingState.CurrentBookmark buildEmptyBookmark(OffsetDateTime timestamp) {
return KoboReadingState.CurrentBookmark.builder()
.lastModified(timestamp.toString())
@@ -25,6 +29,30 @@ public class KoboReadingStateBuilder {
}
public KoboReadingState.CurrentBookmark buildBookmarkFromProgress(UserBookProgressEntity progress, OffsetDateTime defaultTime) {
if (isWebReaderNewer(progress)) {
return buildBookmarkFromWebReaderProgress(progress, defaultTime);
}
return buildBookmarkFromKoboProgress(progress, defaultTime);
}
private boolean isWebReaderNewer(UserBookProgressEntity progress) {
return koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()
&& progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null;
}
private KoboReadingState.CurrentBookmark buildBookmarkFromWebReaderProgress(UserBookProgressEntity progress, OffsetDateTime defaultTime) {
String lastModified = Optional.ofNullable(progress.getLastReadTime())
.map(this::formatTimestamp)
.or(() -> Optional.ofNullable(defaultTime).map(OffsetDateTime::toString))
.orElse(null);
return KoboReadingState.CurrentBookmark.builder()
.progressPercent(Math.round(progress.getEpubProgressPercent()))
.lastModified(lastModified)
.build();
}
private KoboReadingState.CurrentBookmark buildBookmarkFromKoboProgress(UserBookProgressEntity progress, OffsetDateTime defaultTime) {
KoboReadingState.CurrentBookmark.Location location = Optional.ofNullable(progress.getKoboLocation())
.map(koboLocation -> KoboReadingState.CurrentBookmark.Location.builder()
.value(koboLocation)
@@ -1,21 +1,21 @@
package org.booklore.service.kobo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.booklore.config.security.service.AuthenticationService;
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.response.kobo.KoboReadingStateResponse;
import org.booklore.model.entity.*;
import org.booklore.model.entity.BookEntity;
import org.booklore.model.entity.BookLoreUserEntity;
import org.booklore.model.entity.KoboReadingStateEntity;
import org.booklore.model.entity.UserBookFileProgressEntity;
import org.booklore.model.entity.UserBookProgressEntity;
import org.booklore.model.enums.ReadStatus;
import org.booklore.repository.BookRepository;
import org.booklore.repository.KoboReadingStateRepository;
import org.booklore.repository.UserBookFileProgressRepository;
import org.booklore.repository.UserBookProgressRepository;
import org.booklore.repository.UserRepository;
import org.booklore.repository.*;
import org.booklore.service.hardcover.HardcoverSyncService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -80,7 +80,7 @@ public class KoboReadingStateService {
private List<KoboReadingState> saveAll(List<KoboReadingState> dtos) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
Long userId = user.getId();
return dtos.stream()
.map(dto -> {
String entitlementId = mapper.cleanString(dto.getEntitlementId());
@@ -114,9 +114,9 @@ public class KoboReadingStateService {
KoboReadingStateEntity savedEntity = repository.save(entity);
KoboReadingState savedState = mapper.toDto(savedEntity);
syncKoboProgressToUserBookProgress(savedState, userId);
return savedEntity;
})
.map(mapper::toDto)
@@ -139,6 +139,8 @@ public class KoboReadingStateService {
.map(mapper::toDto))
.or(() -> constructReadingStateFromProgress(entitlementId));
readingState.ifPresent(state -> overlayWebReaderBookmark(state, entitlementId, userId));
return readingState
.map(state -> {
normalizeResponseTimestamps(state);
@@ -146,21 +148,46 @@ public class KoboReadingStateService {
})
.orElse(List.of());
}
private void overlayWebReaderBookmark(KoboReadingState state, String entitlementId, Long userId) {
if (!koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()) {
return;
}
try {
Long bookId = Long.parseLong(entitlementId);
progressRepository.findByUserIdAndBookId(userId, bookId)
.filter(progress -> progress.getEpubProgress() != null && progress.getEpubProgressPercent() != null)
.ifPresent(progress -> {
KoboReadingState.CurrentBookmark existing = state.getCurrentBookmark();
KoboReadingState.CurrentBookmark webReaderBookmark = readingStateBuilder.buildBookmarkFromProgress(progress);
if (existing != null) {
existing.setProgressPercent(webReaderBookmark.getProgressPercent());
existing.setLastModified(webReaderBookmark.getLastModified());
} else {
state.setCurrentBookmark(webReaderBookmark);
}
});
} catch (NumberFormatException e) {
// Not a valid book ID, skip overlay
}
}
private Optional<KoboReadingState> constructReadingStateFromProgress(String entitlementId) {
try {
Long bookId = Long.parseLong(entitlementId);
BookLoreUser user = authenticationService.getAuthenticatedUser();
boolean twoWaySync = koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync();
return progressRepository.findByUserIdAndBookId(user.getId(), bookId)
.filter(progress -> progress.getKoboProgressPercent() != null || progress.getKoboLocation() != null)
.filter(progress -> progress.getKoboProgressPercent() != null || progress.getKoboLocation() != null || (twoWaySync && progress.getEpubProgressPercent() != null))
.map(progress -> readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress));
} catch (NumberFormatException e) {
log.warn("Invalid entitlement ID format when constructing reading state: {}", entitlementId);
return Optional.empty();
}
}
private void syncKoboProgressToUserBookProgress(KoboReadingState readingState, Long userId) {
try {
Long bookId = Long.parseLong(readingState.getEntitlementId());
@@ -197,9 +224,6 @@ public class KoboReadingStateService {
KoboReadingState.CurrentBookmark.Location location = bookmark.getLocation();
if (location != null) {
log.debug("Kobo location data: value={}, type={}, source={} (length={})",
location.getValue(), location.getType(), location.getSource(),
location.getSource() != null ? location.getSource().length() : 0);
progress.setKoboLocation(location.getValue());
progress.setKoboLocationType(location.getType());
progress.setKoboLocationSource(location.getSource());
@@ -208,7 +232,11 @@ public class KoboReadingStateService {
Instant now = Instant.now();
progress.setKoboProgressReceivedTime(now);
progress.setLastReadTime(now);
boolean koboApplied = crossPopulateEpubFieldsFromKobo(progress, bookmark, book, userId, now);
if (koboApplied) {
progress.setLastReadTime(now);
}
if (progress.getKoboProgressPercent() != null) {
updateReadStatusFromKoboProgress(progress, now);
@@ -216,16 +244,11 @@ public class KoboReadingStateService {
progressRepository.save(progress);
// Also save to file-level progress table (dual-write)
saveToFileProgress(userOpt.get(), book, progress);
log.debug("Synced Kobo progress: bookId={}, progress={}%", bookId, progress.getKoboProgressPercent());
// Sync progress to Hardcover asynchronously (if enabled for this user)
// But only if the progress percentage has changed from last time, or the read status has changed
if (progress.getKoboProgressPercent() != null
&& (!progress.getKoboProgressPercent().equals(prevousKoboProgressPercent)
|| progress.getReadStatus() != previousReadStatus)) {
|| progress.getReadStatus() != previousReadStatus)) {
hardcoverSyncService.syncProgressToHardcover(book.getId(), progress.getKoboProgressPercent(), userId);
}
} catch (NumberFormatException e) {
@@ -233,6 +256,51 @@ public class KoboReadingStateService {
}
}
private boolean crossPopulateEpubFieldsFromKobo(UserBookProgressEntity progress,
KoboReadingState.CurrentBookmark bookmark,
BookEntity book, Long userId, Instant now) {
if (bookmark == null || bookmark.getProgressPercent() == null) {
return false;
}
if (!koboSettingsService.getCurrentUserSettings().isTwoWayProgressSync()) {
return false;
}
UserBookFileProgressEntity fileProgress = book.getPrimaryBookFile() != null
? fileProgressRepository.findByUserIdAndBookFileId(userId, book.getPrimaryBookFile().getId()).orElse(null)
: null;
Instant bookmarkTime = parseTimestamp(bookmark.getLastModified());
boolean webReaderIsNewer = fileProgress != null
&& fileProgress.getLastReadTime() != null
&& bookmarkTime != null
&& fileProgress.getLastReadTime().isAfter(bookmarkTime);
if (webReaderIsNewer) {
return false;
}
progress.setEpubProgressPercent(bookmark.getProgressPercent().floatValue());
KoboReadingState.CurrentBookmark.Location location = bookmark.getLocation();
if (location != null && location.getSource() != null) {
progress.setEpubProgressHref(location.getSource());
}
progress.setEpubProgress(null);
if (fileProgress != null) {
fileProgress.setProgressPercent(bookmark.getProgressPercent().floatValue());
if (location != null && location.getSource() != null) {
fileProgress.setPositionHref(location.getSource());
}
fileProgress.setPositionData(null);
fileProgress.setLastReadTime(now);
fileProgressRepository.save(fileProgress);
}
return true;
}
private void normalizePutTimestamps(List<KoboReadingState> readingStates) {
if (readingStates == null || readingStates.isEmpty()) {
return;
@@ -429,26 +497,6 @@ public class KoboReadingStateService {
return value == null || value.trim().isEmpty() || "null".equalsIgnoreCase(value.trim());
}
private void saveToFileProgress(BookLoreUserEntity user, BookEntity book, UserBookProgressEntity progress) {
try {
BookFileEntity primaryFile = book.getPrimaryBookFile();
UserBookFileProgressEntity fileProgress = fileProgressRepository
.findByUserIdAndBookFileId(user.getId(), primaryFile.getId())
.orElseGet(UserBookFileProgressEntity::new);
fileProgress.setUser(user);
fileProgress.setBookFile(primaryFile);
fileProgress.setLastReadTime(progress.getLastReadTime());
// For Kobo, we store the progress percent (Kobo doesn't provide position data)
fileProgress.setProgressPercent(progress.getKoboProgressPercent());
fileProgressRepository.save(fileProgress);
} catch (Exception e) {
log.warn("Failed to save file-level progress for book {}: {}", book.getId(), e.getMessage());
}
}
private void updateReadStatusFromKoboProgress(UserBookProgressEntity userProgress, Instant now) {
if (shouldPreserveCurrentStatus(userProgress, now)) {
return;
@@ -479,15 +527,15 @@ public class KoboReadingStateService {
return now.isBefore(statusSentTime.plusSeconds(STATUS_SYNC_BUFFER_SECONDS));
}
private ReadStatus deriveStatusFromProgress(double progressPercent) {
KoboSyncSettings settings = koboSettingsService.getCurrentUserSettings();
float finishedThreshold = settings.getProgressMarkAsFinishedThreshold() != null
float finishedThreshold = settings.getProgressMarkAsFinishedThreshold() != null
? settings.getProgressMarkAsFinishedThreshold() : 99f;
float readingThreshold = settings.getProgressMarkAsReadingThreshold() != null
float readingThreshold = settings.getProgressMarkAsReadingThreshold() != null
? settings.getProgressMarkAsReadingThreshold() : 1f;
if (progressPercent >= finishedThreshold) return ReadStatus.READ;
if (progressPercent >= readingThreshold) return ReadStatus.READING;
return ReadStatus.UNREAD;
@@ -84,6 +84,7 @@ public class KoboSettingsService {
}
entity.setAutoAddToShelf(settings.isAutoAddToShelf());
entity.setTwoWayProgressSync(settings.isTwoWayProgressSync());
repository.save(entity);
return mapToDto(entity, hardcoverSyncSettingsService.getSettingsForUserId(user.getId()));
@@ -130,6 +131,7 @@ 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());
@@ -0,0 +1 @@
ALTER TABLE kobo_user_settings ADD COLUMN IF NOT EXISTS two_way_progress_sync BOOLEAN NOT NULL DEFAULT FALSE;