feat(kobo-sync): add user scoped 2 way kobo sync (#2452)
* fix(kobo-sync): Kobo reading state sync by returning the device expected shape and improve management with new DTOs and timestamp normalization - Introduced `KoboReadingStateList` and `KoboReadingStateRequest` DTOs for improved handling of reading states. - Updated `KoboController` to utilize the new DTOs and log request bodies. - Enhanced `KoboReadingStateService` to normalize timestamps during reading state updates and merges. - Adjusted repository queries to include user ID for better data integrity. - Updated tests to reflect changes in DTOs and repository interactions. * feat(kobo-sync): Enhance Kobo reading state management with user ID integration * feat(kobo-sync): Add JSON annotations to KoboReadingStateList for improved serialization * refactor(kobo-sync): Update repository and service methods to enhance reading state retrieval logic - Replaced the existing method for fetching reading states with a new query that orders results by priority and timestamps. - Updated service classes to utilize the new repository method for improved data handling. - Adjusted unit tests to reflect changes in repository interactions. * Enhance KoboReadingStateService and add database migration for user_id - Added a new column `user_id` to the `kobo_reading_state` table with a foreign key constraint referencing the `users` table. - Updated the `KoboReadingStateService` class by adding a new method to check for blank values, improving code readability and maintainability.
This commit is contained in:
@@ -3,7 +3,9 @@ package org.booklore.controller;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.Shelf;
|
||||
import org.booklore.model.dto.kobo.KoboAuthentication;
|
||||
import org.booklore.model.dto.kobo.KoboReadingStateWrapper;
|
||||
import org.booklore.model.dto.kobo.KoboReadingState;
|
||||
import org.booklore.model.dto.kobo.KoboReadingStateList;
|
||||
import org.booklore.model.dto.kobo.KoboReadingStateRequest;
|
||||
import org.booklore.model.dto.kobo.KoboResources;
|
||||
import org.booklore.model.dto.kobo.KoboTestResponse;
|
||||
import org.booklore.service.ShelfService;
|
||||
@@ -149,7 +151,7 @@ public class KoboController {
|
||||
@GetMapping("/v1/library/{bookId}/state")
|
||||
public ResponseEntity<?> getState(@Parameter(description = "Book ID") @PathVariable String bookId) {
|
||||
if (StringUtils.isNumeric(bookId)) {
|
||||
return ResponseEntity.ok(koboReadingStateService.getReadingState(bookId));
|
||||
return ResponseEntity.ok(new KoboReadingStateList(koboReadingStateService.getReadingState(bookId)));
|
||||
} else {
|
||||
return koboServerProxy.proxyCurrentRequest(null, false);
|
||||
}
|
||||
@@ -160,7 +162,7 @@ public class KoboController {
|
||||
@PutMapping("/v1/library/{bookId}/state")
|
||||
public ResponseEntity<?> updateState(
|
||||
@Parameter(description = "Book ID") @PathVariable String bookId,
|
||||
@Parameter(description = "Reading state update body") @RequestBody KoboReadingStateWrapper body) {
|
||||
@Parameter(description = "Reading state update body") @RequestBody KoboReadingStateRequest body) {
|
||||
if (StringUtils.isNumeric(bookId)) {
|
||||
return ResponseEntity.ok(koboReadingStateService.saveReadingState(body.getReadingStates()));
|
||||
} else {
|
||||
|
||||
@@ -21,7 +21,8 @@ public interface KoboReadingStateMapper {
|
||||
@Mapping(target = "statusInfoJson", expression = "java(toJson(dto.getStatusInfo()))")
|
||||
@Mapping(target = "entitlementId", expression = "java(cleanString(dto.getEntitlementId()))")
|
||||
@Mapping(target = "created", expression = "java(dto.getCreated())")
|
||||
@Mapping(target = "lastModified", expression = "java(dto.getLastModified())")
|
||||
@Mapping(target = "lastModifiedString", expression = "java(dto.getLastModified())")
|
||||
@Mapping(target = "lastModified", ignore = true)
|
||||
@Mapping(target = "priorityTimestamp", expression = "java(dto.getPriorityTimestamp())")
|
||||
KoboReadingStateEntity toEntity(KoboReadingState dto);
|
||||
|
||||
@@ -30,7 +31,7 @@ public interface KoboReadingStateMapper {
|
||||
@Mapping(target = "statusInfo", expression = "java(fromJson(entity.getStatusInfoJson(), KoboReadingState.StatusInfo.class))")
|
||||
@Mapping(target = "entitlementId", expression = "java(cleanString(entity.getEntitlementId()))")
|
||||
@Mapping(target = "created", expression = "java(entity.getCreated())")
|
||||
@Mapping(target = "lastModified", expression = "java(entity.getLastModified())")
|
||||
@Mapping(target = "lastModified", expression = "java(entity.getLastModifiedString())")
|
||||
@Mapping(target = "priorityTimestamp", expression = "java(entity.getPriorityTimestamp())")
|
||||
KoboReadingState toDto(KoboReadingStateEntity entity);
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package org.booklore.model.dto.kobo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonNaming;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
|
||||
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public class KoboReadingStateList extends ArrayList<KoboReadingState> {
|
||||
public KoboReadingStateList() {
|
||||
super();
|
||||
}
|
||||
|
||||
public KoboReadingStateList(Collection<KoboReadingState> states) {
|
||||
super(states);
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -10,7 +10,6 @@ import java.util.List;
|
||||
@Data
|
||||
@Builder
|
||||
@JsonNaming(PropertyNamingStrategies.UpperCamelCaseStrategy.class)
|
||||
public class KoboReadingStateWrapper {
|
||||
public class KoboReadingStateRequest {
|
||||
private List<KoboReadingState> readingStates;
|
||||
}
|
||||
|
||||
@@ -17,7 +17,10 @@ public class KoboReadingStateEntity {
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@Column(name = "entitlement_id", nullable = false, unique = true)
|
||||
@Column(name = "user_id")
|
||||
private Long userId;
|
||||
|
||||
@Column(name = "entitlement_id", nullable = false)
|
||||
private String entitlementId;
|
||||
|
||||
@Column(name = "created")
|
||||
|
||||
@@ -8,5 +8,7 @@ import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
public interface KoboReadingStateRepository extends JpaRepository<KoboReadingStateEntity, Long> {
|
||||
Optional<KoboReadingStateEntity> findByEntitlementId(String entitlementId);
|
||||
Optional<KoboReadingStateEntity> findByEntitlementIdAndUserId(String entitlementId, Long userId);
|
||||
Optional<KoboReadingStateEntity> findFirstByEntitlementIdAndUserIdIsNullOrderByPriorityTimestampDescLastModifiedStringDescIdDesc(
|
||||
String entitlementId);
|
||||
}
|
||||
@@ -132,8 +132,12 @@ public class KoboEntitlementService {
|
||||
private KoboReadingState getReadingStateForBook(BookEntity book) {
|
||||
OffsetDateTime now = getCurrentUtc();
|
||||
String entitlementId = String.valueOf(book.getId());
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
|
||||
KoboReadingState existingState = readingStateRepository.findByEntitlementId(entitlementId)
|
||||
KoboReadingState existingState = readingStateRepository.findByEntitlementIdAndUserId(entitlementId, userId)
|
||||
.or(() -> readingStateRepository
|
||||
.findFirstByEntitlementIdAndUserIdIsNullOrderByPriorityTimestampDescLastModifiedStringDescIdDesc(
|
||||
entitlementId))
|
||||
.map(readingStateMapper::toDto)
|
||||
.orElse(null);
|
||||
|
||||
|
||||
+255
-18
@@ -5,7 +5,6 @@ import org.booklore.mapper.KoboReadingStateMapper;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.KoboSyncSettings;
|
||||
import org.booklore.model.dto.kobo.KoboReadingState;
|
||||
import org.booklore.model.dto.kobo.KoboReadingStateWrapper;
|
||||
import org.booklore.model.dto.response.kobo.KoboReadingStateResponse;
|
||||
import org.booklore.model.entity.*;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
@@ -21,6 +20,13 @@ import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeFormatterBuilder;
|
||||
import java.time.temporal.ChronoField;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
@@ -31,6 +37,14 @@ import java.util.stream.Collectors;
|
||||
public class KoboReadingStateService {
|
||||
|
||||
private static final int STATUS_SYNC_BUFFER_SECONDS = 10;
|
||||
private static final DateTimeFormatter KOBO_TIMESTAMP_FORMAT =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'").withZone(ZoneOffset.UTC);
|
||||
private static final DateTimeFormatter LOCAL_TIMESTAMP_FORMAT = new DateTimeFormatterBuilder()
|
||||
.appendPattern("yyyy-MM-dd HH:mm:ss")
|
||||
.optionalStart()
|
||||
.appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
|
||||
.optionalEnd()
|
||||
.toFormatter();
|
||||
|
||||
private final KoboReadingStateRepository repository;
|
||||
private final KoboReadingStateMapper mapper;
|
||||
@@ -45,6 +59,7 @@ public class KoboReadingStateService {
|
||||
|
||||
@Transactional
|
||||
public KoboReadingStateResponse saveReadingState(List<KoboReadingState> readingStates) {
|
||||
normalizePutTimestamps(readingStates);
|
||||
List<KoboReadingState> koboReadingStates = saveAll(readingStates);
|
||||
|
||||
List<KoboReadingStateResponse.UpdateResult> updateResults = koboReadingStates.stream()
|
||||
@@ -64,26 +79,43 @@ public class KoboReadingStateService {
|
||||
|
||||
private List<KoboReadingState> saveAll(List<KoboReadingState> dtos) {
|
||||
BookLoreUser user = authenticationService.getAuthenticatedUser();
|
||||
Long userId = user.getId();
|
||||
|
||||
return dtos.stream()
|
||||
.map(dto -> {
|
||||
KoboReadingStateEntity entity = repository.findByEntitlementId(dto.getEntitlementId())
|
||||
.map(existing -> {
|
||||
existing.setCurrentBookmarkJson(mapper.toJson(dto.getCurrentBookmark()));
|
||||
existing.setStatisticsJson(mapper.toJson(dto.getStatistics()));
|
||||
existing.setStatusInfoJson(mapper.toJson(dto.getStatusInfo()));
|
||||
existing.setLastModifiedString(mapper.cleanString(String.valueOf(dto.getLastModified())));
|
||||
return existing;
|
||||
})
|
||||
String entitlementId = mapper.cleanString(dto.getEntitlementId());
|
||||
Optional<KoboReadingStateEntity> existingOpt =
|
||||
repository.findByEntitlementIdAndUserId(entitlementId, userId);
|
||||
log.debug("Kobo reading state lookup: entitlementId={}, foundExisting={}",
|
||||
entitlementId, existingOpt.isPresent());
|
||||
KoboReadingStateEntity entity = existingOpt
|
||||
.map(existing -> mergeReadingState(existing, dto))
|
||||
.orElseGet(() -> {
|
||||
KoboReadingStateEntity newEntity = mapper.toEntity(dto);
|
||||
newEntity.setCreated(mapper.cleanString(String.valueOf(dto.getCreated())));
|
||||
newEntity.setUserId(userId);
|
||||
if (entitlementId != null && !entitlementId.isBlank()) {
|
||||
newEntity.setEntitlementId(entitlementId);
|
||||
}
|
||||
String created = normalizeTimestampValue(dto.getCreated());
|
||||
if (isBlank(created)) {
|
||||
created = KOBO_TIMESTAMP_FORMAT.format(Instant.now());
|
||||
}
|
||||
String lastModified = normalizeTimestampValue(dto.getLastModified());
|
||||
if (isBlank(lastModified)) {
|
||||
lastModified = created;
|
||||
}
|
||||
dto.setLastModified(lastModified);
|
||||
dto.setCreated(created);
|
||||
newEntity.setLastModifiedString(mapper.cleanString(lastModified));
|
||||
newEntity.setPriorityTimestamp(mapper.cleanString(computePriorityTimestamp(dto)));
|
||||
newEntity.setCreated(mapper.cleanString(created));
|
||||
return newEntity;
|
||||
});
|
||||
|
||||
KoboReadingStateEntity savedEntity = repository.save(entity);
|
||||
KoboReadingState savedState = mapper.toDto(savedEntity);
|
||||
|
||||
syncKoboProgressToUserBookProgress(dto, user.getId());
|
||||
syncKoboProgressToUserBookProgress(savedState, userId);
|
||||
|
||||
return savedEntity;
|
||||
})
|
||||
@@ -93,17 +125,26 @@ public class KoboReadingStateService {
|
||||
|
||||
@Transactional
|
||||
public void deleteReadingState(Long bookId) {
|
||||
repository.findByEntitlementId(String.valueOf(bookId)).ifPresent(repository::delete);
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
repository.findByEntitlementIdAndUserId(String.valueOf(bookId), userId).ifPresent(repository::delete);
|
||||
}
|
||||
|
||||
public KoboReadingStateWrapper getReadingState(String entitlementId) {
|
||||
Optional<KoboReadingState> readingState = repository.findByEntitlementId(entitlementId)
|
||||
public List<KoboReadingState> getReadingState(String entitlementId) {
|
||||
Long userId = authenticationService.getAuthenticatedUser().getId();
|
||||
Optional<KoboReadingState> readingState = repository.findByEntitlementIdAndUserId(entitlementId, userId)
|
||||
.map(mapper::toDto)
|
||||
.or(() -> repository
|
||||
.findFirstByEntitlementIdAndUserIdIsNullOrderByPriorityTimestampDescLastModifiedStringDescIdDesc(
|
||||
entitlementId)
|
||||
.map(mapper::toDto))
|
||||
.or(() -> constructReadingStateFromProgress(entitlementId));
|
||||
|
||||
return readingState.map(state -> KoboReadingStateWrapper.builder()
|
||||
.readingStates(List.of(state))
|
||||
.build()).orElse(null);
|
||||
|
||||
return readingState
|
||||
.map(state -> {
|
||||
normalizeResponseTimestamps(state);
|
||||
return List.of(state);
|
||||
})
|
||||
.orElse(List.of());
|
||||
}
|
||||
|
||||
private Optional<KoboReadingState> constructReadingStateFromProgress(String entitlementId) {
|
||||
@@ -184,6 +225,202 @@ public class KoboReadingStateService {
|
||||
}
|
||||
}
|
||||
|
||||
private void normalizePutTimestamps(List<KoboReadingState> readingStates) {
|
||||
if (readingStates == null || readingStates.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
String requestTimestamp = KOBO_TIMESTAMP_FORMAT.format(Instant.now());
|
||||
readingStates.forEach(state -> {
|
||||
if (isBlank(state.getPriorityTimestamp())) {
|
||||
state.setPriorityTimestamp(requestTimestamp);
|
||||
}
|
||||
if (isBlank(state.getLastModified())) {
|
||||
state.setLastModified(requestTimestamp);
|
||||
}
|
||||
if (state.getStatusInfo() != null) {
|
||||
if (isBlank(state.getStatusInfo().getLastModified())) {
|
||||
state.getStatusInfo().setLastModified(requestTimestamp);
|
||||
}
|
||||
}
|
||||
if (state.getStatistics() != null) {
|
||||
if (isBlank(state.getStatistics().getLastModified())) {
|
||||
state.getStatistics().setLastModified(requestTimestamp);
|
||||
}
|
||||
}
|
||||
if (state.getCurrentBookmark() != null) {
|
||||
if (isBlank(state.getCurrentBookmark().getLastModified())) {
|
||||
state.getCurrentBookmark().setLastModified(requestTimestamp);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void normalizeResponseTimestamps(KoboReadingState state) {
|
||||
if (state == null) {
|
||||
return;
|
||||
}
|
||||
state.setCreated(normalizeTimestampValue(state.getCreated()));
|
||||
state.setLastModified(normalizeTimestampValue(state.getLastModified()));
|
||||
state.setPriorityTimestamp(normalizeTimestampValue(state.getPriorityTimestamp()));
|
||||
if (state.getStatusInfo() != null) {
|
||||
state.getStatusInfo().setLastModified(normalizeTimestampValue(state.getStatusInfo().getLastModified()));
|
||||
}
|
||||
if (state.getStatistics() != null) {
|
||||
state.getStatistics().setLastModified(normalizeTimestampValue(state.getStatistics().getLastModified()));
|
||||
}
|
||||
if (state.getCurrentBookmark() != null) {
|
||||
state.getCurrentBookmark().setLastModified(normalizeTimestampValue(state.getCurrentBookmark().getLastModified()));
|
||||
}
|
||||
}
|
||||
|
||||
private String normalizeTimestampValue(String value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = value.trim();
|
||||
if (trimmed.isEmpty() || "null".equalsIgnoreCase(trimmed)) {
|
||||
return value;
|
||||
}
|
||||
try {
|
||||
Instant instant = Instant.parse(trimmed).truncatedTo(ChronoUnit.SECONDS);
|
||||
return KOBO_TIMESTAMP_FORMAT.format(instant);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
try {
|
||||
OffsetDateTime offsetDateTime = OffsetDateTime.parse(trimmed);
|
||||
return KOBO_TIMESTAMP_FORMAT.format(offsetDateTime.toInstant().truncatedTo(ChronoUnit.SECONDS));
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
try {
|
||||
LocalDateTime localDateTime = LocalDateTime.parse(trimmed, LOCAL_TIMESTAMP_FORMAT);
|
||||
return KOBO_TIMESTAMP_FORMAT.format(localDateTime.toInstant(ZoneOffset.UTC).truncatedTo(ChronoUnit.SECONDS));
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
private KoboReadingStateEntity mergeReadingState(KoboReadingStateEntity existing, KoboReadingState incoming) {
|
||||
KoboReadingState existingState = mapper.toDto(existing);
|
||||
if (existingState == null) {
|
||||
existingState = KoboReadingState.builder().entitlementId(existing.getEntitlementId()).build();
|
||||
}
|
||||
|
||||
KoboReadingState merged = mergeReadingState(existingState, incoming);
|
||||
|
||||
existing.setCurrentBookmarkJson(mapper.toJson(merged.getCurrentBookmark()));
|
||||
existing.setStatisticsJson(mapper.toJson(merged.getStatistics()));
|
||||
existing.setStatusInfoJson(mapper.toJson(merged.getStatusInfo()));
|
||||
existing.setLastModifiedString(mapper.cleanString(merged.getLastModified()));
|
||||
existing.setPriorityTimestamp(mapper.cleanString(merged.getPriorityTimestamp()));
|
||||
return existing;
|
||||
}
|
||||
|
||||
private KoboReadingState mergeReadingState(KoboReadingState existing, KoboReadingState incoming) {
|
||||
KoboReadingState.StatusInfo statusInfo = existing.getStatusInfo();
|
||||
KoboReadingState.Statistics statistics = existing.getStatistics();
|
||||
KoboReadingState.CurrentBookmark currentBookmark = existing.getCurrentBookmark();
|
||||
String lastModified = existing.getLastModified();
|
||||
|
||||
if (incoming.getStatusInfo() != null && isIncomingNewer(incoming.getStatusInfo().getLastModified(),
|
||||
statusInfo != null ? statusInfo.getLastModified() : null)) {
|
||||
statusInfo = incoming.getStatusInfo();
|
||||
}
|
||||
if (incoming.getStatistics() != null && isIncomingNewer(incoming.getStatistics().getLastModified(),
|
||||
statistics != null ? statistics.getLastModified() : null)) {
|
||||
statistics = incoming.getStatistics();
|
||||
}
|
||||
if (incoming.getCurrentBookmark() != null && isIncomingNewer(incoming.getCurrentBookmark().getLastModified(),
|
||||
currentBookmark != null ? currentBookmark.getLastModified() : null)) {
|
||||
currentBookmark = incoming.getCurrentBookmark();
|
||||
}
|
||||
if (isIncomingNewer(incoming.getLastModified(), lastModified)) {
|
||||
lastModified = incoming.getLastModified();
|
||||
}
|
||||
|
||||
KoboReadingState merged = KoboReadingState.builder()
|
||||
.entitlementId(existing.getEntitlementId())
|
||||
.created(firstNonBlank(existing.getCreated(), incoming.getCreated()))
|
||||
.lastModified(lastModified)
|
||||
.statusInfo(statusInfo)
|
||||
.statistics(statistics)
|
||||
.currentBookmark(currentBookmark)
|
||||
.build();
|
||||
merged.setPriorityTimestamp(computePriorityTimestamp(merged));
|
||||
return merged;
|
||||
}
|
||||
|
||||
private boolean isIncomingNewer(String incoming, String existing) {
|
||||
if (isBlank(incoming)) {
|
||||
return false;
|
||||
}
|
||||
if (isBlank(existing)) {
|
||||
return true;
|
||||
}
|
||||
Instant incomingInstant = parseTimestamp(incoming);
|
||||
Instant existingInstant = parseTimestamp(existing);
|
||||
if (incomingInstant == null || existingInstant == null) {
|
||||
return false;
|
||||
}
|
||||
return incomingInstant.isAfter(existingInstant);
|
||||
}
|
||||
|
||||
private String computePriorityTimestamp(KoboReadingState state) {
|
||||
Instant maxInstant = maxInstant(
|
||||
state.getLastModified(),
|
||||
state.getStatusInfo() != null ? state.getStatusInfo().getLastModified() : null,
|
||||
state.getStatistics() != null ? state.getStatistics().getLastModified() : null,
|
||||
state.getCurrentBookmark() != null ? state.getCurrentBookmark().getLastModified() : null
|
||||
);
|
||||
if (maxInstant == null) {
|
||||
String fallback = firstNonBlank(state.getPriorityTimestamp(), state.getLastModified());
|
||||
return normalizeTimestampValue(fallback);
|
||||
}
|
||||
return KOBO_TIMESTAMP_FORMAT.format(maxInstant);
|
||||
}
|
||||
|
||||
private Instant maxInstant(String... candidates) {
|
||||
Instant max = null;
|
||||
for (String candidate : candidates) {
|
||||
Instant parsed = parseTimestamp(candidate);
|
||||
if (parsed == null) {
|
||||
continue;
|
||||
}
|
||||
if (max == null || parsed.isAfter(max)) {
|
||||
max = parsed;
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
private Instant parseTimestamp(String value) {
|
||||
if (isBlank(value)) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = value.trim();
|
||||
try {
|
||||
return Instant.parse(trimmed);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
try {
|
||||
return OffsetDateTime.parse(trimmed).toInstant();
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
try {
|
||||
LocalDateTime localDateTime = LocalDateTime.parse(trimmed, LOCAL_TIMESTAMP_FORMAT);
|
||||
return localDateTime.toInstant(ZoneOffset.UTC);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String firstNonBlank(String primary, String fallback) {
|
||||
return isBlank(primary) ? fallback : primary;
|
||||
}
|
||||
|
||||
private boolean isBlank(String value) {
|
||||
return value == null || value.trim().isEmpty() || "null".equalsIgnoreCase(value.trim());
|
||||
}
|
||||
|
||||
private void saveToFileProgress(BookLoreUserEntity user, BookEntity book, UserBookProgressEntity progress) {
|
||||
try {
|
||||
BookFileEntity primaryFile = book.getPrimaryBookFile();
|
||||
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
ALTER TABLE kobo_reading_state
|
||||
ADD COLUMN IF NOT EXISTS user_id BIGINT NULL;
|
||||
|
||||
ALTER TABLE kobo_reading_state
|
||||
ADD CONSTRAINT fk_kobo_reading_state_user
|
||||
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE;
|
||||
|
||||
ALTER TABLE kobo_reading_state
|
||||
DROP INDEX IF EXISTS entitlement_id;
|
||||
|
||||
ALTER TABLE kobo_reading_state
|
||||
ADD UNIQUE INDEX uq_kobo_reading_state_user_entitlement (user_id, entitlement_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_kobo_reading_state_entitlement_id
|
||||
ON kobo_reading_state (entitlement_id);
|
||||
@@ -5,12 +5,12 @@ import org.booklore.mapper.KoboReadingStateMapper;
|
||||
import org.booklore.model.dto.BookLoreUser;
|
||||
import org.booklore.model.dto.KoboSyncSettings;
|
||||
import org.booklore.model.dto.kobo.KoboReadingState;
|
||||
import org.booklore.model.dto.kobo.KoboReadingStateWrapper;
|
||||
import org.booklore.model.entity.BookEntity;
|
||||
import org.booklore.model.entity.BookLoreUserEntity;
|
||||
import org.booklore.model.entity.KoboReadingStateEntity;
|
||||
import org.booklore.model.entity.UserBookProgressEntity;
|
||||
import org.booklore.model.enums.ReadStatus;
|
||||
import org.booklore.model.enums.KoboReadStatus;
|
||||
import org.booklore.repository.BookRepository;
|
||||
import org.booklore.repository.KoboReadingStateRepository;
|
||||
import org.booklore.repository.UserBookProgressRepository;
|
||||
@@ -30,6 +30,8 @@ import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
@@ -96,6 +98,12 @@ class KoboReadingStateServiceTest {
|
||||
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
when(koboSettingsService.getCurrentUserSettings()).thenReturn(testSettings);
|
||||
lenient().when(repository
|
||||
.findFirstByEntitlementIdAndUserIdIsNullOrderByPriorityTimestampDescLastModifiedStringDescIdDesc(
|
||||
anyString()))
|
||||
.thenReturn(Optional.empty());
|
||||
lenient().when(mapper.toJson(any())).thenCallRealMethod();
|
||||
lenient().when(mapper.cleanString(any())).thenCallRealMethod();
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -124,7 +132,7 @@ class KoboReadingStateServiceTest {
|
||||
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.findByEntitlementIdAndUserId(entitlementId, 1L)).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));
|
||||
@@ -154,7 +162,7 @@ class KoboReadingStateServiceTest {
|
||||
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.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
|
||||
when(repository.save(any())).thenReturn(entity);
|
||||
|
||||
assertDoesNotThrow(() -> service.saveReadingState(List.of(readingState)));
|
||||
@@ -175,7 +183,7 @@ class KoboReadingStateServiceTest {
|
||||
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.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
|
||||
when(repository.save(any())).thenReturn(entity);
|
||||
when(bookRepository.findById(999L)).thenReturn(Optional.empty());
|
||||
|
||||
@@ -206,18 +214,17 @@ class KoboReadingStateServiceTest {
|
||||
.build())
|
||||
.build();
|
||||
|
||||
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
|
||||
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
|
||||
when(readingStateBuilder.buildReadingStateFromProgress(entitlementId, progress)).thenReturn(expectedState);
|
||||
|
||||
KoboReadingStateWrapper result = service.getReadingState(entitlementId);
|
||||
List<KoboReadingState> result = service.getReadingState(entitlementId);
|
||||
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.getReadingStates());
|
||||
assertEquals(1, result.getReadingStates().size());
|
||||
assertEquals(1, result.size());
|
||||
|
||||
KoboReadingState state = result.getReadingStates().getFirst();
|
||||
KoboReadingState state = result.getFirst();
|
||||
assertEquals(entitlementId, state.getEntitlementId());
|
||||
assertNotNull(state.getCurrentBookmark());
|
||||
assertEquals(75, state.getCurrentBookmark().getProgressPercent());
|
||||
@@ -226,7 +233,7 @@ class KoboReadingStateServiceTest {
|
||||
assertEquals("EpubCfi", state.getCurrentBookmark().getLocation().getType());
|
||||
assertEquals("Kobo", state.getCurrentBookmark().getLocation().getSource());
|
||||
|
||||
verify(repository).findByEntitlementId(entitlementId);
|
||||
verify(repository).findByEntitlementIdAndUserId(entitlementId, 1L);
|
||||
verify(progressRepository).findByUserIdAndBookId(1L, 100L);
|
||||
verify(readingStateBuilder).buildReadingStateFromProgress(entitlementId, progress);
|
||||
}
|
||||
@@ -239,14 +246,15 @@ class KoboReadingStateServiceTest {
|
||||
progress.setKoboProgressPercent(null);
|
||||
progress.setKoboLocation(null);
|
||||
|
||||
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
|
||||
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.of(progress));
|
||||
|
||||
KoboReadingStateWrapper result = service.getReadingState(entitlementId);
|
||||
List<KoboReadingState> result = service.getReadingState(entitlementId);
|
||||
|
||||
assertNull(result);
|
||||
verify(repository).findByEntitlementId(entitlementId);
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
verify(repository).findByEntitlementIdAndUserId(entitlementId, 1L);
|
||||
verify(progressRepository).findByUserIdAndBookId(1L, 100L);
|
||||
}
|
||||
|
||||
@@ -254,13 +262,14 @@ class KoboReadingStateServiceTest {
|
||||
@DisplayName("Should return null when no Kobo state and no UserBookProgress exists")
|
||||
void testGetReadingState_NoDataExists() {
|
||||
String entitlementId = "100";
|
||||
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.empty());
|
||||
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
|
||||
when(authenticationService.getAuthenticatedUser()).thenReturn(testUser);
|
||||
when(progressRepository.findByUserIdAndBookId(1L, 100L)).thenReturn(Optional.empty());
|
||||
|
||||
KoboReadingStateWrapper result = service.getReadingState(entitlementId);
|
||||
List<KoboReadingState> result = service.getReadingState(entitlementId);
|
||||
|
||||
assertNull(result);
|
||||
assertNotNull(result);
|
||||
assertTrue(result.isEmpty());
|
||||
verify(progressRepository).findByUserIdAndBookId(1L, 100L);
|
||||
}
|
||||
|
||||
@@ -273,14 +282,14 @@ class KoboReadingStateServiceTest {
|
||||
.build();
|
||||
|
||||
KoboReadingStateEntity entity = new KoboReadingStateEntity();
|
||||
when(repository.findByEntitlementId(entitlementId)).thenReturn(Optional.of(entity));
|
||||
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.of(entity));
|
||||
when(mapper.toDto(entity)).thenReturn(existingState);
|
||||
|
||||
KoboReadingStateWrapper result = service.getReadingState(entitlementId);
|
||||
List<KoboReadingState> result = service.getReadingState(entitlementId);
|
||||
|
||||
assertNotNull(result);
|
||||
assertEquals(1, result.getReadingStates().size());
|
||||
assertEquals(entitlementId, result.getReadingStates().getFirst().getEntitlementId());
|
||||
assertEquals(1, result.size());
|
||||
assertEquals(entitlementId, result.getFirst().getEntitlementId());
|
||||
verify(progressRepository, never()).findByUserIdAndBookId(anyLong(), anyLong());
|
||||
}
|
||||
|
||||
@@ -296,7 +305,7 @@ class KoboReadingStateServiceTest {
|
||||
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.findByEntitlementIdAndUserId(entitlementId, 1L)).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));
|
||||
@@ -328,7 +337,7 @@ class KoboReadingStateServiceTest {
|
||||
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.findByEntitlementIdAndUserId(entitlementId, 1L)).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));
|
||||
@@ -342,4 +351,132 @@ class KoboReadingStateServiceTest {
|
||||
UserBookProgressEntity savedProgress = progressCaptor.getValue();
|
||||
assertNull(savedProgress.getKoboProgressPercent());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should merge per-field updates based on lastModified")
|
||||
void testSaveReadingState_PerFieldMerge() throws Exception {
|
||||
String entitlementId = "100";
|
||||
String existingTimestamp = "2025-01-01T00:00:00.0000000Z";
|
||||
String newerTimestamp = "2025-01-04T00:00:00.0000000Z";
|
||||
String midTimestamp = "2025-01-03T00:00:00.0000000Z";
|
||||
String olderTimestamp = "2025-01-02T00:00:00.0000000Z";
|
||||
|
||||
KoboReadingState.StatusInfo existingStatus = KoboReadingState.StatusInfo.builder()
|
||||
.lastModified(existingTimestamp)
|
||||
.status(KoboReadStatus.READING)
|
||||
.timesStartedReading(1)
|
||||
.build();
|
||||
KoboReadingState.Statistics existingStats = KoboReadingState.Statistics.builder()
|
||||
.lastModified(existingTimestamp)
|
||||
.spentReadingMinutes(5)
|
||||
.remainingTimeMinutes(20)
|
||||
.build();
|
||||
KoboReadingState.CurrentBookmark existingBookmark = KoboReadingState.CurrentBookmark.builder()
|
||||
.lastModified(midTimestamp)
|
||||
.progressPercent(25)
|
||||
.build();
|
||||
|
||||
KoboReadingState existingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.created(existingTimestamp)
|
||||
.lastModified(midTimestamp)
|
||||
.statusInfo(existingStatus)
|
||||
.statistics(existingStats)
|
||||
.currentBookmark(existingBookmark)
|
||||
.priorityTimestamp(midTimestamp)
|
||||
.build();
|
||||
|
||||
KoboReadingState.StatusInfo incomingStatus = KoboReadingState.StatusInfo.builder()
|
||||
.lastModified(newerTimestamp)
|
||||
.status(KoboReadStatus.FINISHED)
|
||||
.timesStartedReading(2)
|
||||
.build();
|
||||
KoboReadingState.CurrentBookmark incomingBookmark = KoboReadingState.CurrentBookmark.builder()
|
||||
.lastModified(olderTimestamp)
|
||||
.progressPercent(10)
|
||||
.build();
|
||||
|
||||
KoboReadingState incomingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.lastModified(newerTimestamp)
|
||||
.statusInfo(incomingStatus)
|
||||
.currentBookmark(incomingBookmark)
|
||||
.build();
|
||||
|
||||
KoboReadingStateEntity existingEntity = new KoboReadingStateEntity();
|
||||
existingEntity.setEntitlementId(entitlementId);
|
||||
existingEntity.setUserId(1L);
|
||||
|
||||
when(mapper.toDto(existingEntity)).thenReturn(existingState);
|
||||
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.of(existingEntity));
|
||||
when(repository.save(any())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
|
||||
ArgumentCaptor<KoboReadingStateEntity> entityCaptor = ArgumentCaptor.forClass(KoboReadingStateEntity.class);
|
||||
service.saveReadingState(List.of(incomingState));
|
||||
verify(repository).save(entityCaptor.capture());
|
||||
|
||||
KoboReadingStateEntity saved = entityCaptor.getValue();
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
KoboReadingState.StatusInfo savedStatus = objectMapper.readValue(saved.getStatusInfoJson(), KoboReadingState.StatusInfo.class);
|
||||
KoboReadingState.CurrentBookmark savedBookmark = objectMapper.readValue(saved.getCurrentBookmarkJson(), KoboReadingState.CurrentBookmark.class);
|
||||
KoboReadingState.Statistics savedStatistics = objectMapper.readValue(saved.getStatisticsJson(), KoboReadingState.Statistics.class);
|
||||
|
||||
assertEquals(incomingStatus.getStatus(), savedStatus.getStatus());
|
||||
assertEquals(existingBookmark.getProgressPercent(), savedBookmark.getProgressPercent());
|
||||
assertEquals(existingStats.getSpentReadingMinutes(), savedStatistics.getSpentReadingMinutes());
|
||||
assertEquals(newerTimestamp, saved.getLastModifiedString());
|
||||
assertEquals(newerTimestamp, saved.getPriorityTimestamp());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Should not update fields when timestamps are equal")
|
||||
void testSaveReadingState_EqualTimestampNoUpdate() throws Exception {
|
||||
String entitlementId = "100";
|
||||
String timestamp = "2025-01-01T00:00:00.0000000Z";
|
||||
|
||||
KoboReadingState.StatusInfo existingStatus = KoboReadingState.StatusInfo.builder()
|
||||
.lastModified(timestamp)
|
||||
.status(KoboReadStatus.READING)
|
||||
.timesStartedReading(1)
|
||||
.build();
|
||||
|
||||
KoboReadingState existingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.created(timestamp)
|
||||
.lastModified(timestamp)
|
||||
.statusInfo(existingStatus)
|
||||
.priorityTimestamp(timestamp)
|
||||
.build();
|
||||
|
||||
KoboReadingState.StatusInfo incomingStatus = KoboReadingState.StatusInfo.builder()
|
||||
.lastModified(timestamp)
|
||||
.status(KoboReadStatus.FINISHED)
|
||||
.timesStartedReading(2)
|
||||
.build();
|
||||
|
||||
KoboReadingState incomingState = KoboReadingState.builder()
|
||||
.entitlementId(entitlementId)
|
||||
.lastModified(timestamp)
|
||||
.statusInfo(incomingStatus)
|
||||
.build();
|
||||
|
||||
KoboReadingStateEntity existingEntity = new KoboReadingStateEntity();
|
||||
existingEntity.setEntitlementId(entitlementId);
|
||||
existingEntity.setUserId(1L);
|
||||
|
||||
when(mapper.toDto(existingEntity)).thenReturn(existingState);
|
||||
when(repository.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.of(existingEntity));
|
||||
when(repository.save(any())).thenAnswer(invocation -> invocation.getArgument(0));
|
||||
|
||||
ArgumentCaptor<KoboReadingStateEntity> entityCaptor = ArgumentCaptor.forClass(KoboReadingStateEntity.class);
|
||||
service.saveReadingState(List.of(incomingState));
|
||||
verify(repository).save(entityCaptor.capture());
|
||||
|
||||
KoboReadingStateEntity saved = entityCaptor.getValue();
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
KoboReadingState.StatusInfo savedStatus = objectMapper.readValue(saved.getStatusInfoJson(), KoboReadingState.StatusInfo.class);
|
||||
|
||||
assertEquals(existingStatus.getStatus(), savedStatus.getStatus());
|
||||
assertEquals(timestamp, saved.getLastModifiedString());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -86,13 +86,19 @@ class KoboStatusSyncProtectionTest {
|
||||
when(koboSettingsService.getCurrentUserSettings()).thenReturn(testSettings);
|
||||
when(bookRepository.findById(100L)).thenReturn(Optional.of(testBook));
|
||||
when(userRepository.findById(1L)).thenReturn(Optional.of(testUserEntity));
|
||||
lenient().when(repository
|
||||
.findFirstByEntitlementIdAndUserIdIsNullOrderByPriorityTimestampDescLastModifiedStringDescIdDesc(
|
||||
anyString()))
|
||||
.thenReturn(Optional.empty());
|
||||
lenient().when(mapper.toJson(any())).thenCallRealMethod();
|
||||
lenient().when(mapper.cleanString(any())).thenCallRealMethod();
|
||||
}
|
||||
|
||||
private void setupMocksForSave(String entitlementId, KoboReadingState readingState) {
|
||||
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.findByEntitlementIdAndUserId(entitlementId, 1L)).thenReturn(Optional.empty());
|
||||
when(repository.save(any())).thenReturn(entity);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user