Feature: Sync reading progress from Kobo in-built reader (#1541)

* feat: add kobo reading progress sync

* fix: remove old variable references

* fix: avoid changing koreader behaviour

* fix: resolve typo in koreader progress

* fix: remove link between booklore progress and kobo sync progress

* feat: add unit tests for kobo reading status sync

* fix: remove unnecessary conversion value for kobo progress

* fix: resolve issue with kobo_progress beiong optional in template

* fix: update entitlement to provide existing reading progress back to kobo on sync

* fix: use stored bookmark before creating new bookmark

* fix: update default thresholds to full numbers. kobo doesn't report progress with any decimal places

* chore: update unit tests

* fix: remove decimal places in kobo settings progress threshold
This commit is contained in:
CounterClops
2025-11-21 00:17:57 -07:00
committed by GitHub
parent 9eb0dabd5e
commit 7ebdc7b106
20 changed files with 937 additions and 9 deletions
@@ -47,4 +47,15 @@ public class KoboSettingsController {
koboService.setSyncEnabled(enabled);
return ResponseEntity.noContent().build();
}
@Operation(summary = "Update progress thresholds", description = "Update the progress thresholds for marking books as reading or finished. Requires sync permission or admin.")
@ApiResponse(responseCode = "200", description = "Thresholds updated successfully")
@PutMapping("/progress-thresholds")
@PreAuthorize("@securityUtil.canSyncKobo() or @securityUtil.isAdmin()")
public ResponseEntity<KoboSyncSettings> updateProgressThresholds(
@Parameter(description = "Progress percentage to mark as reading (0-100)") @RequestParam(required = false) Float readingThreshold,
@Parameter(description = "Progress percentage to mark as finished (0-100)") @RequestParam(required = false) Float finishedThreshold) {
KoboSyncSettings updated = koboService.updateProgressThresholds(readingThreshold, finishedThreshold);
return ResponseEntity.ok(updated);
}
}
@@ -31,6 +31,7 @@ public class Book {
private EpubProgress epubProgress;
private CbxProgress cbxProgress;
private KoProgress koreaderProgress;
private KoboProgress koboProgress;
private Set<Shelf> shelves;
private String readStatus;
private Instant dateFinished;
@@ -9,4 +9,6 @@ public class KoboSyncSettings {
private String userId;
private String token;
private boolean syncEnabled;
private Float progressMarkAsReadingThreshold;
private Float progressMarkAsFinishedThreshold;
}
@@ -0,0 +1,10 @@
package com.adityachandel.booklore.model.dto.progress;
import lombok.Builder;
import lombok.Data;
@Builder
@Data
public class KoboProgress {
private Float percentage;
}
@@ -24,4 +24,10 @@ public class KoboUserSettingsEntity {
@Column(name = "sync_enabled")
private boolean syncEnabled = true;
@Column(name = "progress_mark_as_reading_threshold")
private Float progressMarkAsReadingThreshold = 1f;
@Column(name = "progress_mark_as_finished_threshold")
private Float progressMarkAsFinishedThreshold = 99f;
}
@@ -60,6 +60,18 @@ public class UserBookProgressEntity {
@Column(name = "koreader_device_id", length = 100)
private String koreaderDeviceId;
@Column(name = "kobo_progress_percent")
private Float koboProgressPercent;
@Column(name = "kobo_location", length = 1000)
private String koboLocation;
@Column(name = "kobo_location_type", length = 50)
private String koboLocationType;
@Column(name = "kobo_location_source", length = 50)
private String koboLocationSource;
@Enumerated(EnumType.STRING)
@Column(name = "read_status")
private ReadStatus readStatus;
@@ -69,4 +81,7 @@ public class UserBookProgressEntity {
@Column(name = "koreader_last_sync_time")
private Instant koreaderLastSyncTime;
@Column(name = "kobo_last_sync_time")
private Instant koboLastSyncTime;
}
@@ -1,5 +1,5 @@
package com.adityachandel.booklore.model.enums;
public enum ResetProgressType {
BOOKLORE, KOREADER
BOOKLORE, KOREADER, KOBO
}
@@ -7,6 +7,7 @@ import com.adityachandel.booklore.model.dto.*;
import com.adityachandel.booklore.model.dto.progress.CbxProgress;
import com.adityachandel.booklore.model.dto.progress.EpubProgress;
import com.adityachandel.booklore.model.dto.progress.KoProgress;
import com.adityachandel.booklore.model.dto.progress.KoboProgress;
import com.adityachandel.booklore.model.dto.progress.PdfProgress;
import com.adityachandel.booklore.model.dto.request.ReadProgressRequest;
import com.adityachandel.booklore.model.dto.response.BookDeletionResponse;
@@ -64,6 +65,12 @@ public class BookService {
private void setBookProgress(Book book, UserBookProgressEntity progress) {
if (progress.getKoboProgressPercent() != null) {
book.setKoboProgress(KoboProgress.builder()
.percentage(progress.getKoboProgressPercent())
.build());
}
switch (book.getBookType()) {
case EPUB -> {
book.setEpubProgress(EpubProgress.builder()
@@ -149,6 +156,12 @@ public class BookService {
book.setShelves(filterShelvesByUserId(book.getShelves(), user.getId()));
book.setLastReadTime(userProgress.getLastReadTime());
if (userProgress.getKoboProgressPercent() != null) {
book.setKoboProgress(KoboProgress.builder()
.percentage(userProgress.getKoboProgressPercent())
.build());
}
if (bookEntity.getBookType() == BookFileType.PDF) {
book.setPdfProgress(PdfProgress.builder()
.page(userProgress.getPdfProgress())
@@ -456,6 +469,12 @@ public class BookService {
progress.setKoreaderDeviceId(null);
progress.setKoreaderDevice(null);
progress.setKoreaderLastSyncTime(null);
} else if (type == ResetProgressType.KOBO) {
progress.setKoboProgressPercent(null);
progress.setKoboLocation(null);
progress.setKoboLocationType(null);
progress.setKoboLocationSource(null);
progress.setKoboLastSyncTime(null);
}
userBookProgressRepository.save(progress);
updatedBooks.add(bookMapper.toBook(bookEntity));
@@ -1,14 +1,20 @@
package com.adityachandel.booklore.service.kobo;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.mapper.KoboReadingStateMapper;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.kobo.*;
import com.adityachandel.booklore.model.dto.settings.KoboSettings;
import com.adityachandel.booklore.model.entity.AuthorEntity;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookMetadataEntity;
import com.adityachandel.booklore.model.entity.CategoryEntity;
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
import com.adityachandel.booklore.model.enums.BookFileType;
import com.adityachandel.booklore.model.enums.KoboBookFormat;
import com.adityachandel.booklore.model.enums.KoboReadStatus;
import com.adityachandel.booklore.repository.KoboReadingStateRepository;
import com.adityachandel.booklore.repository.UserBookProgressRepository;
import com.adityachandel.booklore.service.book.BookQueryService;
import com.adityachandel.booklore.service.appsettings.AppSettingService;
import com.adityachandel.booklore.util.kobo.KoboUrlBuilder;
@@ -32,6 +38,11 @@ public class KoboEntitlementService {
private final KoboUrlBuilder koboUrlBuilder;
private final BookQueryService bookQueryService;
private final AppSettingService appSettingService;
private final UserBookProgressRepository progressRepository;
private final KoboReadingStateRepository readingStateRepository;
private final KoboReadingStateMapper readingStateMapper;
private final AuthenticationService authenticationService;
private final KoboReadingStateBuilder readingStateBuilder;
public List<NewEntitlement> generateNewEntitlements(Set<Long> bookIds, String token, boolean removed) {
List<BookEntity> books = bookQueryService.findAllWithMetadataByIds(bookIds);
@@ -79,9 +90,25 @@ public class KoboEntitlementService {
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(String.valueOf(book.getId()))
.entitlementId(entitlementId)
.created(createdOn.toString())
.lastModified(now.toString())
.statusInfo(KoboReadingState.StatusInfo.builder()
@@ -89,9 +116,7 @@ public class KoboEntitlementService {
.status(KoboReadStatus.READY_TO_READ)
.timesStartedReading(0)
.build())
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
.lastModified(now.toString())
.build())
.currentBookmark(bookmark)
.statistics(KoboReadingState.Statistics.builder()
.lastModified(now.toString())
.build())
@@ -0,0 +1,63 @@
package com.adityachandel.booklore.service.kobo;
import com.adityachandel.booklore.model.dto.kobo.KoboReadingState;
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Optional;
@Component
public class KoboReadingStateBuilder {
public KoboReadingState.CurrentBookmark buildEmptyBookmark(OffsetDateTime timestamp) {
return KoboReadingState.CurrentBookmark.builder()
.lastModified(timestamp.toString())
.build();
}
public KoboReadingState.CurrentBookmark buildBookmarkFromProgress(UserBookProgressEntity progress) {
return buildBookmarkFromProgress(progress, null);
}
public KoboReadingState.CurrentBookmark buildBookmarkFromProgress(UserBookProgressEntity progress, OffsetDateTime defaultTime) {
KoboReadingState.CurrentBookmark.Location location = Optional.ofNullable(progress.getKoboLocation())
.map(loc -> KoboReadingState.CurrentBookmark.Location.builder()
.value(loc)
.type(progress.getKoboLocationType())
.source(progress.getKoboLocationSource())
.build())
.orElse(null);
String lastModified = Optional.ofNullable(progress.getKoboLastSyncTime())
.map(this::formatTimestamp)
.or(() -> Optional.ofNullable(defaultTime).map(OffsetDateTime::toString))
.orElse(null);
return KoboReadingState.CurrentBookmark.builder()
.progressPercent(Optional.ofNullable(progress.getKoboProgressPercent())
.map(Math::round)
.orElse(null))
.location(location)
.lastModified(lastModified)
.build();
}
public KoboReadingState buildReadingStateFromProgress(String entitlementId, UserBookProgressEntity progress) {
KoboReadingState.CurrentBookmark bookmark = buildBookmarkFromProgress(progress);
String lastModified = bookmark.getLastModified();
return KoboReadingState.builder()
.entitlementId(entitlementId)
.currentBookmark(bookmark)
.created(lastModified)
.lastModified(lastModified)
.build();
}
private String formatTimestamp(Instant instant) {
return instant.atOffset(ZoneOffset.UTC).toString();
}
}
@@ -1,25 +1,46 @@
package com.adityachandel.booklore.service.kobo;
import com.adityachandel.booklore.config.security.service.AuthenticationService;
import com.adityachandel.booklore.mapper.KoboReadingStateMapper;
import com.adityachandel.booklore.model.dto.BookLoreUser;
import com.adityachandel.booklore.model.dto.KoboSyncSettings;
import com.adityachandel.booklore.model.dto.kobo.KoboReadingState;
import com.adityachandel.booklore.model.dto.kobo.KoboReadingStateWrapper;
import com.adityachandel.booklore.model.dto.response.kobo.KoboReadingStateResponse;
import com.adityachandel.booklore.model.entity.BookEntity;
import com.adityachandel.booklore.model.entity.BookLoreUserEntity;
import com.adityachandel.booklore.model.entity.KoboReadingStateEntity;
import com.adityachandel.booklore.model.entity.UserBookProgressEntity;
import com.adityachandel.booklore.model.enums.ReadStatus;
import com.adityachandel.booklore.repository.BookRepository;
import com.adityachandel.booklore.repository.KoboReadingStateRepository;
import com.adityachandel.booklore.repository.UserBookProgressRepository;
import com.adityachandel.booklore.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
public class KoboReadingStateService {
private final KoboReadingStateRepository repository;
private final KoboReadingStateMapper mapper;
private final UserBookProgressRepository progressRepository;
private final BookRepository bookRepository;
private final UserRepository userRepository;
private final AuthenticationService authenticationService;
private final KoboSettingsService koboSettingsService;
private final KoboReadingStateBuilder readingStateBuilder;
@Transactional
public KoboReadingStateResponse saveReadingState(List<KoboReadingState> readingStates) {
List<KoboReadingState> koboReadingStates = saveAll(readingStates);
@@ -39,6 +60,8 @@ public class KoboReadingStateService {
}
private List<KoboReadingState> saveAll(List<KoboReadingState> dtos) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
return dtos.stream()
.map(dto -> {
KoboReadingStateEntity entity = repository.findByEntitlementId(dto.getEntitlementId())
@@ -55,16 +78,118 @@ public class KoboReadingStateService {
return newEntity;
});
return repository.save(entity);
KoboReadingStateEntity savedEntity = repository.save(entity);
syncKoboProgressToUserBookProgress(dto, user.getId());
return savedEntity;
})
.map(mapper::toDto)
.collect(Collectors.toList());
}
public KoboReadingStateWrapper getReadingState(String entitlementId) {
Optional<KoboReadingState> readingState = repository.findByEntitlementId(entitlementId).map(mapper::toDto);
Optional<KoboReadingState> readingState = repository.findByEntitlementId(entitlementId)
.map(mapper::toDto)
.or(() -> constructReadingStateFromProgress(entitlementId));
return readingState.map(state -> KoboReadingStateWrapper.builder()
.readingStates(List.of(state))
.build()).orElse(null);
}
private Optional<KoboReadingState> constructReadingStateFromProgress(String entitlementId) {
try {
Long bookId = Long.parseLong(entitlementId);
BookLoreUser user = authenticationService.getAuthenticatedUser();
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);
});
} 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());
Optional<BookEntity> bookOpt = bookRepository.findById(bookId);
if (bookOpt.isEmpty()) {
log.warn("Book not found for entitlement ID: {}", readingState.getEntitlementId());
return;
}
BookEntity book = bookOpt.get();
Optional<BookLoreUserEntity> userOpt = userRepository.findById(userId);
if (userOpt.isEmpty()) {
log.warn("User not found: {}", userId);
return;
}
UserBookProgressEntity progress = progressRepository.findByUserIdAndBookId(userId, bookId)
.orElseGet(() -> {
UserBookProgressEntity newProgress = new UserBookProgressEntity();
newProgress.setUser(userOpt.get());
newProgress.setBook(book);
return newProgress;
});
KoboReadingState.CurrentBookmark bookmark = readingState.getCurrentBookmark();
if (bookmark != null) {
if (bookmark.getProgressPercent() != null) {
progress.setKoboProgressPercent(bookmark.getProgressPercent().floatValue());
}
KoboReadingState.CurrentBookmark.Location location = bookmark.getLocation();
if (location != null) {
progress.setKoboLocation(location.getValue());
progress.setKoboLocationType(location.getType());
progress.setKoboLocationSource(location.getSource());
}
}
progress.setKoboLastSyncTime(Instant.now());
progress.setLastReadTime(Instant.now());
if (progress.getKoboProgressPercent() != null) {
updateKoboReadStatus(progress, progress.getKoboProgressPercent() / 100.0);
}
progressRepository.save(progress);
log.info("Synced Kobo progress to BookLore: userId={}, bookId={}, progress={}%",
userId, 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);
userProgress.setDateFinished(Instant.now());
} else if (progressPercent >= readingThreshold) {
userProgress.setReadStatus(ReadStatus.READING);
} else {
userProgress.setReadStatus(ReadStatus.UNREAD);
}
}
}
@@ -71,6 +71,23 @@ public class KoboSettingsService {
repository.save(entity);
}
@Transactional
public KoboSyncSettings updateProgressThresholds(Float readingThreshold, Float finishedThreshold) {
BookLoreUser user = authenticationService.getAuthenticatedUser();
KoboUserSettingsEntity entity = repository.findByUserId(user.getId())
.orElseGet(() -> initDefaultSettings(user.getId()));
if (readingThreshold != null) {
entity.setProgressMarkAsReadingThreshold(readingThreshold);
}
if (finishedThreshold != null) {
entity.setProgressMarkAsFinishedThreshold(finishedThreshold);
}
repository.save(entity);
return mapToDto(entity);
}
private KoboUserSettingsEntity initDefaultSettings(Long userId) {
ensureKoboShelfExists(userId);
KoboUserSettingsEntity entity = KoboUserSettingsEntity.builder()
@@ -103,6 +120,8 @@ public class KoboSettingsService {
dto.setUserId(entity.getUserId().toString());
dto.setToken(entity.getToken());
dto.setSyncEnabled(entity.isSyncEnabled());
dto.setProgressMarkAsReadingThreshold(entity.getProgressMarkAsReadingThreshold());
dto.setProgressMarkAsFinishedThreshold(entity.getProgressMarkAsFinishedThreshold());
return dto;
}
}
@@ -0,0 +1,12 @@
-- Add Kobo progress tracking columns to user_book_progress table
ALTER TABLE user_book_progress
ADD COLUMN IF NOT EXISTS kobo_progress_percent FLOAT,
ADD COLUMN IF NOT EXISTS kobo_location VARCHAR(1000),
ADD COLUMN IF NOT EXISTS kobo_location_type VARCHAR(50),
ADD COLUMN IF NOT EXISTS kobo_location_source VARCHAR(50),
ADD COLUMN IF NOT EXISTS kobo_last_sync_time TIMESTAMP;
-- Add configurable progress thresholds to kobo_user_settings table
ALTER TABLE kobo_user_settings
ADD COLUMN IF NOT EXISTS progress_mark_as_reading_threshold FLOAT DEFAULT 1,
ADD COLUMN IF NOT EXISTS progress_mark_as_finished_threshold FLOAT DEFAULT 99;