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:
+11
@@ -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;
|
||||
}
|
||||
|
||||
+10
@@ -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;
|
||||
}
|
||||
+6
@@ -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;
|
||||
}
|
||||
|
||||
+15
@@ -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
-1
@@ -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));
|
||||
|
||||
+29
-4
@@ -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())
|
||||
|
||||
+63
@@ -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();
|
||||
}
|
||||
}
|
||||
+127
-2
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
+12
@@ -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;
|
||||
+505
@@ -0,0 +1,505 @@
|
||||
package com.adityachandel.booklore.service;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
|
||||
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 com.adityachandel.booklore.service.kobo.KoboReadingStateService;
|
||||
import com.adityachandel.booklore.service.kobo.KoboSettingsService;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.*;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class KoboReadingStateServiceTest {
|
||||
|
||||
@Mock
|
||||
private KoboReadingStateRepository repository;
|
||||
|
||||
@Mock
|
||||
private KoboReadingStateMapper mapper;
|
||||
|
||||
@Mock
|
||||
private UserBookProgressRepository progressRepository;
|
||||
|
||||
@Mock
|
||||
private BookRepository bookRepository;
|
||||
|
||||
@Mock
|
||||
private UserRepository userRepository;
|
||||
|
||||
@Mock
|
||||
private AuthenticationService authenticationService;
|
||||
|
||||
@Mock
|
||||
private KoboSettingsService koboSettingsService;
|
||||
|
||||
@InjectMocks
|
||||
private KoboReadingStateService service;
|
||||
|
||||
private BookLoreUser testUser;
|
||||
private BookEntity testBook;
|
||||
private BookLoreUserEntity testUserEntity;
|
||||
private KoboSyncSettings testSettings;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
testUser = BookLoreUser.builder()
|
||||
.id(1L)
|
||||
.username("testuser")
|
||||
.build();
|
||||
|
||||
testUserEntity = new BookLoreUserEntity();
|
||||
testUserEntity.setId(1L);
|
||||
testUserEntity.setUsername("testuser");
|
||||
|
||||
testBook = new BookEntity();
|
||||
testBook.setId(100L);
|
||||
|
||||
testSettings = new KoboSyncSettings();
|
||||
testSettings.setProgressMarkAsReadingThreshold(1f);
|
||||
testSettings.setProgressMarkAsFinishedThreshold(99f);
|
||||
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
when(koboSettingsService.getCurrentUserSettings()).thenReturn(testSettings);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should sync Kobo progress to UserBookProgress with valid data")
|
||||
void testSyncKoboProgressToUserBookProgress_Success() {
|
||||
// Arrange
|
||||
String entitlementId = "100";
|
||||
KoboReadingState.CurrentBookmark.Location location = KoboReadingState.CurrentBookmark.Location.builder()
|
||||
.value("epubcfi(/6/4[chap01ref]!/4/2/1:3)")
|
||||
.type("EpubCfi")
|
||||
.source("Kobo")
|
||||
.build();
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(25)
|
||||
.location(location)
|
||||
.build();
|
||||
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(bookmark)
|
||||
.build();
|
||||
|
||||
KoboReadingStateEntity entity = new KoboReadingStateEntity();
|
||||
when(mapper.toEntity(any())).thenReturn(entity);
|
||||
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
|
||||
when(repository.findByEntitlementId(entitlementId)).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.empty());
|
||||
|
||||
ArgumentCaptor<UserBookProgressEntity> progressCaptor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
|
||||
when(progressRepository.save(progressCaptor.capture())).thenReturn(new UserBookProgressEntity());
|
||||
|
||||
// Act
|
||||
KoboReadingStateResponse response = service.saveReadingState(List.of(readingState));
|
||||
|
||||
// Assert
|
||||
assertNotNull(response);
|
||||
assertEquals("Success", response.getRequestResult());
|
||||
assertEquals(1, response.getUpdateResults().size());
|
||||
|
||||
UserBookProgressEntity savedProgress = progressCaptor.getValue();
|
||||
assertNotNull(savedProgress);
|
||||
assertEquals(25.0f, savedProgress.getKoboProgressPercent());
|
||||
assertEquals("epubcfi(/6/4[chap01ref]!/4/2/1:3)", savedProgress.getKoboLocation());
|
||||
assertEquals("EpubCfi", savedProgress.getKoboLocationType());
|
||||
assertEquals("Kobo", savedProgress.getKoboLocationSource());
|
||||
assertNotNull(savedProgress.getKoboLastSyncTime());
|
||||
assertNotNull(savedProgress.getLastReadTime());
|
||||
assertEquals(ReadStatus.READING, savedProgress.getReadStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should update existing progress when syncing Kobo data")
|
||||
void testSyncKoboProgressToUserBookProgress_UpdateExisting() {
|
||||
// Arrange
|
||||
String entitlementId = "100";
|
||||
UserBookProgressEntity existingProgress = new UserBookProgressEntity();
|
||||
existingProgress.setUser(testUserEntity);
|
||||
existingProgress.setBook(testBook);
|
||||
existingProgress.setKoboProgressPercent(10.0f);
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(50)
|
||||
.build();
|
||||
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(bookmark)
|
||||
.build();
|
||||
|
||||
KoboReadingStateEntity entity = new KoboReadingStateEntity();
|
||||
when(mapper.toEntity(any())).thenReturn(entity);
|
||||
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
|
||||
when(repository.findByEntitlementId(entitlementId)).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> progressCaptor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
|
||||
when(progressRepository.save(progressCaptor.capture())).thenReturn(existingProgress);
|
||||
|
||||
// Act
|
||||
service.saveReadingState(List.of(readingState));
|
||||
|
||||
// Assert
|
||||
UserBookProgressEntity savedProgress = progressCaptor.getValue();
|
||||
assertEquals(50.0f, savedProgress.getKoboProgressPercent());
|
||||
assertEquals(ReadStatus.READING, savedProgress.getReadStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should mark book as READ when progress reaches finished threshold")
|
||||
void testSyncKoboProgressToUserBookProgress_MarkAsRead() {
|
||||
// Arrange
|
||||
String entitlementId = "100";
|
||||
testSettings.setProgressMarkAsFinishedThreshold(99f);
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(100)
|
||||
.build();
|
||||
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(bookmark)
|
||||
.build();
|
||||
|
||||
KoboReadingStateEntity entity = new KoboReadingStateEntity();
|
||||
when(mapper.toEntity(any())).thenReturn(entity);
|
||||
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
|
||||
when(repository.findByEntitlementId(entitlementId)).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.empty());
|
||||
|
||||
ArgumentCaptor<UserBookProgressEntity> progressCaptor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
|
||||
when(progressRepository.save(progressCaptor.capture())).thenReturn(new UserBookProgressEntity());
|
||||
|
||||
// Act
|
||||
service.saveReadingState(List.of(readingState));
|
||||
|
||||
// Assert
|
||||
UserBookProgressEntity savedProgress = progressCaptor.getValue();
|
||||
assertEquals(100.0f, savedProgress.getKoboProgressPercent());
|
||||
assertEquals(ReadStatus.READ, savedProgress.getReadStatus());
|
||||
assertNotNull(savedProgress.getDateFinished());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should mark book as READING when progress exceeds reading threshold")
|
||||
void testSyncKoboProgressToUserBookProgress_MarkAsReading() {
|
||||
// Arrange
|
||||
String entitlementId = "100";
|
||||
testSettings.setProgressMarkAsReadingThreshold(1f);
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(1)
|
||||
.build();
|
||||
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(bookmark)
|
||||
.build();
|
||||
|
||||
KoboReadingStateEntity entity = new KoboReadingStateEntity();
|
||||
when(mapper.toEntity(any())).thenReturn(entity);
|
||||
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
|
||||
when(repository.findByEntitlementId(entitlementId)).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.empty());
|
||||
|
||||
ArgumentCaptor<UserBookProgressEntity> progressCaptor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
|
||||
when(progressRepository.save(progressCaptor.capture())).thenReturn(new UserBookProgressEntity());
|
||||
|
||||
// Act
|
||||
service.saveReadingState(List.of(readingState));
|
||||
|
||||
// Assert
|
||||
UserBookProgressEntity savedProgress = progressCaptor.getValue();
|
||||
assertEquals(1.0f, savedProgress.getKoboProgressPercent());
|
||||
assertEquals(ReadStatus.READING, savedProgress.getReadStatus());
|
||||
assertNull(savedProgress.getDateFinished());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should use custom thresholds from settings")
|
||||
void testSyncKoboProgressToUserBookProgress_CustomThresholds() {
|
||||
// Arrange
|
||||
String entitlementId = "100";
|
||||
testSettings.setProgressMarkAsReadingThreshold(5.0f);
|
||||
testSettings.setProgressMarkAsFinishedThreshold(95.0f);
|
||||
|
||||
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(96)
|
||||
.build();
|
||||
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(bookmark)
|
||||
.build();
|
||||
|
||||
KoboReadingStateEntity entity = new KoboReadingStateEntity();
|
||||
when(mapper.toEntity(any())).thenReturn(entity);
|
||||
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
|
||||
when(repository.findByEntitlementId(entitlementId)).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.empty());
|
||||
|
||||
ArgumentCaptor<UserBookProgressEntity> progressCaptor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
|
||||
when(progressRepository.save(progressCaptor.capture())).thenReturn(new UserBookProgressEntity());
|
||||
|
||||
// Act
|
||||
service.saveReadingState(List.of(readingState));
|
||||
|
||||
// Assert
|
||||
UserBookProgressEntity savedProgress = progressCaptor.getValue();
|
||||
assertEquals(ReadStatus.READ, savedProgress.getReadStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle invalid entitlement ID gracefully")
|
||||
void testSyncKoboProgressToUserBookProgress_InvalidEntitlementId() {
|
||||
// Arrange
|
||||
String entitlementId = "not-a-number";
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(KoboReadingState.CurrentBookmark.builder().build())
|
||||
.build();
|
||||
|
||||
KoboReadingStateEntity entity = new KoboReadingStateEntity();
|
||||
when(mapper.toEntity(any())).thenReturn(entity);
|
||||
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
|
||||
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
|
||||
when(repository.save(any())).thenReturn(entity);
|
||||
|
||||
// Act & Assert - should not throw exception
|
||||
assertDoesNotThrow(() -> service.saveReadingState(List.of(readingState)));
|
||||
verify(progressRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle missing book gracefully")
|
||||
void testSyncKoboProgressToUserBookProgress_BookNotFound() {
|
||||
// Arrange
|
||||
String entitlementId = "999";
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(50)
|
||||
.build())
|
||||
.build();
|
||||
|
||||
KoboReadingStateEntity entity = new KoboReadingStateEntity();
|
||||
when(mapper.toEntity(any())).thenReturn(entity);
|
||||
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
|
||||
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
|
||||
when(repository.save(any())).thenReturn(entity);
|
||||
when(bookRepository.findById(999L)).thenReturn(Optional.empty());
|
||||
|
||||
// Act & Assert - should not throw exception
|
||||
assertDoesNotThrow(() -> service.saveReadingState(List.of(readingState)));
|
||||
verify(progressRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should construct reading state from UserBookProgress when no Kobo state exists")
|
||||
void testGetReadingState_ConstructFromProgress() {
|
||||
// Arrange
|
||||
String entitlementId = "100";
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
progress.setKoboProgressPercent(75.5f);
|
||||
progress.setKoboLocation("epubcfi(/6/4[chap01ref]!/4/2/1:3)");
|
||||
progress.setKoboLocationType("EpubCfi");
|
||||
progress.setKoboLocationSource("Kobo");
|
||||
progress.setKoboLastSyncTime(Instant.now());
|
||||
|
||||
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
|
||||
|
||||
// Act
|
||||
KoboReadingStateWrapper result = service.getReadingState(entitlementId);
|
||||
|
||||
// Assert
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getReadingStates());
|
||||
assertEquals(1, result.getReadingStates().size());
|
||||
|
||||
KoboReadingState state = result.getReadingStates().get(0);
|
||||
assertEquals(entitlementId, state.getEntitlementId());
|
||||
assertNotNull(state.getCurrentBookmark());
|
||||
assertEquals(75, state.getCurrentBookmark().getProgressPercent());
|
||||
assertNotNull(state.getCurrentBookmark().getLocation());
|
||||
assertEquals("epubcfi(/6/4[chap01ref]!/4/2/1:3)", state.getCurrentBookmark().getLocation().getValue());
|
||||
assertEquals("EpubCfi", state.getCurrentBookmark().getLocation().getType());
|
||||
assertEquals("Kobo", state.getCurrentBookmark().getLocation().getSource());
|
||||
|
||||
verify(repository).findByEntitlementId(entitlementId);
|
||||
verify(progressRepository).findByUserIdAndBookId(1L, 100L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return null when no Kobo reading state exists and UserBookProgress has no Kobo data")
|
||||
void testGetReadingState_NoKoboDataInProgress() {
|
||||
// Arrange
|
||||
String entitlementId = "100";
|
||||
UserBookProgressEntity progress = new UserBookProgressEntity();
|
||||
// Progress exists but has no Kobo-specific data
|
||||
progress.setKoboProgressPercent(null);
|
||||
progress.setKoboLocation(null);
|
||||
|
||||
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
|
||||
|
||||
// Act
|
||||
KoboReadingStateWrapper result = service.getReadingState(entitlementId);
|
||||
|
||||
// Assert
|
||||
assertNull(result);
|
||||
verify(repository).findByEntitlementId(entitlementId);
|
||||
verify(progressRepository).findByUserIdAndBookId(1L, 100L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return null when no Kobo state and no UserBookProgress exists")
|
||||
void testGetReadingState_NoDataExists() {
|
||||
// Arrange
|
||||
String entitlementId = "100";
|
||||
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.empty());
|
||||
|
||||
// Act
|
||||
KoboReadingStateWrapper result = service.getReadingState(entitlementId);
|
||||
|
||||
// Assert
|
||||
assertNull(result);
|
||||
verify(progressRepository).findByUserIdAndBookId(1L, 100L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should return existing Kobo reading state when it exists")
|
||||
void testGetReadingState_ExistingState() {
|
||||
// Arrange
|
||||
String entitlementId = "100";
|
||||
KoboReadingState existingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.build();
|
||||
|
||||
KoboReadingStateEntity entity = new KoboReadingStateEntity();
|
||||
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.of(entity));
|
||||
when(mapper.toDto(entity)).thenReturn(existingState);
|
||||
|
||||
// Act
|
||||
KoboReadingStateWrapper result = service.getReadingState(entitlementId);
|
||||
|
||||
// Assert
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getReadingStates().size());
|
||||
assertEquals(entitlementId, result.getReadingStates().get(0).getEntitlementId());
|
||||
verify(progressRepository, never()).findByUserIdAndBookId(anyLong(), anyLong());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle null bookmark gracefully")
|
||||
void testSyncKoboProgressToUserBookProgress_NullBookmark() {
|
||||
// Arrange
|
||||
String entitlementId = "100";
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(null)
|
||||
.build();
|
||||
|
||||
KoboReadingStateEntity entity = new KoboReadingStateEntity();
|
||||
when(mapper.toEntity(any())).thenReturn(entity);
|
||||
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
|
||||
when(repository.findByEntitlementId(entitlementId)).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.empty());
|
||||
|
||||
ArgumentCaptor<UserBookProgressEntity> progressCaptor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
|
||||
when(progressRepository.save(progressCaptor.capture())).thenReturn(new UserBookProgressEntity());
|
||||
|
||||
// Act
|
||||
assertDoesNotThrow(() -> service.saveReadingState(List.of(readingState)));
|
||||
|
||||
// Assert
|
||||
UserBookProgressEntity savedProgress = progressCaptor.getValue();
|
||||
assertNull(savedProgress.getKoboProgressPercent());
|
||||
assertNotNull(savedProgress.getKoboLastSyncTime());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should handle null progress percent in bookmark")
|
||||
void testSyncKoboProgressToUserBookProgress_NullProgressPercent() {
|
||||
// Arrange
|
||||
String entitlementId = "100";
|
||||
KoboReadingState.CurrentBookmark bookmark = KoboReadingState.CurrentBookmark.builder()
|
||||
.progressPercent(null)
|
||||
.build();
|
||||
|
||||
KoboReadingState readingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.currentBookmark(bookmark)
|
||||
.build();
|
||||
|
||||
KoboReadingStateEntity entity = new KoboReadingStateEntity();
|
||||
when(mapper.toEntity(any())).thenReturn(entity);
|
||||
when(mapper.toDto(any(KoboReadingStateEntity.class))).thenReturn(readingState);
|
||||
when(repository.findByEntitlementId(entitlementId)).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.empty());
|
||||
|
||||
ArgumentCaptor<UserBookProgressEntity> progressCaptor = ArgumentCaptor.forClass(UserBookProgressEntity.class);
|
||||
when(progressRepository.save(progressCaptor.capture())).thenReturn(new UserBookProgressEntity());
|
||||
|
||||
// Act
|
||||
assertDoesNotThrow(() -> service.saveReadingState(List.of(readingState)));
|
||||
|
||||
// Assert
|
||||
UserBookProgressEntity savedProgress = progressCaptor.getValue();
|
||||
assertNull(savedProgress.getKoboProgressPercent());
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ export interface Book extends FileInfo {
|
||||
pdfProgress?: PdfProgress;
|
||||
cbxProgress?: CbxProgress;
|
||||
koreaderProgress?: KoReaderProgress;
|
||||
koboProgress?: KoboProgress;
|
||||
seriesCount?: number | null;
|
||||
metadataMatchScore?: number | null;
|
||||
readStatus?: ReadStatus;
|
||||
@@ -65,6 +66,10 @@ export interface KoReaderProgress {
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
export interface KoboProgress {
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
export interface BookMetadata {
|
||||
bookId: number;
|
||||
title?: string;
|
||||
|
||||
+22
@@ -364,6 +364,28 @@
|
||||
</span>
|
||||
</p>
|
||||
}
|
||||
@if (book?.koboProgress && book.koboProgress?.percentage != null) {
|
||||
<p class="whitespace-nowrap flex items-center">
|
||||
<span class="font-bold mr-2">Kobo Progress:</span>
|
||||
<span class="inline-flex items-center">
|
||||
<app-tag size="3xs" variant="pill" [color]="getKoProgressColor(book.koboProgress?.percentage)">
|
||||
{{ book.koboProgress?.percentage | number:'1.0-1' }}%
|
||||
</app-tag>
|
||||
@if (book.koboProgress?.percentage !== null) {
|
||||
<p-button
|
||||
pTooltip="Reset progress"
|
||||
tooltipPosition="bottom"
|
||||
icon="pi pi-refresh"
|
||||
size="small"
|
||||
severity="danger"
|
||||
text
|
||||
class="ml-1 custom-button-padding"
|
||||
(onClick)="resetProgress(book, ResetProgressTypes.KOBO)">
|
||||
</p-button>
|
||||
}
|
||||
</span>
|
||||
</p>
|
||||
}
|
||||
@if (selectedReadStatus === ReadStatus.READ) {
|
||||
<div>
|
||||
@if (book?.dateFinished) {
|
||||
|
||||
+48
@@ -100,6 +100,54 @@
|
||||
</p-button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Mark as Reading at: {{ koboSyncSettings.progressMarkAsReadingThreshold?.toFixed(0) }}%</label>
|
||||
<div class="slider-container">
|
||||
<p-slider
|
||||
id="markAsReadingThreshold"
|
||||
name="markAsReadingThreshold"
|
||||
[(ngModel)]="koboSyncSettings.progressMarkAsReadingThreshold"
|
||||
[min]="1"
|
||||
[max]="10"
|
||||
[step]="1"
|
||||
(ngModelChange)="onProgressThresholdsChange()">
|
||||
</p-slider>
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Books are marked as "Reading" when progress exceeds this percentage. This helps automatically track which books you've started.
|
||||
<br>
|
||||
<strong>Recommended:</strong> 1% (default) - marks as reading after the first page or two.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="setting-item">
|
||||
<div class="setting-info">
|
||||
<div class="setting-label-row">
|
||||
<label class="setting-label">Mark as Finished at: {{ koboSyncSettings.progressMarkAsFinishedThreshold?.toFixed(0) }}%</label>
|
||||
<div class="slider-container">
|
||||
<p-slider
|
||||
id="markAsFinishedThreshold"
|
||||
name="markAsFinishedThreshold"
|
||||
[(ngModel)]="koboSyncSettings.progressMarkAsFinishedThreshold"
|
||||
[min]="90"
|
||||
[max]="100"
|
||||
[step]="1"
|
||||
(ngModelChange)="onProgressThresholdsChange()">
|
||||
</p-slider>
|
||||
</div>
|
||||
</div>
|
||||
<p class="setting-description">
|
||||
Books are marked as "Finished" when progress reaches this percentage. Accounts for books where the last few pages are acknowledgments or index.
|
||||
<br>
|
||||
<strong>Recommended:</strong> 99% (default) - marks as finished when nearly complete.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
</form>
|
||||
</div>
|
||||
|
||||
+27
-1
@@ -50,7 +50,9 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy {
|
||||
|
||||
koboSyncSettings: KoboSyncSettings = {
|
||||
token: '',
|
||||
syncEnabled: false
|
||||
syncEnabled: false,
|
||||
progressMarkAsReadingThreshold: 1,
|
||||
progressMarkAsFinishedThreshold: 99
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
@@ -101,6 +103,8 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy {
|
||||
next: (settings: KoboSyncSettings) => {
|
||||
this.koboSyncSettings.token = settings.token;
|
||||
this.koboSyncSettings.syncEnabled = settings.syncEnabled;
|
||||
this.koboSyncSettings.progressMarkAsReadingThreshold = settings.progressMarkAsReadingThreshold ?? 1;
|
||||
this.koboSyncSettings.progressMarkAsFinishedThreshold = settings.progressMarkAsFinishedThreshold ?? 99;
|
||||
this.credentialsSaved = !!settings.token;
|
||||
},
|
||||
error: () => {
|
||||
@@ -198,6 +202,28 @@ export class KoboSyncSettingsComponent implements OnInit, OnDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
onProgressThresholdsChange() {
|
||||
this.koboService.updateProgressThresholds(
|
||||
this.koboSyncSettings.progressMarkAsReadingThreshold,
|
||||
this.koboSyncSettings.progressMarkAsFinishedThreshold
|
||||
).subscribe({
|
||||
next: () => {
|
||||
this.messageService.add({
|
||||
severity: 'success',
|
||||
summary: 'Thresholds Updated',
|
||||
detail: 'Progress thresholds updated successfully'
|
||||
});
|
||||
},
|
||||
error: () => {
|
||||
this.messageService.add({
|
||||
severity: 'error',
|
||||
summary: 'Error',
|
||||
detail: 'Failed to update progress thresholds'
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
saveSettings() {
|
||||
this.settingsHelperService.saveSetting(AppSettingKey.KOBO_SETTINGS, this.koboSettings)
|
||||
.subscribe({
|
||||
|
||||
+13
@@ -6,6 +6,8 @@ import {API_CONFIG} from '../../../../../core/config/api-config';
|
||||
export interface KoboSyncSettings {
|
||||
token: string;
|
||||
syncEnabled: boolean;
|
||||
progressMarkAsReadingThreshold?: number;
|
||||
progressMarkAsFinishedThreshold?: number;
|
||||
}
|
||||
|
||||
@Injectable({
|
||||
@@ -27,4 +29,15 @@ export class KoboService {
|
||||
const params = new HttpParams().set('enabled', enabled.toString());
|
||||
return this.http.put<void>(`${this.baseUrl}/sync`, null, { params });
|
||||
}
|
||||
|
||||
updateProgressThresholds(readingThreshold?: number, finishedThreshold?: number): Observable<KoboSyncSettings> {
|
||||
let params = new HttpParams();
|
||||
if (readingThreshold !== undefined && readingThreshold !== null) {
|
||||
params = params.set('readingThreshold', readingThreshold.toString());
|
||||
}
|
||||
if (finishedThreshold !== undefined && finishedThreshold !== null) {
|
||||
params = params.set('finishedThreshold', finishedThreshold.toString());
|
||||
}
|
||||
return this.http.put<KoboSyncSettings>(`${this.baseUrl}/progress-thresholds`, null, { params });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
export const ResetProgressTypes = {
|
||||
KOREADER: 'KOREADER',
|
||||
BOOKLORE: 'BOOKLORE'
|
||||
BOOKLORE: 'BOOKLORE',
|
||||
KOBO: 'KOBO'
|
||||
} as const;
|
||||
|
||||
export type ResetProgressType = keyof typeof ResetProgressTypes;
|
||||
|
||||
Reference in New Issue
Block a user