Feat: Improve kobo reading state sync logic for better bidirectional support (#1644)

* feat: kobo sync improvements (push changes from booklore, and properly delete kobo data on reset)

* fix: issues with sync race conditions and improve readability

* fix: update function names to be clearer and more explicit

* fix: move partially_read to reading status mapping

* fix: make the bufferwindow more explicit in the unsynced progress check

* chore: add unit tests for additional sync logic

* fix: improve bi-directional logic to account for changes in progress and status

* chore: add additional tests to check the kobo sync logic and remove redundant tests
This commit is contained in:
CounterClops
2025-11-30 09:44:11 -07:00
committed by GitHub
parent 2336d04a46
commit 3ef5b60ed6
14 changed files with 1169 additions and 254 deletions
@@ -0,0 +1,27 @@
package com.adityachandel.booklore.model.dto.kobo;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
public class ChangedReadingState implements Entitlement {
private WrappedReadingState changedReadingState;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
public static class WrappedReadingState {
private KoboReadingState readingState;
}
}
@@ -82,6 +82,15 @@ public class UserBookProgressEntity {
@Column(name = "koreader_last_sync_time")
private Instant koreaderLastSyncTime;
@Column(name = "kobo_last_sync_time")
private Instant koboLastSyncTime;
@Column(name = "kobo_progress_received_time")
private Instant koboProgressReceivedTime;
@Column(name = "kobo_status_sent_time")
private Instant koboStatusSentTime;
@Column(name = "kobo_progress_sent_time")
private Instant koboProgressSentTime;
@Column(name = "read_status_modified_time")
private Instant readStatusModifiedTime;
}
@@ -2,6 +2,8 @@ package com.adityachandel.booklore.repository;
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@@ -14,4 +16,28 @@ public interface UserBookProgressRepository extends JpaRepository<UserBookProgre
Optional<UserBookProgressEntity> findByUserIdAndBookId(Long userId, Long bookId);
List<UserBookProgressEntity> findByUserIdAndBookIdIn(Long userId, Set<Long> bookIds);
@Query("""
SELECT ubp FROM UserBookProgressEntity ubp
WHERE ubp.user.id = :userId
AND ubp.book.id IN (
SELECT ksb.bookId FROM KoboSnapshotBookEntity ksb
WHERE ksb.snapshot.id = :snapshotId
)
AND (
(ubp.readStatusModifiedTime IS NOT NULL AND (
ubp.koboStatusSentTime IS NULL
OR ubp.readStatusModifiedTime > ubp.koboStatusSentTime
))
OR
(ubp.koboProgressReceivedTime IS NOT NULL AND (
ubp.koboProgressSentTime IS NULL
OR ubp.koboProgressReceivedTime > ubp.koboProgressSentTime
))
)
""")
List<UserBookProgressEntity> findAllBooksNeedingKoboSync(
@Param("userId") Long userId,
@Param("snapshotId") String snapshotId
);
}
@@ -16,6 +16,7 @@ import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.ReadStatus;
import com.adityachandel.booklore.model.enums.ResetProgressType;
import com.adityachandel.booklore.repository.*;
import com.adityachandel.booklore.service.kobo.KoboReadingStateService;
import com.adityachandel.booklore.service.user.UserProgressService;
import com.adityachandel.booklore.service.monitoring.MonitoringRegistrationService;
import com.adityachandel.booklore.util.FileService;
@@ -62,6 +63,7 @@ public class BookService {
private final UserProgressService userProgressService;
private final BookDownloadService bookDownloadService;
private final MonitoringRegistrationService monitoringRegistrationService;
private final KoboReadingStateService koboReadingStateService;
private void setBookProgress(Book book, UserBookProgressEntity progress) {
@@ -407,6 +409,7 @@ public class BookService {
progress.setUser(userEntity);
progress.setBook(book);
progress.setReadStatus(readStatus);
progress.setReadStatusModifiedTime(Instant.now());
if (readStatus == ReadStatus.READ) {
progress.setDateFinished(Instant.now());
@@ -452,6 +455,11 @@ public class BookService {
progress.setBook(bookEntity);
progress.setUser(userEntity.orElseThrow());
if (progress.getReadStatus() != null) {
progress.setReadStatusModifiedTime(Instant.now());
}
progress.setReadStatus(null);
progress.setLastReadTime(null);
progress.setDateFinished(null);
@@ -473,7 +481,8 @@ public class BookService {
progress.setKoboLocation(null);
progress.setKoboLocationType(null);
progress.setKoboLocationSource(null);
progress.setKoboLastSyncTime(null);
progress.setKoboProgressReceivedTime(null);
koboReadingStateService.deleteReadingState(bookId);
}
userBookProgressRepository.save(progress);
updatedBooks.add(bookMapper.toBook(bookEntity));
@@ -19,6 +19,7 @@ import com.adityachandel.booklore.service.book.BookQueryService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.util.kobo.KoboUrlBuilder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.OffsetDateTime;
@@ -32,6 +33,7 @@ import java.util.stream.Collectors;
@AllArgsConstructor
@Service
@Slf4j
public class KoboEntitlementService {
private static final Pattern NON_ALPHANUMERIC_LOWERCASE_PATTERN = Pattern.compile("[^a-z0-9]");
@@ -87,39 +89,72 @@ public class KoboEntitlementService {
.collect(Collectors.toList());
}
public List<ChangedReadingState> generateChangedReadingStates(List<UserBookProgressEntity> progressEntries) {
OffsetDateTime now = getCurrentUtc();
String timestamp = now.toString();
return progressEntries.stream()
.map(progress -> buildChangedReadingState(progress, timestamp, now))
.toList();
}
private ChangedReadingState buildChangedReadingState(UserBookProgressEntity progress, String timestamp, OffsetDateTime now) {
String entitlementId = String.valueOf(progress.getBook().getId());
KoboReadingState.CurrentBookmark bookmark = progress.getKoboProgressPercent() != null
? readingStateBuilder.buildBookmarkFromProgress(progress, now)
: readingStateBuilder.buildEmptyBookmark(now);
KoboReadingState readingState = KoboReadingState.builder()
.entitlementId(entitlementId)
.created(timestamp)
.lastModified(timestamp)
.priorityTimestamp(timestamp)
.statusInfo(readingStateBuilder.buildStatusInfoFromProgress(progress, timestamp))
.currentBookmark(bookmark)
.statistics(KoboReadingState.Statistics.builder().lastModified(timestamp).build())
.build();
return ChangedReadingState.builder()
.changedReadingState(ChangedReadingState.WrappedReadingState.builder()
.readingState(readingState)
.build())
.build();
}
private KoboReadingState createInitialReadingState(BookEntity book) {
OffsetDateTime now = getCurrentUtc();
OffsetDateTime createdOn = getCreatedOn(book);
String entitlementId = String.valueOf(book.getId());
KoboReadingState existingState = readingStateRepository.findByEntitlementId(entitlementId)
.map(readingStateMapper::toDto)
.orElse(null);
KoboReadingState.CurrentBookmark bookmark;
if (existingState != null && existingState.getCurrentBookmark() != null) {
bookmark = existingState.getCurrentBookmark();
} else {
bookmark = progressRepository
.findByUserIdAndBookId(authenticationService.getAuthenticatedUser().getId(), book.getId())
.filter(progress -> progress.getKoboProgressPercent() != null)
.map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, now))
.orElseGet(() -> readingStateBuilder.buildEmptyBookmark(now));
}
return KoboReadingState.builder()
.entitlementId(entitlementId)
.created(createdOn.toString())
.lastModified(now.toString())
.statusInfo(KoboReadingState.StatusInfo.builder()
Optional<UserBookProgressEntity> userProgress = progressRepository
.findByUserIdAndBookId(authenticationService.getAuthenticatedUser().getId(), book.getId());
KoboReadingState.CurrentBookmark bookmark = existingState != null && existingState.getCurrentBookmark() != null
? existingState.getCurrentBookmark()
: userProgress
.filter(progress -> progress.getKoboProgressPercent() != null)
.map(progress -> readingStateBuilder.buildBookmarkFromProgress(progress, now))
.orElseGet(() -> readingStateBuilder.buildEmptyBookmark(now));
KoboReadingState.StatusInfo statusInfo = userProgress
.map(progress -> readingStateBuilder.buildStatusInfoFromProgress(progress, now.toString()))
.orElseGet(() -> KoboReadingState.StatusInfo.builder()
.lastModified(now.toString())
.status(KoboReadStatus.READY_TO_READ)
.timesStartedReading(0)
.build())
.build());
return KoboReadingState.builder()
.entitlementId(entitlementId)
.created(getCreatedOn(book).toString())
.lastModified(now.toString())
.statusInfo(statusInfo)
.currentBookmark(bookmark)
.statistics(KoboReadingState.Statistics.builder()
.lastModified(now.toString())
.build())
.statistics(KoboReadingState.Statistics.builder().lastModified(now.toString()).build())
.priorityTimestamp(now.toString())
.build();
}
@@ -6,7 +6,9 @@ import com.adityachandel.booklore.model.dto.BookloreSyncToken;
import com.adityachandel.booklore.model.dto.kobo.*;
import com.adityachandel.booklore.model.entity.KoboSnapshotBookEntity;
import com.adityachandel.booklore.model.entity.KoboLibrarySnapshotEntity;
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
import com.adityachandel.booklore.repository.KoboDeletedBookProgressRepository;
import com.adityachandel.booklore.repository.UserBookProgressRepository;
import com.adityachandel.booklore.util.RequestUtils;
import com.adityachandel.booklore.util.kobo.BookloreSyncTokenGenerator;
import com.fasterxml.jackson.databind.JsonNode;
@@ -17,9 +19,11 @@ import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
@@ -32,9 +36,11 @@ public class KoboLibrarySyncService {
private final KoboLibrarySnapshotService koboLibrarySnapshotService;
private final KoboEntitlementService entitlementService;
private final KoboDeletedBookProgressRepository koboDeletedBookProgressRepository;
private final UserBookProgressRepository userBookProgressRepository;
private final KoboServerProxy koboServerProxy;
private final ObjectMapper objectMapper;
@Transactional
public ResponseEntity<?> syncLibrary(BookLoreUser user, String token) {
HttpServletRequest request = RequestUtils.getCurrentRequest();
BookloreSyncToken syncToken = Optional.ofNullable(tokenGenerator.fromRequestHeaders(request)).orElse(new BookloreSyncToken());
@@ -68,6 +74,10 @@ public class KoboLibrarySyncService {
entitlements.addAll(entitlementService.generateNewEntitlements(addedIds, token, false));
entitlements.addAll(entitlementService.generateChangedEntitlements(removedIds, token, true));
if (!shouldContinueSync) {
entitlements.addAll(syncReadingStatesToKobo(user.getId(), currSnapshot.getId()));
}
} else {
int maxRemaining = 5;
List<KoboSnapshotBookEntity> all = new ArrayList<>();
@@ -80,6 +90,10 @@ public class KoboLibrarySyncService {
}
Set<Long> ids = all.stream().map(KoboSnapshotBookEntity::getBookId).collect(Collectors.toSet());
entitlements.addAll(entitlementService.generateNewEntitlements(ids, token, false));
if (!shouldContinueSync) {
entitlements.addAll(syncReadingStatesToKobo(user.getId(), currSnapshot.getId()));
}
}
if (!shouldContinueSync) {
@@ -131,4 +145,47 @@ public class KoboLibrarySyncService {
.header(KoboHeaders.X_KOBO_SYNCTOKEN, tokenGenerator.toBase64(syncToken))
.body(entitlements);
}
}
private List<ChangedReadingState> syncReadingStatesToKobo(Long userId, String snapshotId) {
List<UserBookProgressEntity> booksNeedingSync =
userBookProgressRepository.findAllBooksNeedingKoboSync(userId, snapshotId);
if (booksNeedingSync.isEmpty()) {
return Collections.emptyList();
}
List<ChangedReadingState> changedStates = entitlementService.generateChangedReadingStates(booksNeedingSync);
Instant sentTime = Instant.now();
for (UserBookProgressEntity progress : booksNeedingSync) {
if (needsStatusSync(progress)) {
progress.setKoboStatusSentTime(sentTime);
}
if (needsProgressSync(progress)) {
progress.setKoboProgressSentTime(sentTime);
}
}
userBookProgressRepository.saveAll(booksNeedingSync);
log.info("Synced {} reading states to Kobo", changedStates.size());
return changedStates;
}
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 needsProgressSync(UserBookProgressEntity progress) {
Instant receivedTime = progress.getKoboProgressReceivedTime();
if (receivedTime == null) {
return false;
}
Instant sentTime = progress.getKoboProgressSentTime();
return sentTime == null || receivedTime.isAfter(sentTime);
}
}
@@ -2,6 +2,8 @@ package com.adityachandel.booklore.service.kobo;
import com.adityachandel.booklore.model.dto.kobo.KoboReadingState;
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
import com.adityachandel.booklore.model.enums.KoboReadStatus;
import com.adityachandel.booklore.model.enums.ReadStatus;
import org.springframework.stereotype.Component;
import java.time.Instant;
@@ -24,14 +26,14 @@ public class KoboReadingStateBuilder {
public KoboReadingState.CurrentBookmark buildBookmarkFromProgress(UserBookProgressEntity progress, OffsetDateTime defaultTime) {
KoboReadingState.CurrentBookmark.Location location = Optional.ofNullable(progress.getKoboLocation())
.map(loc -> KoboReadingState.CurrentBookmark.Location.builder()
.value(loc)
.map(koboLocation -> KoboReadingState.CurrentBookmark.Location.builder()
.value(koboLocation)
.type(progress.getKoboLocationType())
.source(progress.getKoboLocationSource())
.build())
.orElse(null);
String lastModified = Optional.ofNullable(progress.getKoboLastSyncTime())
String lastModified = Optional.ofNullable(progress.getKoboProgressReceivedTime())
.map(this::formatTimestamp)
.or(() -> Optional.ofNullable(defaultTime).map(OffsetDateTime::toString))
.orElse(null);
@@ -48,15 +50,45 @@ public class KoboReadingStateBuilder {
public KoboReadingState buildReadingStateFromProgress(String entitlementId, UserBookProgressEntity progress) {
KoboReadingState.CurrentBookmark bookmark = buildBookmarkFromProgress(progress);
String lastModified = bookmark.getLastModified();
KoboReadingState.StatusInfo statusInfo = buildStatusInfoFromProgress(progress, lastModified);
return KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(bookmark)
.statusInfo(statusInfo)
.created(lastModified)
.lastModified(lastModified)
.build();
}
public KoboReadingState.StatusInfo buildStatusInfoFromProgress(UserBookProgressEntity progress, String lastModified) {
KoboReadStatus koboStatus = mapReadStatusToKoboStatus(progress.getReadStatus());
int timesStartedReading = koboStatus == KoboReadStatus.READY_TO_READ ? 0 : 1;
KoboReadingState.StatusInfo.StatusInfoBuilder builder = KoboReadingState.StatusInfo.builder()
.lastModified(lastModified)
.status(koboStatus)
.timesStartedReading(timesStartedReading);
if (koboStatus == KoboReadStatus.FINISHED && progress.getDateFinished() != null) {
builder.lastTimeFinished(formatTimestamp(progress.getDateFinished()));
}
return builder.build();
}
public KoboReadStatus mapReadStatusToKoboStatus(ReadStatus readStatus) {
if (readStatus == null) {
return KoboReadStatus.READY_TO_READ;
}
return switch (readStatus) {
case READ -> KoboReadStatus.FINISHED;
case PARTIALLY_READ, READING, RE_READING, PAUSED -> KoboReadStatus.READING;
case UNREAD, WONT_READ, ABANDONED -> KoboReadStatus.READY_TO_READ;
};
}
private String formatTimestamp(Instant instant) {
return instant.atOffset(ZoneOffset.UTC).toString();
}
@@ -31,6 +31,8 @@ import java.util.stream.Collectors;
@RequiredArgsConstructor
public class KoboReadingStateService {
private static final int STATUS_SYNC_BUFFER_SECONDS = 10;
private final KoboReadingStateRepository repository;
private final KoboReadingStateMapper mapper;
private final UserBookProgressRepository progressRepository;
@@ -88,6 +90,11 @@ public class KoboReadingStateService {
.collect(Collectors.toList());
}
@Transactional
public void deleteReadingState(Long bookId) {
repository.findByEntitlementId(String.valueOf(bookId)).ifPresent(repository::delete);
}
public KoboReadingStateWrapper getReadingState(String entitlementId) {
Optional<KoboReadingState> readingState = repository.findByEntitlementId(entitlementId)
.map(mapper::toDto)
@@ -105,11 +112,7 @@ public class KoboReadingStateService {
return progressRepository.findByUserIdAndBookId(user.getId(), bookId)
.filter(progress -> progress.getKoboProgressPercent() != null || progress.getKoboLocation() != null)
.map(progress -> {
log.info("Constructed reading state from UserBookProgress for book: {}, progress: {}%",
entitlementId, progress.getKoboProgressPercent());
return readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress);
});
.map(progress -> readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress));
} catch (NumberFormatException e) {
log.warn("Invalid entitlement ID format when constructing reading state: {}", entitlementId);
return Optional.empty();
@@ -155,43 +158,63 @@ public class KoboReadingStateService {
}
}
progress.setKoboLastSyncTime(Instant.now());
progress.setLastReadTime(Instant.now());
Instant now = Instant.now();
progress.setKoboProgressReceivedTime(now);
progress.setLastReadTime(now);
if (progress.getKoboProgressPercent() != null) {
updateKoboReadStatus(progress, progress.getKoboProgressPercent() / 100.0);
updateReadStatusFromKoboProgress(progress, now);
}
progressRepository.save(progress);
log.info("Synced Kobo progress to BookLore: userId={}, bookId={}, progress={}%",
userId, bookId, progress.getKoboProgressPercent());
log.debug("Synced Kobo progress: bookId={}, progress={}%", bookId, progress.getKoboProgressPercent());
} catch (NumberFormatException e) {
log.warn("Invalid entitlement ID format: {}", readingState.getEntitlementId());
}
}
private void updateKoboReadStatus(UserBookProgressEntity userProgress, double progressFraction) {
KoboSyncSettings settings = koboSettingsService.getCurrentUserSettings();
double progressPercent = progressFraction * 100.0;
float finishedThreshold = settings.getProgressMarkAsFinishedThreshold() != null
? settings.getProgressMarkAsFinishedThreshold()
: 99f;
float readingThreshold = settings.getProgressMarkAsReadingThreshold() != null
? settings.getProgressMarkAsReadingThreshold()
: 1f;
if (progressPercent >= finishedThreshold) {
userProgress.setReadStatus(ReadStatus.READ);
if (userProgress.getDateFinished() == null) {
userProgress.setDateFinished(Instant.now());
}
} else if (progressPercent >= readingThreshold) {
userProgress.setReadStatus(ReadStatus.READING);
} else {
userProgress.setReadStatus(ReadStatus.UNREAD);
private void updateReadStatusFromKoboProgress(UserBookProgressEntity userProgress, Instant now) {
if (shouldPreserveCurrentStatus(userProgress, now)) {
return;
}
double koboProgressPercent = userProgress.getKoboProgressPercent();
ReadStatus derivedStatus = deriveStatusFromProgress(koboProgressPercent);
userProgress.setReadStatus(derivedStatus);
if (derivedStatus == ReadStatus.READ && userProgress.getDateFinished() == null) {
userProgress.setDateFinished(Instant.now());
}
}
private boolean shouldPreserveCurrentStatus(UserBookProgressEntity progress, Instant now) {
Instant statusModifiedTime = progress.getReadStatusModifiedTime();
if (statusModifiedTime == null) {
return false;
}
Instant statusSentTime = progress.getKoboStatusSentTime();
boolean hasPendingStatusUpdate = statusSentTime == null || statusModifiedTime.isAfter(statusSentTime);
if (hasPendingStatusUpdate) {
return true;
}
boolean withinSyncBufferWindow = now.isBefore(statusSentTime.plusSeconds(STATUS_SYNC_BUFFER_SECONDS));
return withinSyncBufferWindow;
}
private ReadStatus deriveStatusFromProgress(double progressPercent) {
KoboSyncSettings settings = koboSettingsService.getCurrentUserSettings();
float finishedThreshold = settings.getProgressMarkAsFinishedThreshold() != null
? settings.getProgressMarkAsFinishedThreshold() : 99f;
float readingThreshold = settings.getProgressMarkAsReadingThreshold() != null
? settings.getProgressMarkAsReadingThreshold() : 1f;
if (progressPercent >= finishedThreshold) return ReadStatus.READ;
if (progressPercent >= readingThreshold) return ReadStatus.READING;
return ReadStatus.UNREAD;
}
}
@@ -0,0 +1,11 @@
ALTER TABLE user_book_progress
ADD COLUMN IF NOT EXISTS kobo_status_sent_time TIMESTAMP;
ALTER TABLE user_book_progress
ADD COLUMN IF NOT EXISTS read_status_modified_time TIMESTAMP;
ALTER TABLE user_book_progress
ADD COLUMN IF NOT EXISTS kobo_progress_sent_time TIMESTAMP;
ALTER TABLE user_book_progress
CHANGE COLUMN kobo_last_sync_time kobo_progress_received_time TIMESTAMP;