From 8011c532a1b712bd19e7e51c8a95fed60d67f3fb Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Mon, 26 Oct 2026 08:47:08 +0200 Subject: [PATCH] Wires book reader consumption reporting and resume --- .../CompleteConsumptionRequestMapping.cs | 3 +- .../StopConsumptionRequestMapping.cs | 3 +- .../CompleteConsumptionCommand.cs | 7 +- .../CompleteConsumptionCommandHandler.cs | 106 +-- .../CompleteConsumptionCommandValidator.cs | 4 + .../ReportConsumptionProgressCommand.cs | 2 +- .../StopConsumption/StopConsumptionCommand.cs | 6 +- .../StopConsumptionCommandHandler.cs | 172 +++-- .../StopConsumptionCommandValidator.cs | 4 + .../CompleteConsumptionRequest.cs | 7 +- .../ReportConsumptionProgressRequest.cs | 3 +- .../StopConsumptionRequest.cs | 7 +- .../MediaConsumptionRecord.cs | 26 +- .../CompleteConsumptionEndpointSummary.cs | 21 +- ...eportConsumptionProgressEndpointSummary.cs | 2 +- .../StopConsumptionEndpointSummary.cs | 21 +- .../DTO/MediaConsumption/ResumePointDto.cs | 28 + .../CompleteConsumptionRequest.cs | 7 +- .../ReportConsumptionProgressRequest.cs | 3 +- .../StopConsumptionRequest.cs | 7 +- .../Routes/ApiRoutes.MediaConsumption.cs | 3 +- .../Routes/WebRoutes.MediaConsumption.cs | 3 +- .../CompleteConsumptionEndpointSummary.cs | 4 +- .../GetResumePoint/GetResumePointEndpoint.cs | 87 +++ .../GetResumePointEndpointSummary.cs | 40 ++ ...eportConsumptionProgressEndpointSummary.cs | 2 +- .../StopConsumptionEndpointSummary.cs | 4 +- .../BookLibrary/Books/Read.cshtml | 622 +++++++++++++++++- 28 files changed, 1037 insertions(+), 167 deletions(-) create mode 100644 src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ResumePointDto.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpoint.cs create mode 100644 src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpointSummary.cs diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/CompleteConsumptionRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/CompleteConsumptionRequestMapping.cs index 98ef0741..3a5f4bab 100644 --- a/src/Lumina.Application/Common/Mapping/MediaConsumption/CompleteConsumptionRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/CompleteConsumptionRequestMapping.cs @@ -24,7 +24,8 @@ public static class CompleteConsumptionRequestMapping request.Position?.TimeOffsetSeconds, request.Position?.Location, request.ProgressFraction, - request.ConsumedDurationInSeconds + request.ConsumedDurationInSeconds, + request.ConsecutivePagesRead ); } } diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/StopConsumptionRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/StopConsumptionRequestMapping.cs index c9a789e3..d354756a 100644 --- a/src/Lumina.Application/Common/Mapping/MediaConsumption/StopConsumptionRequestMapping.cs +++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/StopConsumptionRequestMapping.cs @@ -24,7 +24,8 @@ public static class StopConsumptionRequestMapping request.Position?.TimeOffsetSeconds, request.Position?.Location, request.ProgressFraction, - request.ConsumedDurationInSeconds + request.ConsumedDurationInSeconds, + request.ConsecutivePagesRead ); } } diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommand.cs index e388e893..dbfcf101 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommand.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommand.cs @@ -14,12 +14,15 @@ namespace Lumina.Application.Core.MediaConsumption.Commands.CompleteConsumption; /// The final opaque locator within the media item, when the position is not a time offset. /// The final fraction of the media item that the client reached, between 0 and 1. /// The active duration consumed by the session, in seconds. -[DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}; ProgressFraction: {ProgressFraction}")] +/// The number of consecutive pages read in the session, used by page based media such as books. +/// It must be absent or zero for other kinds. When it is absent, the count of the last progress report is kept. +[DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}; ProgressFraction: {ProgressFraction}; ConsecutivePagesRead: {ConsecutivePagesRead}")] public record CompleteConsumptionCommand( string? ConsumptionRecordId, string? PositionKind, double? PositionTimeOffsetInSeconds, string? PositionLocation, double? ProgressFraction, - double? ConsumedDurationInSeconds + double? ConsumedDurationInSeconds, + int? ConsecutivePagesRead ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandHandler.cs index 2db8038a..38555a1c 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandHandler.cs @@ -14,6 +14,7 @@ using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaCon using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -27,6 +28,12 @@ namespace Lumina.Application.Core.MediaConsumption.Commands.CompleteConsumption; /// public class CompleteConsumptionCommandHandler : ICommandHandler> { + /// + /// The maximum number of times the terminal state is applied when a concurrent progress report changes the record between its + /// read and its save. + /// + private const int MAXIMUM_TERMINAL_SAVE_ATTEMPTS = 3; + private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; private readonly IDomainEventsQueue _domainEventsQueue; @@ -74,53 +81,74 @@ public class CompleteConsumptionCommandHandler : ICommandHandler getRecordResult = await _unitOfWork.MediaConsumptionRecordRepository - .GetByIdForUserAsync(consumptionRecordId, userId, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getRecordResult.IsFailure) - return getRecordResult.Errors; - if (getRecordResult.Value is null) - return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; - - Result toDomainEntityResult = getRecordResult.Value.ToDomainEntity(); - if (toDomainEntityResult.IsFailure) - return toDomainEntityResult.Errors; - MediaConsumptionRecord record = toDomainEntityResult.Value; - Optional position = ToMediaPosition(command.PositionKind, command.PositionTimeOffsetInSeconds, command.PositionLocation); + Optional consecutivePagesRead = command.ConsecutivePagesRead.HasValue + ? Optional.Some(command.ConsecutivePagesRead.Value) + : Optional.None(); - Result completeResult = record.Complete(position, command.ProgressFraction!.Value, TimeSpan.FromSeconds(command.ConsumedDurationInSeconds!.Value)); - if (completeResult.IsFailure) - return completeResult.Errors; + // A terminal report can race with an in-flight progress report on the same record. The record is read, then saved with the + // version it was read with, so a progress report that commits in between makes the save fail with a concurrency conflict. + // The terminal payload is absolute, so the record is reloaded and the terminal state is applied again to the fresh version. + for (int attempt = 1; attempt <= MAXIMUM_TERMINAL_SAVE_ATTEMPTS; attempt++) + { + // The record is loaded scoped to the current user, so a record of another user is indistinguishable from a missing one. + Result getRecordResult = await _unitOfWork.MediaConsumptionRecordRepository + .GetByIdForUserAsync(consumptionRecordId, userId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getRecordResult.IsFailure) + return getRecordResult.Errors; + if (getRecordResult.Value is null) + return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; - // Completion discards the resume point, because the media item no longer has a point to continue from. A missing resume point is not an - // error, so an explicit completion after a completion that already deleted it stays idempotent. - Result deleteResumePointResult = await _unitOfWork.MediaResumePointRepository - .DeleteForUserAndMediaItemAsync(userId, record.MediaKind, record.MediaItemId.Value, cancellationToken).ConfigureAwait(false); - if (deleteResumePointResult.IsFailure) - return deleteResumePointResult.Errors; + Result toDomainEntityResult = getRecordResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + MediaConsumptionRecord record = toDomainEntityResult.Value; - Result updateResult = await _unitOfWork.MediaConsumptionRecordRepository.UpdateForUserAsync(record.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false); - if (updateResult.IsFailure) - return updateResult.Errors; + Result completeResult = record.Complete(position, command.ProgressFraction!.Value, TimeSpan.FromSeconds(command.ConsumedDurationInSeconds!.Value), consecutivePagesRead); + if (completeResult.IsFailure) + return completeResult.Errors; - Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - return saveChangesResult.Errors; + // Completion discards the resume point, because the media item no longer has a point to continue from. A missing resume point is not an + // error, so an explicit completion after a completion that already deleted it stays idempotent. + Result deleteResumePointResult = await _unitOfWork.MediaResumePointRepository + .DeleteForUserAndMediaItemAsync(userId, record.MediaKind, record.MediaItemId.Value, cancellationToken).ConfigureAwait(false); + if (deleteResumePointResult.IsFailure) + return deleteResumePointResult.Errors; - // Queue any domain events, to be published after the request has completed successfully. - foreach (IDomainEvent domainEvent in record.GetDomainEvents()) - _domainEventsQueue.Enqueue(domainEvent); + Result updateResult = await _unitOfWork.MediaConsumptionRecordRepository.UpdateForUserAsync(record.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; - // The persisted row is read back, so the response carries the timestamps and version the persistence medium actually stored. - Result getPersistedRecordResult = await _unitOfWork.MediaConsumptionRecordRepository - .GetByIdForUserAsync(record.Id.Value, userId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getPersistedRecordResult.IsFailure) - return getPersistedRecordResult.Errors; - if (getPersistedRecordResult.Value is null) - return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + { + // Only a concurrency conflict is worth retrying. The failed attempt is discarded, so the next loop reads the version + // the progress report committed and applies the terminal state to it. + if (attempt < MAXIMUM_TERMINAL_SAVE_ATTEMPTS && saveChangesResult.Errors.Any(error => error == ApplicationErrors.Persistence.ConcurrencyConflict)) + { + _unitOfWork.ClearTrackedEntities(); + continue; + } + return saveChangesResult.Errors; + } - return getPersistedRecordResult.Value.ToDto().ToResponse(); + // Queue any domain events, to be published after the request has completed successfully. + foreach (IDomainEvent domainEvent in record.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + // The persisted row is read back, so the response carries the timestamps and version the persistence medium actually stored. + Result getPersistedRecordResult = await _unitOfWork.MediaConsumptionRecordRepository + .GetByIdForUserAsync(record.Id.Value, userId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPersistedRecordResult.IsFailure) + return getPersistedRecordResult.Errors; + if (getPersistedRecordResult.Value is null) + return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; + + return getPersistedRecordResult.Value.ToDto().ToResponse(); + } + + // Every attempt conflicted with a concurrent write, so the terminal state could not be stored. + return ApplicationErrors.Persistence.ConcurrencyConflict; } /// diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandValidator.cs index 8339dd8b..4d936a09 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandValidator.cs @@ -62,6 +62,10 @@ public class CompleteConsumptionCommandValidator : AbstractValidator consumedDuration is null || consumedDuration.Value <= MAXIMUM_REPORTED_DURATION_IN_SECONDS) .WithError(Errors.MediaConsumption.ConsumedDurationIsOutOfRange); + + RuleFor(command => command.ConsecutivePagesRead) + .Must(consecutivePagesRead => consecutivePagesRead is null || consecutivePagesRead.Value >= 0) + .WithError(Errors.MediaConsumption.ConsecutivePagesReadMustBeNonNegative); } /// diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommand.cs index 8dd5a35e..02647dfc 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommand.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommand.cs @@ -14,7 +14,7 @@ namespace Lumina.Application.Core.MediaConsumption.Commands.ReportConsumptionPro /// The opaque locator within the media item, when the position is not a time offset. /// The fraction of the media item that the client reached, between 0 and 1. /// The active duration consumed by the session, in seconds. -/// The number of consecutive pages read in the current session, used by page based media such as books. +/// The number of consecutive pages read in the current session, used by page based media such as books. It must be zero for other kinds. Defaults to 0. Optional. [DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}; ProgressFraction: {ProgressFraction}")] public record ReportConsumptionProgressCommand( string? ConsumptionRecordId, diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommand.cs index eecb06db..53183900 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommand.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommand.cs @@ -14,12 +14,14 @@ namespace Lumina.Application.Core.MediaConsumption.Commands.StopConsumption; /// The final opaque locator within the media item, when the position is not a time offset. /// The final fraction of the media item that the client reached, between 0 and 1. /// The active duration consumed by the session, in seconds. -[DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}; ProgressFraction: {ProgressFraction}")] +/// The number of consecutive pages read in the session, used by page based media such as books. It must be absent or zero for other kinds. When it is absent, the count of the last progress report is kept. +[DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}; ProgressFraction: {ProgressFraction}; ConsecutivePagesRead: {ConsecutivePagesRead}")] public record StopConsumptionCommand( string? ConsumptionRecordId, string? PositionKind, double? PositionTimeOffsetInSeconds, string? PositionLocation, double? ProgressFraction, - double? ConsumedDurationInSeconds + double? ConsumedDurationInSeconds, + int? ConsecutivePagesRead ) : ICommand; diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandHandler.cs index bcbb472d..44a1b919 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandHandler.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandHandler.cs @@ -18,6 +18,7 @@ using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaRes using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption; using System; using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; using ApplicationErrors = Lumina.Application.Common.Errors.Errors; @@ -31,6 +32,12 @@ namespace Lumina.Application.Core.MediaConsumption.Commands.StopConsumption; /// public class StopConsumptionCommandHandler : ICommandHandler> { + /// + /// The maximum number of times the terminal state is applied when a concurrent progress report changes the record between its + /// read and its save. + /// + private const int MAXIMUM_TERMINAL_SAVE_ATTEMPTS = 3; + private readonly IUnitOfWork _unitOfWork; private readonly ICurrentUserService _currentUserService; private readonly IDomainEventsQueue _domainEventsQueue; @@ -78,85 +85,106 @@ public class StopConsumptionCommandHandler : ICommandHandler getRecordResult = await _unitOfWork.MediaConsumptionRecordRepository.GetByIdForUserAsync(consumptionRecordId, userId, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getRecordResult.IsFailure) - return getRecordResult.Errors; - if (getRecordResult.Value is null) - return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; - - Result toDomainEntityResult = getRecordResult.Value.ToDomainEntity(); - if (toDomainEntityResult.IsFailure) - return toDomainEntityResult.Errors; - MediaConsumptionRecord record = toDomainEntityResult.Value; - - // The settings of the library decide whether reaching a threshold turns the stop into a completion. If the library was deleted after - // the session started, the defaults of the media kind are used instead, so the reported session can still be closed consistently. - Result getLibraryResult = await _unitOfWork.LibraryRepository - .GetByIdAsync(record.LibraryId.Value, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getLibraryResult.IsFailure) - return getLibraryResult.Errors; - LibraryConsumptionSettings consumptionSettings = getLibraryResult.Value is null - ? LibraryConsumptionSettings.CreateDefault(record.MediaKind) - : getLibraryResult.Value.ToDomainValueObject(); - Optional position = ToMediaPosition(command.PositionKind, command.PositionTimeOffsetInSeconds, command.PositionLocation); + Optional consecutivePagesRead = command.ConsecutivePagesRead.HasValue + ? Optional.Some(command.ConsecutivePagesRead.Value) + : Optional.None(); double progressFraction = command.ProgressFraction!.Value; TimeSpan consumedDuration = TimeSpan.FromSeconds(command.ConsumedDurationInSeconds!.Value); - // A session stopped at or after the completion threshold of its library is recorded as completed, not stopped, and loses its resume - // point. Tracking on without a threshold, and tracking off, never complete a session implicitly. The percentage is divided instead of - // multiplying the fraction by one hundred, because the multiplication can round a fraction that is exactly at the threshold below it. - bool isAtCompletionThreshold = consumptionSettings.ShouldTrackConsumptionProgress && - consumptionSettings.CompletionThresholdPercentage.HasValue && - progressFraction >= consumptionSettings.CompletionThresholdPercentage.Value / 100.0; - - Result terminalResult = isAtCompletionThreshold - ? record.Complete(position, progressFraction, consumedDuration) - : record.Stop(position, progressFraction, consumedDuration); - if (terminalResult.IsFailure) - return terminalResult.Errors; - - Optional ruleResult = MediaConsumptionRule.For(record.MediaKind); - if (!ruleResult.HasValue) - return DomainErrors.MediaConsumption.UnsupportedMediaKind; - - if (isAtCompletionThreshold) + // A terminal report can race with an in-flight progress report on the same record. The record is read, then saved with the + // version it was read with, so a progress report that commits in between makes the save fail with a concurrency conflict. + // The terminal payload is absolute, so the record is reloaded and the terminal state is applied again to the fresh version. + for (int attempt = 1; attempt <= MAXIMUM_TERMINAL_SAVE_ATTEMPTS; attempt++) { - // Completion discards the resume point, because the media item no longer has a point to continue from. - Result deleteResumePointResult = await _unitOfWork.MediaResumePointRepository.DeleteForUserAndMediaItemAsync(userId, record.MediaKind, record.MediaItemId.Value, cancellationToken).ConfigureAwait(false); - if (deleteResumePointResult.IsFailure) - return deleteResumePointResult.Errors; - } - else if (consumptionSettings.ShouldTrackConsumptionProgress && ruleResult.Value.CanResume && record.LastPosition.HasValue) - { - // A stopped session that did not reach the completion threshold keeps a resume point. Without a known position there is nothing to resume from, so no resume point is written. - Result upsertResumePointResult = await UpsertResumePointAsync(record, record.LastPosition.Value, record.LastProgressFraction, userId, cancellationToken).ConfigureAwait(false); - if (upsertResumePointResult.IsFailure) - return upsertResumePointResult.Errors; + // The record is loaded scoped to the current user, so a record of another user is indistinguishable from a missing one. + Result getRecordResult = await _unitOfWork.MediaConsumptionRecordRepository.GetByIdForUserAsync(consumptionRecordId, userId, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getRecordResult.IsFailure) + return getRecordResult.Errors; + if (getRecordResult.Value is null) + return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; + + Result toDomainEntityResult = getRecordResult.Value.ToDomainEntity(); + if (toDomainEntityResult.IsFailure) + return toDomainEntityResult.Errors; + MediaConsumptionRecord record = toDomainEntityResult.Value; + + // The settings of the library decide whether reaching a threshold turns the stop into a completion. If the library was deleted after + // the session started, the defaults of the media kind are used instead, so the reported session can still be closed consistently. + Result getLibraryResult = await _unitOfWork.LibraryRepository + .GetByIdAsync(record.LibraryId.Value, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getLibraryResult.IsFailure) + return getLibraryResult.Errors; + LibraryConsumptionSettings consumptionSettings = getLibraryResult.Value is null + ? LibraryConsumptionSettings.CreateDefault(record.MediaKind) + : getLibraryResult.Value.ToDomainValueObject(); + + // A session stopped at or after the completion threshold of its library is recorded as completed, not stopped, and loses its resume + // point. Tracking on without a threshold, and tracking off, never complete a session implicitly. The percentage is divided instead of + // multiplying the fraction by one hundred, because the multiplication can round a fraction that is exactly at the threshold below it. + bool isAtCompletionThreshold = consumptionSettings.ShouldTrackConsumptionProgress && + consumptionSettings.CompletionThresholdPercentage.HasValue && + progressFraction >= consumptionSettings.CompletionThresholdPercentage.Value / 100.0; + + Result terminalResult = isAtCompletionThreshold + ? record.Complete(position, progressFraction, consumedDuration, consecutivePagesRead) + : record.Stop(position, progressFraction, consumedDuration, consecutivePagesRead); + if (terminalResult.IsFailure) + return terminalResult.Errors; + + Optional ruleResult = MediaConsumptionRule.For(record.MediaKind); + if (!ruleResult.HasValue) + return DomainErrors.MediaConsumption.UnsupportedMediaKind; + + if (isAtCompletionThreshold) + { + // Completion discards the resume point, because the media item no longer has a point to continue from. + Result deleteResumePointResult = await _unitOfWork.MediaResumePointRepository.DeleteForUserAndMediaItemAsync(userId, record.MediaKind, record.MediaItemId.Value, cancellationToken).ConfigureAwait(false); + if (deleteResumePointResult.IsFailure) + return deleteResumePointResult.Errors; + } + else if (consumptionSettings.ShouldTrackConsumptionProgress && ruleResult.Value.CanResume && record.LastPosition.HasValue) + { + // A stopped session that did not reach the completion threshold keeps a resume point. Without a known position there is nothing to resume from, so no resume point is written. + Result upsertResumePointResult = await UpsertResumePointAsync(record, record.LastPosition.Value, record.LastProgressFraction, userId, cancellationToken).ConfigureAwait(false); + if (upsertResumePointResult.IsFailure) + return upsertResumePointResult.Errors; + } + + Result updateResult = await _unitOfWork.MediaConsumptionRecordRepository.UpdateForUserAsync(record.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false); + if (updateResult.IsFailure) + return updateResult.Errors; + + Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); + if (saveChangesResult.IsFailure) + { + // Only a concurrency conflict is worth retrying. The failed attempt is discarded, so the next loop reads the version + // the progress report committed and applies the terminal state to it. + if (attempt < MAXIMUM_TERMINAL_SAVE_ATTEMPTS && saveChangesResult.Errors.Any(error => error == ApplicationErrors.Persistence.ConcurrencyConflict)) + { + _unitOfWork.ClearTrackedEntities(); + continue; + } + return saveChangesResult.Errors; + } + + // Queue any domain events, to be published after the request has completed successfully. + foreach (IDomainEvent domainEvent in record.GetDomainEvents()) + _domainEventsQueue.Enqueue(domainEvent); + + // The persisted row is read back, so the response carries the timestamps and version the persistence medium actually stored. + Result getPersistedRecordResult = await _unitOfWork.MediaConsumptionRecordRepository + .GetByIdForUserAsync(record.Id.Value, userId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (getPersistedRecordResult.IsFailure) + return getPersistedRecordResult.Errors; + if (getPersistedRecordResult.Value is null) + return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; + + return getPersistedRecordResult.Value.ToDto().ToResponse(); } - Result updateResult = await _unitOfWork.MediaConsumptionRecordRepository.UpdateForUserAsync(record.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false); - if (updateResult.IsFailure) - return updateResult.Errors; - - Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false); - if (saveChangesResult.IsFailure) - return saveChangesResult.Errors; - - // Queue any domain events, to be published after the request has completed successfully. - foreach (IDomainEvent domainEvent in record.GetDomainEvents()) - _domainEventsQueue.Enqueue(domainEvent); - - // The persisted row is read back, so the response carries the timestamps and version the persistence medium actually stored. - Result getPersistedRecordResult = await _unitOfWork.MediaConsumptionRecordRepository - .GetByIdForUserAsync(record.Id.Value, userId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false); - if (getPersistedRecordResult.IsFailure) - return getPersistedRecordResult.Errors; - if (getPersistedRecordResult.Value is null) - return DomainErrors.MediaConsumption.ConsumptionRecordNotFound; - - return getPersistedRecordResult.Value.ToDto().ToResponse(); + // Every attempt conflicted with a concurrent write, so the terminal state could not be stored. + return ApplicationErrors.Persistence.ConcurrencyConflict; } /// diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandValidator.cs index 4420ae65..69de6154 100644 --- a/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandValidator.cs +++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandValidator.cs @@ -62,6 +62,10 @@ public class StopConsumptionCommandValidator : AbstractValidator consumedDuration is null || consumedDuration.Value <= MAXIMUM_REPORTED_DURATION_IN_SECONDS) .WithError(Errors.MediaConsumption.ConsumedDurationIsOutOfRange); + + RuleFor(command => command.ConsecutivePagesRead) + .Must(consecutivePagesRead => consecutivePagesRead is null || consecutivePagesRead.Value >= 0) + .WithError(Errors.MediaConsumption.ConsecutivePagesReadMustBeNonNegative); } /// diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/CompleteConsumptionRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/CompleteConsumptionRequest.cs index f1d79885..e3810e1a 100644 --- a/src/Lumina.Contracts/Requests/MediaConsumption/CompleteConsumptionRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaConsumption/CompleteConsumptionRequest.cs @@ -10,9 +10,12 @@ namespace Lumina.Contracts.Requests.MediaConsumption; /// The final position reported for the media item, if the client knows it. Optional. /// The fraction of the media item that the client reached, between 0 and 1. Required. /// The active duration consumed by the session, in seconds. Required. -[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}")] +/// The number of consecutive pages read in the session, used by page based media such as books. +/// It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional. +[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}; ConsecutivePagesRead: {ConsecutivePagesRead}")] public sealed record CompleteConsumptionRequest( MediaPositionRequest? Position, double? ProgressFraction, - double? ConsumedDurationInSeconds + double? ConsumedDurationInSeconds, + int? ConsecutivePagesRead = null ); diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs index 7d0760c2..41604055 100644 --- a/src/Lumina.Contracts/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs @@ -10,7 +10,8 @@ namespace Lumina.Contracts.Requests.MediaConsumption; /// The last position reported for the media item, if the client knows it. Optional. /// The fraction of the media item that the client reached, between 0 and 1. Required. /// The active duration consumed by the session, in seconds. Required. -/// The number of consecutive pages read in the current session, used by page based media such as books and ignored for other kinds. Defaults to 0. Optional. +/// The number of consecutive pages read in the current session, used by page based media such as books. +/// It must be zero for other kinds; a positive value is rejected with a forbidden error. Defaults to 0. Optional. [DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}; ConsecutivePagesRead: {ConsecutivePagesRead}")] public sealed record ReportConsumptionProgressRequest( MediaPositionRequest? Position, diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/StopConsumptionRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/StopConsumptionRequest.cs index f566e815..c189d147 100644 --- a/src/Lumina.Contracts/Requests/MediaConsumption/StopConsumptionRequest.cs +++ b/src/Lumina.Contracts/Requests/MediaConsumption/StopConsumptionRequest.cs @@ -10,9 +10,12 @@ namespace Lumina.Contracts.Requests.MediaConsumption; /// The final position reported for the media item, if the client knows it. Optional. /// The fraction of the media item that the client reached, between 0 and 1. Required. /// The active duration consumed by the session, in seconds. Required. -[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}")] +/// The number of consecutive pages read in the session, used by page based media such as books. +/// It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional. +[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}; ConsecutivePagesRead: {ConsecutivePagesRead}")] public sealed record StopConsumptionRequest( MediaPositionRequest? Position, double? ProgressFraction, - double? ConsumedDurationInSeconds + double? ConsumedDurationInSeconds, + int? ConsecutivePagesRead = null ); diff --git a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/MediaConsumptionRecord.cs b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/MediaConsumptionRecord.cs index d61676a3..2dd64891 100644 --- a/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/MediaConsumptionRecord.cs +++ b/src/Lumina.Domain/Core/BoundedContexts/MediaConsumptionBoundedContext/MediaConsumptionRecordAggregate/MediaConsumptionRecord.cs @@ -275,12 +275,8 @@ public sealed class MediaConsumptionRecord : AggregateRoot ruleResult = MediaConsumptionRule.For(mediaKind); if (!ruleResult.HasValue) return Errors.MediaConsumption.UnsupportedMediaKind; - if (consumedDuration < TimeSpan.Zero) - return Errors.MediaConsumption.ConsumedDurationMustBeNonNegative; if (!IsProgressFractionValid(lastProgressFraction)) return Errors.MediaConsumption.InvalidProgressFraction; - if (consecutivePagesRead < 0) - return Errors.MediaConsumption.ConsecutivePagesReadMustBeNonNegative; if (consecutivePagesRead > 0 && !IsPageBased(ruleResult.Value)) return Errors.MediaConsumption.ConsecutivePagesReadIsOnlySupportedForPageBasedMedia; if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) @@ -328,12 +324,8 @@ public sealed class MediaConsumptionRecord : AggregateRoot 0 && !IsPageBased(ruleResult.Value)) return Errors.MediaConsumption.ConsecutivePagesReadIsOnlySupportedForPageBasedMedia; if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) @@ -369,8 +361,9 @@ public sealed class MediaConsumptionRecord : AggregateRootThe final position reported by the client, if the call carries one. When it is absent, the last known position is kept. /// The final progress fraction reported by the client. /// The active duration consumed by the session. + /// The number of consecutive pages read in the session, when the client reported it. When it is absent, the count of the last progress report is kept. /// An representing either a successful completion, or an error. - public Result Complete(Optional lastPosition, double lastProgressFraction, TimeSpan consumedDuration) + public Result Complete(Optional lastPosition, double lastProgressFraction, TimeSpan consumedDuration, Optional consecutivePagesRead) { if (Status != ConsumptionStatus.InProgress) return Errors.MediaConsumption.ConsumptionIsAlreadyTerminal; @@ -380,10 +373,10 @@ public sealed class MediaConsumptionRecord : AggregateRoot 0 && !IsPageBased(ruleResult.Value)) + return Errors.MediaConsumption.ConsecutivePagesReadIsOnlySupportedForPageBasedMedia; if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) return Errors.MediaConsumption.InvalidMediaPosition; @@ -391,6 +384,8 @@ public sealed class MediaConsumptionRecord : AggregateRootThe final position reported by the client, if the call carries one. When it is absent, the last known position is kept. /// The final progress fraction reported by the client. /// The active duration consumed by the session. + /// The number of consecutive pages read in the session, when the client reported it. When it is absent, the count of the last progress report is kept. /// An representing either a successful stop, or an error. - public Result Stop(Optional lastPosition, double lastProgressFraction, TimeSpan consumedDuration) + public Result Stop(Optional lastPosition, double lastProgressFraction, TimeSpan consumedDuration, Optional consecutivePagesRead) { if (Status != ConsumptionStatus.InProgress) return Errors.MediaConsumption.ConsumptionIsAlreadyTerminal; @@ -429,10 +425,10 @@ public sealed class MediaConsumptionRecord : AggregateRoot 0 && !IsPageBased(ruleResult.Value)) + return Errors.MediaConsumption.ConsecutivePagesReadIsOnlySupportedForPageBasedMedia; if (!DoesPositionMatchRule(ruleResult.Value, lastPosition)) return Errors.MediaConsumption.InvalidMediaPosition; @@ -440,6 +436,8 @@ public sealed class MediaConsumptionRecord : AggregateRoot request.Position, "The final position reported for the media item, if the client knows it. It carries the position Kind, and either TimeOffsetSeconds or Location. Optional."); RequestParam(request => request.ProgressFraction, "The final fraction of the media item that the client reached, between 0 and 1. Required."); RequestParam(request => request.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds. Required."); + RequestParam(request => request.ConsecutivePagesRead, "The number of consecutive pages read in the session, used by page based media such as books. It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional."); ResponseParam(record => record.Id, "The Id of the consumption record."); ResponseParam(record => record.LibraryId, "The Id of the media library that contains the consumed media item."); @@ -93,7 +96,7 @@ public class CompleteConsumptionEndpointSummary : Summary request.Position, "The last position reported for the media item, if the client knows it. It carries the position Kind, and either TimeOffsetSeconds or Location. Optional."); RequestParam(request => request.ProgressFraction, "The fraction of the media item that the client reached, between 0 and 1. Required."); RequestParam(request => request.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds. Required."); - RequestParam(request => request.ConsecutivePagesRead, "The number of consecutive pages read in the current session, used by page based media such as books. Optional, defaults to 0."); + RequestParam(request => request.ConsecutivePagesRead, "The number of consecutive pages read in the current session, used by page based media such as books. It must be zero for other kinds; a positive value is rejected with a forbidden error. Optional, defaults to 0."); ResponseParam(record => record.Id, "The Id of the consumption record."); ResponseParam(record => record.LibraryId, "The Id of the media library that contains the consumed media item."); diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpointSummary.cs index 8725ad01..7d3078cf 100644 --- a/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpointSummary.cs +++ b/src/Lumina.Presentation.Api/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpointSummary.cs @@ -28,18 +28,21 @@ public class StopConsumptionEndpointSummary : Summary request.Position, "The final position reported for the media item, if the client knows it. It carries the position Kind, and either TimeOffsetSeconds or Location. Optional."); RequestParam(request => request.ProgressFraction, "The final fraction of the media item that the client reached, between 0 and 1. Required."); RequestParam(request => request.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds. Required."); + RequestParam(request => request.ConsecutivePagesRead, "The number of consecutive pages read in the session, used by page based media such as books. It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional."); ResponseParam(record => record.Id, "The Id of the consumption record."); ResponseParam(record => record.LibraryId, "The Id of the media library that contains the consumed media item."); @@ -93,7 +96,7 @@ public class StopConsumptionEndpointSummary : Summary +/// Data transfer object for the point at which a user can resume consuming a media item. +/// +/// The Id of the resume point. +/// The Id of the media library that contains the media item. +/// The Id of the media item to resume. +/// The kind of media that is resumed. +/// The position at which the media item can be resumed. +/// The progress fraction at which the media item can be resumed. +/// The date and time when the media item was last consumed. +[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")] +public sealed record ResumePointDto( + Guid Id, + Guid LibraryId, + Guid MediaItemId, + MediaKind MediaKind, + MediaPositionDto LastPosition, + double LastProgressFraction, + DateTime LastConsumedOnUtc +); diff --git a/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/CompleteConsumptionRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/CompleteConsumptionRequest.cs index e8c1ffed..0cb170cd 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/CompleteConsumptionRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/CompleteConsumptionRequest.cs @@ -10,9 +10,12 @@ namespace Lumina.Presentation.Web.Common.Requests.MediaConsumption; /// The final position reported for the media item, if the client knows it. Optional. /// The fraction of the media item that the client reached, between 0 and 1. Required. /// The active duration consumed by the session, in seconds. Required. -[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}")] +/// The number of consecutive pages read in the session, used by page based media such as books. +/// It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional. +[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}; ConsecutivePagesRead: {ConsecutivePagesRead}")] public sealed record CompleteConsumptionRequest( MediaPositionRequest? Position, double? ProgressFraction, - double? ConsumedDurationInSeconds + double? ConsumedDurationInSeconds, + int? ConsecutivePagesRead = null ); diff --git a/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs index 599025ec..b77ab1a6 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs @@ -10,7 +10,8 @@ namespace Lumina.Presentation.Web.Common.Requests.MediaConsumption; /// The last position reported for the media item, if the client knows it. Optional. /// The fraction of the media item that the client reached, between 0 and 1. Required. /// The active duration consumed by the session, in seconds. Required. -/// The number of consecutive pages read in the current session, used by page based media such as books and ignored for other kinds. Defaults to 0. Optional. +/// The number of consecutive pages read in the current session, used by page based media such as books. +/// It must be zero for other kinds; a positive value is rejected with a forbidden error. Defaults to 0. Optional. [DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}; ConsecutivePagesRead: {ConsecutivePagesRead}")] public sealed record ReportConsumptionProgressRequest( MediaPositionRequest? Position, diff --git a/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/StopConsumptionRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/StopConsumptionRequest.cs index b7034f23..12ffcc78 100644 --- a/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/StopConsumptionRequest.cs +++ b/src/Lumina.Presentation.Web/Common/Requests/MediaConsumption/StopConsumptionRequest.cs @@ -10,9 +10,12 @@ namespace Lumina.Presentation.Web.Common.Requests.MediaConsumption; /// The final position reported for the media item, if the client knows it. Optional. /// The fraction of the media item that the client reached, between 0 and 1. Required. /// The active duration consumed by the session, in seconds. Required. -[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}")] +/// The number of consecutive pages read in the session, used by page based media such as books. +/// It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional. +[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}; ConsecutivePagesRead: {ConsecutivePagesRead}")] public sealed record StopConsumptionRequest( MediaPositionRequest? Position, double? ProgressFraction, - double? ConsumedDurationInSeconds + double? ConsumedDurationInSeconds, + int? ConsecutivePagesRead = null ); diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.MediaConsumption.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.MediaConsumption.cs index a912ab06..e0282348 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.MediaConsumption.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.MediaConsumption.cs @@ -6,7 +6,7 @@ namespace Lumina.Presentation.Web.Common.Routes; public static partial class ApiRoutes { /// - /// Routes for the media consumption lifecycle endpoints of the remote API. + /// Routes for the media consumption lifecycle and resume point endpoints of the remote API. /// public static class MediaConsumption { @@ -14,5 +14,6 @@ public static partial class ApiRoutes public const string REPORT_CONSUMPTION_PROGRESS = "users/me/consumption-records/{recordId}/progress"; public const string COMPLETE_CONSUMPTION = "users/me/consumption-records/{recordId}/complete"; public const string STOP_CONSUMPTION = "users/me/consumption-records/{recordId}/stop"; + public const string GET_RESUME_POINT = "users/me/media-resume-points/{mediaKind}/{mediaItemId}"; } } diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.MediaConsumption.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.MediaConsumption.cs index afdd9cd1..d35e3935 100644 --- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.MediaConsumption.cs +++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.MediaConsumption.cs @@ -6,7 +6,7 @@ namespace Lumina.Presentation.Web.Common.Routes; public static partial class WebRoutes { /// - /// Routes for the media consumption lifecycle actions the browser clients report to, proxied to the remote API. + /// Routes for the media consumption lifecycle actions and resume points the browser clients report to, proxied to the remote API. /// public static class MediaConsumption { @@ -14,5 +14,6 @@ public static partial class WebRoutes public const string REPORT_CONSUMPTION_PROGRESS = "{culture}/media-consumption/api-report-consumption-progress/{recordId}"; public const string COMPLETE_CONSUMPTION = "{culture}/media-consumption/api-complete-consumption/{recordId}"; public const string STOP_CONSUMPTION = "{culture}/media-consumption/api-stop-consumption/{recordId}"; + public const string GET_RESUME_POINT = "{culture}/media-consumption/api-get-resume-point/{mediaKind}/{mediaItemId}"; } } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpointSummary.cs index f72d6bac..1274e4fa 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/CompleteConsumption/CompleteConsumptionEndpointSummary.cs @@ -29,11 +29,13 @@ public class CompleteConsumptionEndpointSummary : Summary request.Position, "The final position reported for the media item, if the client knows it. It carries the position Kind, and either TimeOffsetSeconds or Location. Optional."); RequestParam(request => request.ProgressFraction, "The fraction of the media item that the client reached, between 0 and 1. Required."); RequestParam(request => request.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds. Required."); + RequestParam(request => request.ConsecutivePagesRead, "The number of consecutive pages read in the session, used by page based media such as books. It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional."); Response(200, "The consumption session is completed and the updated record is returned.", example: new SuccessResponse(true, new ConsumptionRecordDto( diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpoint.cs new file mode 100644 index 00000000..b827eb65 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpoint.cs @@ -0,0 +1,87 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using Lumina.Presentation.Web.Common.Exceptions; +using Lumina.Presentation.Web.Common.Routes; +using Lumina.Presentation.Web.Core.Endpoints.Common; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using System; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.MediaConsumption.GetResumePoint; + +/// +/// API endpoint for the /{culture}/media-consumption/api-get-resume-point/{mediaKind}/{mediaItemId} route. +/// +public class GetResumePointEndpoint : BaseEndpoint +{ + // A value that is not a name of MediaKind, so the API rejects a crafted route value with its own validation error. + private const string INVALID_MEDIA_KIND_PLACEHOLDER = "Invalid"; + + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetResumePointEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.MediaConsumption.GET_RESUME_POINT); + DontAutoTag(); + Options(options => options.WithTags("MediaConsumption")); + } + + /// + /// Retrieves the resume point of the current user for a media item. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The resume point belongs to the current user, so no intermediary may store the response, and it varies by the sign in cookie. + HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; + HttpContext.Response.Headers.Append("Vary", "Cookie"); + // The identifiers are taken from the route, so they cannot be replaced by values posted in the body. + // The media kind must be the name of a MediaKind member, which also rejects numeric strings, comma separated lists, and + // dot segments that escaping alone would leave in the relative path of the upstream request. + string routeMediaKind = HttpContext.Request.RouteValues["mediaKind"]?.ToString() ?? string.Empty; + string mediaKind = INVALID_MEDIA_KIND_PLACEHOLDER; + foreach (string mediaKindName in Enum.GetNames()) + if (string.Equals(mediaKindName, routeMediaKind, StringComparison.OrdinalIgnoreCase)) + mediaKind = mediaKindName; + string routeMediaItemId = HttpContext.Request.RouteValues["mediaItemId"]?.ToString() ?? string.Empty; + string mediaItemId = Guid.TryParse(routeMediaItemId, out Guid parsedMediaItemId) ? parsedMediaItemId.ToString() : Guid.Empty.ToString(); + string endpoint = ApiRoutes.MediaConsumption.GET_RESUME_POINT + .Replace("{mediaKind}", mediaKind, StringComparison.Ordinal) + .Replace("{mediaItemId}", mediaItemId, StringComparison.Ordinal); + try + { + ResumePointDto resumePoint = await _apiHttpClient.GetAsync(endpoint, cancellationToken).ConfigureAwait(false); + return JsonSuccess(resumePoint); + } + catch (ApiException apiException) when (apiException.HttpStatusCode == HttpStatusCode.NotFound && + apiException.ProblemDetails?.Detail is "MediaResumePointNotFound" or "BookNotFound" or "TrackNotFound") + { + // Only an absent resume point, and the missing or moved media item that turns an existing resume point into an orphan, + // mean that there is nothing to resume. Any other 404, such as a route or API version mismatch, is rethrown so it is + // logged and reported instead of being disguised as an empty resume point. + return JsonSuccess(null); + } + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpointSummary.cs new file mode 100644 index 00000000..e9e8d1cb --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/GetResumePoint/GetResumePointEndpointSummary.cs @@ -0,0 +1,40 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; +using Lumina.Presentation.Web.Common.Enums.MediaConsumption; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.MediaConsumption.GetResumePoint; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetResumePointEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetResumePointEndpointSummary() + { + Summary = "Retrieves the resume point of the current user for a media item."; + Description = "Proxies the retrieval of the point at which the current user can resume a media item to the API server. The book reader calls it with the Book kind and the Id of the book it opens. A book resume point carries an opaque Location, while a music track resume point carries a TimeOffset. When the user has no resume point for the media item, or the media item no longer exists, the response succeeds without data instead of failing, so a reader can fall back to the beginning of the item. Any other upstream failure is rethrown to the application error handling, so a route or version mismatch is not mistaken for an absent resume point."; + + Params["mediaKind"] = "The kind of media to resume. Only the member names of MediaKind are accepted, such as Book or MusicTrack. Numeric values are rejected."; + Params["mediaItemId"] = "The Id of the media item to resume."; + + Response(200, "The resume point of the current user is returned, or no data when the user has none.", "application/json", + example: new SuccessResponse(true, new ResumePointDto( + Id: Guid.Parse("4d5e6f70-8192-4a3b-9c4d-5e6f708192a3"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"), + MediaKind: MediaKind.Book, + LastPosition: new MediaPositionDto(MediaPositionKind.Location, null, "epubcfi(/6/4[chapter-3]!/4/2/2)"), + LastProgressFraction: 0.42, + LastConsumedOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc))) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpointSummary.cs index ac8325fe..9cfaa97e 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/ReportConsumptionProgress/ReportConsumptionProgressEndpointSummary.cs @@ -41,7 +41,7 @@ public class ReportConsumptionProgressEndpointSummary : Summary request.Position, "The last position reported for the media item, if the client knows it. It carries the position Kind, and either TimeOffsetSeconds or Location. Optional."); RequestParam(request => request.ProgressFraction, "The fraction of the media item that the client reached, between 0 and 1. Required."); RequestParam(request => request.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds. Required."); - RequestParam(request => request.ConsecutivePagesRead, "The number of consecutive pages read in the current session, used by page based media such as books. Optional, defaults to 0."); + RequestParam(request => request.ConsecutivePagesRead, "The number of consecutive pages read in the current session, used by page based media such as books. It must be zero for other kinds; a positive value is rejected with a forbidden error. Optional, defaults to 0."); Response(200, "The progress of the consumption session is reported and the updated record is returned.", example: new SuccessResponse(true, new ConsumptionRecordDto( diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpointSummary.cs index 5913ffda..71e4b987 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/MediaConsumption/StopConsumption/StopConsumptionEndpointSummary.cs @@ -29,11 +29,13 @@ public class StopConsumptionEndpointSummary : Summary request.Position, "The final position reported for the media item, if the client knows it. It carries the position Kind, and either TimeOffsetSeconds or Location. Optional."); RequestParam(request => request.ProgressFraction, "The fraction of the media item that the client reached, between 0 and 1. Required."); RequestParam(request => request.ConsumedDurationInSeconds, "The active duration consumed by the session, in seconds. Required."); + RequestParam(request => request.ConsecutivePagesRead, "The number of consecutive pages read in the session, used by page based media such as books. It must be omitted or zero for other kinds; a positive value is rejected with a forbidden error. When omitted, the count stored by the last progress report is kept. Optional."); Response(200, "The consumption session is stopped and the updated record is returned.", example: new SuccessResponse(true, new ConsumptionRecordDto( diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml index 93fe436f..d65a3cad 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/WrittenContentLibrary/BookLibrary/Books/Read.cshtml @@ -48,6 +48,33 @@ const libraryIndexUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.INDEX)'; const sectionUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_SECTION, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + `?libraryId=${libraryId}&locationRef=`; const resourceUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.GET_READING_RESOURCE, new { bookId = default(Guid) })'.replace('/@(default(Guid))', `/${bookId}`) + `?libraryId=${libraryId}&resourceKey=`; + const startConsumptionUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.MediaConsumption.START_CONSUMPTION, new { libraryId = Model.LibraryId, mediaKind = "Book", mediaItemId = Model.BookId })'; + const resumePointUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.MediaConsumption.GET_RESUME_POINT, new { mediaKind = "Book", mediaItemId = Model.BookId })'; + const reportConsumptionProgressUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.MediaConsumption.REPORT_CONSUMPTION_PROGRESS, new { recordId = default(Guid) })'; + const completeConsumptionUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.MediaConsumption.COMPLETE_CONSUMPTION, new { recordId = default(Guid) })'; + const stopConsumptionUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.MediaConsumption.STOP_CONSUMPTION, new { recordId = default(Guid) })'; + const EMPTY_GUID = '00000000-0000-0000-0000-000000000000'; + // The position kind of an opaque book location, as the consumption API names it. + const LOCATION_POSITION_KIND = 'Location'; + // The interval, in milliseconds, at which the heartbeat advances the active reading clock. The clock is paused while + // the tab is hidden, so time spent on another tab is not counted as reading time. + const READING_HEARTBEAT_INTERVAL_MS = 1000; + // The longest wall clock interval, in milliseconds, that one heartbeat may add to the active reading time. A much larger + // interval comes from a device sleep, a closed lid, or a frozen tab, so it is not active reading time. The margin covers + // a late heartbeat while still bounding how much idle time can be counted. + const READING_MAX_ACCUMULATED_INTERVAL_MS = READING_HEARTBEAT_INTERVAL_MS + 5000; + // The time, in milliseconds, after which a background consumption request is abandoned. Reporting is best effort, so a slow + // or hung request must never stop the next report of the reading session from being sent. + const CONSUMPTION_REQUEST_TIMEOUT_MS = 5000; + // The time, in milliseconds, after which the optional resume point lookup is abandoned. The lookup is awaited before the + // first section, because its result chooses that section, so this bounds the wait. The manifest fetch itself is bounded only + // by the browser and the server, not by the reader. + const RESUME_POINT_REQUEST_TIMEOUT_MS = 5000; + // Marks a section request that was redirected to the sign in page, so its caller navigates instead of reporting a failure. + const REDIRECTED = Symbol('redirected'); + // Marks a start request that did not settle within the bounded recovery wait, so the reader shows its failure state instead + // of opening a provisional first section that could overwrite the saved place. + const START_TIMED_OUT = Symbol('startTimedOut'); // Escapes a string for safe interpolation into HTML markup; the table of contents labels and location references come from // the book file itself, so they are escaped before they are placed into innerHTML, keeping a malicious book from injecting markup. @@ -80,11 +107,475 @@ let manifest = null; let currentIndex = -1; + // The section the reader was last asked to open. It advances when navigation starts, so a second Next or Previous click + // during a section load targets the next section instead of requesting the section that is already loading again. + let requestedIndex = -1; + // Identifies the newest section request, so a slow response that was superseded by a later navigation is ignored. + let sectionLoadSequence = 0; + // Aborts the section request that was superseded, so its failure never reaches the error notification after the reader left it. + let sectionLoadAbortController = null; let fontSize = 18; + // The consumption record of the current reader session. The object identity keeps a session that was replaced, such as a + // page restored from the back forward cache while its start request is still in flight, from writing into the session that + // replaced it. + let consumptionSession = null; + // A session whose start request was still in flight when the page was hidden. A restored page revives it instead of + // starting a second record for the same reading session. + let pendingConsumptionSession = null; + let isConsumptionSessionFinished = false; + let isConsumptionSessionCompleted = false; + // The number of pages read consecutively in the current forward run, including the page the run starts on. The reader + // paginates by spine section: a PDF page is a section of its own, and a reflowable book advances one section at a time. + let consecutivePagesRead = 0; + // The active reading clock. Only the time during which the reader is visible is accumulated. + let activeReadingMilliseconds = 0; + let readingClockStartedOnMs = null; + let readingHeartbeatTimer = null; - // Loads the reading manifest of the book, and opens the first reading section. + // Builds the URL of a consumption record route from its template and the Id of the record. + function buildConsumptionRecordUrl(routeTemplate, recordId) { + return routeTemplate.replace(EMPTY_GUID, encodeURIComponent(recordId)); + } + + // Rounds the accumulated reading duration, so it is sent as a stable, readable number of seconds. + function roundConsumptionDuration(value) { + const number = Number(value); + return Number.isFinite(number) ? Math.round(number * 1000) / 1000 : 0; + } + + // Gets the position of the section the reader currently shows, as the opaque location the consumption API stores for books. + function buildReadingPosition() { + if (!manifest || !manifest.spine || currentIndex < 0 || currentIndex >= manifest.spine.length) + return null; + return { + kind: LOCATION_POSITION_KIND, + timeOffsetSeconds: null, + location: manifest.spine[currentIndex].locationRef + }; + } + + // Gets the fraction of the book read so far. The current section counts as read, so the last section is the whole book. + function getReadingProgressFraction() { + if (!manifest || !manifest.spine || manifest.spine.length === 0 || currentIndex < 0) + return 0; + return Math.min(1, (currentIndex + 1) / manifest.spine.length); + } + + // Starts the active reading clock, unless it is already running. + function startReadingClock() { + if (readingClockStartedOnMs === null) + readingClockStartedOnMs = Date.now(); + } + + // Adds the reading time elapsed since the clock was last advanced, and restarts the measured interval. + function accumulateActiveReadingTime() { + if (readingClockStartedOnMs === null) + return; + const now = Date.now(); + const elapsedMilliseconds = Math.max(0, now - readingClockStartedOnMs); + activeReadingMilliseconds += Math.min(elapsedMilliseconds, READING_MAX_ACCUMULATED_INTERVAL_MS); + readingClockStartedOnMs = now; + } + + // Stops the active reading clock, keeping the time accumulated so far. + function pauseReadingClock() { + accumulateActiveReadingTime(); + readingClockStartedOnMs = null; + } + + // Gets the active reading duration, in seconds, accumulated while the reader was visible. + function getActiveReadingSeconds() { + accumulateActiveReadingTime(); + return roundConsumptionDuration(Math.max(0, activeReadingMilliseconds / 1000)); + } + + // Pauses the active reading clock when the tab goes to the background, and resumes it when the reader is shown again, + // so reading in another tab or waiting while the tab is hidden never counts as active reading time. + function handleVisibilityChange() { + // The heartbeat only exists while a reading session is active, so before the first section starts it there is no clock to pause. + if (readingHeartbeatTimer === null) + return; + if (document.visibilityState === 'hidden') + pauseReadingClock(); + else + startReadingClock(); + } + + // Starts the heartbeat that advances the active reading clock while the reader is open. + function startReadingHeartbeat() { + if (document.visibilityState !== 'hidden') + startReadingClock(); + if (readingHeartbeatTimer === null) + readingHeartbeatTimer = window.setInterval(accumulateActiveReadingTime, READING_HEARTBEAT_INTERVAL_MS); + } + + // Stops the heartbeat and the active reading clock when the reader session ends. + function stopReadingHeartbeat() { + if (readingHeartbeatTimer !== null) { + window.clearInterval(readingHeartbeatTimer); + readingHeartbeatTimer = null; + } + pauseReadingClock(); + } + + // Sends a consumption request in the background, with the anti-forgery token the page rendered. Reporting is a background + // concern, so a failed request is only logged and never interrupts or fails the reading itself. + async function sendConsumptionRequestAsync(url, payload, options = {}) { + if (!url) + return null; + // A terminal report is sent with keepalive so the browser finishes it after the page is gone, and it is not aborted, + // because the page may already be unloading while it is still in flight. The start request is also not aborted, because + // a slow start can still succeed and its response carries the only record identifier the client can report against. + const shouldAbortOnTimeout = options.keepalive !== true && options.shouldAbortOnTimeout !== false; + const abortController = shouldAbortOnTimeout ? new AbortController() : null; + const abortTimeoutIdentifier = abortController === null + ? null + : window.setTimeout(() => abortController.abort(), CONSUMPTION_REQUEST_TIMEOUT_MS); + try { + const headers = { + 'Content-Type': 'application/json', + 'Accept': 'application/json', + 'X-Requested-With': 'XMLHttpRequest' + }; + const token = document.querySelector('input[name="__RequestVerificationToken"]'); + if (token && token.value) + headers['RequestVerificationToken'] = token.value; + const response = await fetch(url, { + method: 'POST', + headers: headers, + body: JSON.stringify(payload ?? {}), + signal: abortController === null ? undefined : abortController.signal, + keepalive: options.keepalive === true + }); + // An expired session is redirected to the sign in page. Following it in the background would parse an HTML page as + // JSON and silently drop the rest of the history, so the reader navigates to the sign in page instead. + if (response.redirected) { + window.location.href = response.url; + return null; + } + if (!response.ok) + return null; + const jsonResponse = await response.json(); + return jsonResponse && jsonResponse.success === true ? jsonResponse.data : null; + } catch (error) { + console.debug('Book reader: a consumption request could not be sent.', error); + return null; + } finally { + if (abortTimeoutIdentifier !== null) + window.clearTimeout(abortTimeoutIdentifier); + } + } + + // Fetches the resume point of the current user for the book. It returns the resume point, null when the user has none, or + // undefined when the optional lookup failed. A failed lookup must not be treated as an absent one, because opening the first + // section and reporting it would overwrite the saved place with the start of the book. + async function fetchResumePointAsync() { + if (!resumePointUrl) + return undefined; + const abortController = new AbortController(); + const abortTimeoutIdentifier = window.setTimeout(() => abortController.abort(), RESUME_POINT_REQUEST_TIMEOUT_MS); + try { + const response = await fetch(resumePointUrl, { + headers: { + 'Accept': 'application/json', + 'X-Requested-With': 'XMLHttpRequest' + }, + signal: abortController.signal + }); + if (response.redirected) { + window.location.href = response.url; + return undefined; + } + if (!response.ok) + return undefined; + const jsonResponse = await response.json(); + // The web endpoint answers an absent resume point with a successful response that carries no data. Any other + // response shape is a failure of the optional lookup, not a statement that the user has no saved place. + if (!jsonResponse || jsonResponse.success !== true) + return undefined; + return jsonResponse.data; + } catch (error) { + console.debug('Book reader: the resume point could not be fetched.', error); + return undefined; + } finally { + window.clearTimeout(abortTimeoutIdentifier); + } + } + + // Resolves the section the resume point refers to. A locator that is missing, or that is no longer part of the spine, + // falls back to the first section, so a stale resume point never keeps the reader from opening the book. + function getInitialSectionIndex(resumePoint) { + const position = resumePoint ? resumePoint.lastPosition : null; + const location = position ? position.location : null; + if (!manifest || !manifest.spine || !location) + return 0; + const index = manifest.spine.findIndex(item => item.locationRef === location); + return index >= 0 ? index : 0; + } + + // Creates the state of one consumption session. The object identity is what lets a session that was replaced, such as one + // whose start request is still in flight when the page is restored from the back forward cache, still close the record it + // created instead of writing into the session that replaced it. + function createConsumptionSession() { + return { + recordId: null, + startPromise: null, + startSettled: false, + pendingEndPayload: null, + pendingEndOutcome: null, + progressSender: null, + pendingProgressPayload: null + }; + } + + // Gets the consumption session of the reader session, creating it when the first section opens. + function ensureConsumptionSession() { + if (consumptionSession === null) + consumptionSession = createConsumptionSession(); + return consumptionSession; + } + + // Starts the consumption record of the reader session, once the first section is displayed. The start is attempted once + // per session; a restored page starts a new session only when the previous start settled without a record. + function ensureConsumptionSessionStartedAsync() { + const session = ensureConsumptionSession(); + if (session.startPromise === null) + session.startPromise = startConsumptionSessionAsync(session); + return session.startPromise; + } + + async function startConsumptionSessionAsync(session) { + // The start is not aborted by the progress report timeout: a slow start can still succeed, and aborting it would resolve + // the session to no record id permanently even when the server created the record. + const record = await sendConsumptionRequestAsync(startConsumptionUrl, {}, { shouldAbortOnTimeout: false }); + session.startSettled = true; + const recordId = record && record.id ? String(record.id) : ''; + if (!recordId) + return null; + session.recordId = recordId; + // The session was ended and detached while the start request was in flight, so it still has a terminal payload to send. + // The record this request created is closed here with that payload, so it never stays in progress. + if (session.pendingEndPayload !== null) + finishEndedConsumptionSessionAsync(session).catch((error) => { + console.debug('Book reader: the consumption record of the replaced session could not be ended.', error); + }); + return record; + } + + // Queues a progress report of a session. The payloads are absolute, so only the newest queued report matters: a fast skip + // through many sections replaces the pending payload instead of appending one write per section. The sender is per session, + // so the reports of an ended session can never delay the reports of the session that replaced it. + function queueConsumptionSessionProgressReport(session, payload) { + if (session === null || session.recordId === null) + return Promise.resolve(); + session.pendingProgressPayload = payload; + if (session.progressSender === null) + session.progressSender = sendPendingConsumptionProgressAsync(session); + return session.progressSender; + } + + async function sendPendingConsumptionProgressAsync(session) { + try { + while (session.pendingProgressPayload !== null) { + const payload = session.pendingProgressPayload; + session.pendingProgressPayload = null; + const url = buildConsumptionRecordUrl(reportConsumptionProgressUrlTemplate, session.recordId); + await sendConsumptionRequestAsync(url, payload); + } + } catch (error) { + console.debug('Book reader: a consumption progress report could not be sent.', error); + } finally { + session.progressSender = null; + } + } + + // Sends the terminal request of an ended session. The terminal request carries the final page count and reading time, so it + // does not depend on a progress report that the document destruction of a page unload could cancel. It is also used by a start + // that resolves after its session was detached. + async function finishEndedConsumptionSessionAsync(session) { + if (session === null || session.recordId === null || session.pendingEndPayload === null || session.pendingEndOutcome === null) + return; + const endTemplate = session.pendingEndOutcome === 'complete' ? completeConsumptionUrlTemplate : stopConsumptionUrlTemplate; + await sendConsumptionRequestAsync(buildConsumptionRecordUrl(endTemplate, session.recordId), session.pendingEndPayload, { keepalive: true }); + } + + // Builds the body of a progress report: the section the reader shows, the fraction it represents, the active reading + // duration, and the number of consecutive pages read. + function buildReadingProgressPayload() { + return { + position: buildReadingPosition(), + // The fraction is not rounded: a page just before the last one of a large book would round up to 1, and a stop at + // that fraction would trip a 100 percent completion threshold and delete the resume point one page too early. + progressFraction: getReadingProgressFraction(), + consumedDurationInSeconds: getActiveReadingSeconds(), + consecutivePagesRead: consecutivePagesRead + }; + } + + // Builds the body of the terminal report of the session. It carries the page count as well, so a stop does not depend on a + // progress report that may still be in flight or that the page unload could cancel. + function buildReadingEndPayload() { + return { + position: buildReadingPosition(), + progressFraction: getReadingProgressFraction(), + consumedDurationInSeconds: getActiveReadingSeconds(), + consecutivePagesRead: consecutivePagesRead + }; + } + + // Ends the current consumption session, either as completed or as stopped. The payload is captured before the session is + // detached, so a restored page can reset the reading clock and the page count without changing what this session reports. + // When the start request is still in flight, its continuation either sends the captured terminal payload once the record + // identifier is known, or continues the revived session if the page is restored before that. + function finishConsumptionSession(outcome) { + if (isConsumptionSessionFinished) + return; + isConsumptionSessionFinished = true; + isConsumptionSessionCompleted = outcome === 'complete'; + stopReadingHeartbeat(); + const session = consumptionSession; + // No section was opened, so the reader never created a record to end. + if (session === null) + return; + session.pendingEndPayload = buildReadingEndPayload(); + session.pendingEndOutcome = outcome; + // The terminal request carries the final state, so a progress report that has not been sent yet is obsolete. + session.pendingProgressPayload = null; + consumptionSession = null; + // A record whose start already resolved is closed now. A record whose start is still in flight is closed by the start + // continuation, which uses the payload captured above. A session whose start is still in flight is remembered, so a page + // restored from the back forward cache revives it instead of creating a second record for the same reading session. + if (session.recordId !== null) + finishEndedConsumptionSessionAsync(session).catch((error) => { + console.debug('Book reader: the consumption record could not be ended.', error); + }); + else if (outcome === 'stop' && !session.startSettled) + pendingConsumptionSession = session; + } + + // Reports the progress of the reading session at the section the reader currently shows. The identity check ensures a + // report that was awaiting the start request cannot write into a session that replaced it. + async function reportReadingProgressAsync() { + if (isConsumptionSessionFinished) + return; + const session = ensureConsumptionSession(); + await ensureConsumptionSessionStartedAsync(); + if (isConsumptionSessionFinished || session !== consumptionSession || session.recordId === null) + return; + await queueConsumptionSessionProgressReport(session, buildReadingProgressPayload()); + } + + // Completes the reading session, because the reader reached the last section of the book. The terminal request carries the + // final page count and reading time, and the completion deletes the resume point of the book. + async function completeReadingSessionAsync() { + if (isConsumptionSessionFinished) + return; + // Starting is not awaited: when the start request is still in flight, the session captures the completion and its start + // continuation sends it once the record identifier is known. + ensureConsumptionSessionStartedAsync(); + finishConsumptionSession('complete'); + } + + // Stops the reading session when the reader is left before the last section was reached. Stopping is best effort and must + // never keep the reader from leaving the page. + function stopReadingSession() { + finishConsumptionSession('stop'); + } + + // Stops the reading session during an AJAX navigation, when the page remains alive. The coalesced progress sender is awaited + // before the terminal, so the two writes do not race on the record version. The unload path keeps the immediate stop, and the + // server retries the terminal if it still conflicts. + async function stopReadingSessionOnNavigationAsync() { + if (isConsumptionSessionFinished) + return; + // The clock is stopped before the wait, so the terminal duration does not include the time spent flushing reports. + stopReadingHeartbeat(); + const session = consumptionSession; + if (session !== null && session.progressSender !== null) + await session.progressSender; + finishConsumptionSession('stop'); + } + + // A page restored from the back forward cache keeps the reader on the section it showed. Its session was stopped when the + // page left, so a new session is started for the rest of the reading session, or the session whose start was still in flight + // is revived. A completed session is not restarted, because reaching the last section already ended the book. The finished + // state is reset even when the manifest or the first section has not resolved yet. + function handlePageShow(event) { + if (!event || event.persisted !== true) + return; + // A section load that was in flight when the page was frozen is invalidated, and navigation continues from the section + // that is actually displayed, not from a section that was requested but never shown. This is done even for a completed + // session, so a stale load cannot change the page the reader is left on, without restarting its reporting. + if (isInitialized && manifest && currentIndex >= 0) { + sectionLoadSequence++; + requestedIndex = currentIndex; + readerStatus.classList.add('hidden'); + if (sectionLoadAbortController !== null) { + sectionLoadAbortController.abort(); + sectionLoadAbortController = null; + } + } + if (isConsumptionSessionCompleted || !isConsumptionSessionFinished) + return; + isConsumptionSessionFinished = false; + // A session whose start request was still in flight when the page was hidden never received its record id, so it was + // neither stopped nor replaced. Reviving it keeps one record for the reading session. A session whose start already + // settled is not revived, because it either has a record that was closed or a start that cannot be retried from the + // same session. + const pendingSession = pendingConsumptionSession; + pendingConsumptionSession = null; + const canRevive = pendingSession !== null && pendingSession.recordId === null && !pendingSession.startSettled; + if (canRevive) { + pendingSession.pendingEndPayload = null; + pendingSession.pendingEndOutcome = null; + consumptionSession = pendingSession; + } + else + consumptionSession = null; + consecutivePagesRead = 1; + activeReadingMilliseconds = 0; + readingClockStartedOnMs = null; + if (!isInitialized || !manifest || currentIndex < 0) + return; + startReadingHeartbeat(); + reportReadingProgressAsync().catch((error) => { + console.debug('Book reader: the reading session of the restored page could not be started.', error); + }); + } + + // Updates the page count and reports the section the reader just opened. The first section opens the reader session, a + // forward page advance into the last section completes it, and every other section reports its progress. + async function handleSectionOpenedAsync(previousIndex, index) { + // A section that finishes loading after the reader was left belongs to a finished session and must not open a new one. + if (isConsumptionSessionFinished) + return; + // The count follows pages read, not forward jumps alone: the first displayed page starts a run at one, and a backward + // navigation starts a new run at the page it lands on, so a run that begins after a backward jump counts that page as + // its first. This is what makes a six page read count in both cases, instead of one page short after going back. + if (previousIndex < 0 || index < previousIndex) + consecutivePagesRead = 1; + else if (index > previousIndex) + consecutivePagesRead += 1; + if (readingHeartbeatTimer === null) + startReadingHeartbeat(); + // Only a forward page advance into the last section proves that the reading reached the end of the book. Opening + // the last section directly, such as on a single section book or from the table of contents, is not that proof, so it + // only reports progress and leaves the session open for the pages the reader turns afterwards. The Next control can + // still end the book explicitly from the last section. + const isForwardAdvance = previousIndex >= 0 && index === previousIndex + 1; + if (index === manifest.spine.length - 1 && isForwardAdvance) + await completeReadingSessionAsync(); + else + await reportReadingProgressAsync(); + } + + // Loads the reading manifest of the book, and opens the section the user resumes at, or the first section when there is + // no resume point. async function loadManifestAsync() { readerStatus.textContent = jsLocalizedStrings.loading; + // The resume point is requested together with the manifest, so opening a book costs one round trip instead of two. A + // missing or stale resume point only means that the first section is opened. + const resumePointPromise = fetchResumePointAsync(); const response = await fetch(manifestUrl, { headers: { 'Accept': 'application/json', @@ -122,11 +613,40 @@ readerStatus.textContent = jsLocalizedStrings.readFailed; return; } + // The resume lookup, and the start it may need to recover a lost resume position, are resolved before the manifest is + // exposed to the navigation controls. Until then the toolbar and the table of contents cannot start a navigation, so the + // resume jump cannot discard a section the user already requested. + let resumePointResult = null; + let initialSectionRecord = null; + if (manifestResponse.spine && manifestResponse.spine.length > 0) { + resumePointResult = await resumePointPromise; + if (resumePointResult === undefined) { + // The optional lookup failed, so the saved position is only available from the start response. The wait for it is + // bounded, so a slow or hung start cannot hold the reader on the loading state. The start continues in the + // background, but no section is opened provisionally, because reporting the first section could overwrite the + // saved place. + let startTimeoutIdentifier = null; + const startTimeoutPromise = new Promise(resolve => { + startTimeoutIdentifier = window.setTimeout(() => resolve(START_TIMED_OUT), RESUME_POINT_REQUEST_TIMEOUT_MS); + }); + initialSectionRecord = await Promise.race([ensureConsumptionSessionStartedAsync(), startTimeoutPromise]); + window.clearTimeout(startTimeoutIdentifier); + if (initialSectionRecord === START_TIMED_OUT || initialSectionRecord === null) { + readerStatus.textContent = jsLocalizedStrings.readFailed; + notificationService.show(jsLocalizedStrings.readFailed, NotificationType.ERROR); + return; + } + } + } manifest = manifestResponse; readerTitle.textContent = manifest.title || ''; renderTableOfContents(manifest.tableOfContents || []); - if (manifest.spine && manifest.spine.length > 0) - await goToIndexAsync(0); + if (manifest.spine && manifest.spine.length > 0) { + const initialIndex = resumePointResult === undefined + ? getInitialSectionIndex(initialSectionRecord) + : getInitialSectionIndex(resumePointResult); + await goToIndexAsync(initialIndex); + } else readerStatus.textContent = jsLocalizedStrings.readFailed; @@ -167,25 +687,81 @@ } } - // Opens the reading section at the given spine index. + // Fetches the content of a reading section. A superseded request is aborted, so a failure of a section the reader already + // left never reaches the error notification. The caller decides when a genuine failure is shown. + async function fetchReadingSectionAsync(locationRef, signal) { + try { + const response = await fetch(sectionUrlTemplate + encodeURIComponent(locationRef), { + headers: { + 'Accept': 'application/json', + 'X-Requested-With': 'XMLHttpRequest' + }, + signal + }); + if (response.redirected) { + window.location.href = response.url; + return REDIRECTED; + } + if (!response.ok) + return null; + const jsonResponse = await response.json(); + return jsonResponse && jsonResponse.success === true ? jsonResponse.data : null; + } catch (error) { + if (!error || error.name !== 'AbortError') + console.debug('Book reader: the reading section could not be fetched.', error); + return null; + } + } + + // Opens the reading section at the given spine index, and reports the reading session for it. async function goToIndexAsync(index) { if (!manifest || index < 0 || index >= manifest.spine.length) return; - currentIndex = index; + // The requested index advances before the section loads, so the navigation controls derive their next target from it + // instead of from the section that is still displayed. + requestedIndex = index; + const loadSequence = ++sectionLoadSequence; + // A new navigation aborts the previous section request, so its response can no longer render or report a failure the + // reader has already left. + if (sectionLoadAbortController !== null) + sectionLoadAbortController.abort(); + const abortController = new AbortController(); + sectionLoadAbortController = abortController; // The status line lives outside the content container, so that replacing the section content cannot destroy it; it is // shown while a section loads and hidden once the section is rendered, and a failing section load leaves it visible with // the failure message. readerStatus.classList.remove('hidden'); readerStatus.textContent = jsLocalizedStrings.loading; - const response = await callApiGetAsync(sectionUrlTemplate + encodeURIComponent(manifest.spine[index].locationRef)); - if (!response) { + const section = await fetchReadingSectionAsync(manifest.spine[index].locationRef, abortController.signal); + if (sectionLoadAbortController === abortController) + sectionLoadAbortController = null; + // A navigation made after this one supersedes its result, so a slow section can never overwrite the newer one or + // report the same page advance twice. An aborted request is silent, even when its failure arrives after the abort. + if (loadSequence !== sectionLoadSequence || abortController.signal.aborted || section === REDIRECTED) + return; + if (!section) { readerStatus.textContent = jsLocalizedStrings.readFailed; + notificationService.show(jsLocalizedStrings.readFailed, NotificationType.ERROR); + // The failed section was never displayed, so the navigation controls retry from the section that is still shown. + requestedIndex = currentIndex; return; } - readerContent.innerHTML = response.contentHtml || ''; + const previousIndex = currentIndex; + currentIndex = index; + readerContent.innerHTML = section.contentHtml || ''; resolveResources(); updatePosition(); readerStatus.classList.add('hidden'); + // Reporting runs in the background, so a slow consumption endpoint never delays showing the section. + handleSectionOpenedAsync(previousIndex, index).catch((error) => { + console.debug('Book reader: the reading session could not be reported.', error); + }); + } + + // Gets the section the navigation controls move from: the section already requested while another one is loading, or + // the section that is currently displayed. + function getRequestedSectionIndex() { + return requestedIndex >= 0 ? requestedIndex : currentIndex; } // Resolves the resource marker attributes of the rendered content, pointing them at the reading resource endpoint. @@ -254,12 +830,22 @@ // On previous button click, opens the previous reading section. function handlePrevClick() { - goToIndexAsync(currentIndex - 1); + goToIndexAsync(getRequestedSectionIndex() - 1); } - // On next button click, opens the next reading section. + // On next button click, opens the next reading section. At the requested last section, once it is also the displayed + // section, it ends the book explicitly. Both values are checked, so a Next pressed while a backward navigation is loading + // moves back to the requested section instead of completing the book the user is leaving. function handleNextClick() { - goToIndexAsync(currentIndex + 1); + const requestedSectionIndex = getRequestedSectionIndex(); + if (manifest && requestedSectionIndex >= 0 && requestedSectionIndex === manifest.spine.length - 1 && + currentIndex === requestedSectionIndex) { + completeReadingSessionAsync().catch((error) => { + console.debug('Book reader: the reading session could not be completed.', error); + }); + return; + } + goToIndexAsync(requestedSectionIndex + 1); } // Applies the current font size to the reading content. @@ -288,6 +874,10 @@ btnFontDecrease.addEventListener('click', handleFontDecreaseClick); btnFontIncrease.addEventListener('click', handleFontIncreaseClick); document.addEventListener('DOMContentLoaded', InitializeAsync); + document.addEventListener('visibilitychange', handleVisibilityChange); + // A full page unload does not run the view cleanups, so the last reading time and page are also stopped on pagehide. + window.addEventListener('pagehide', stopReadingSession); + window.addEventListener('pageshow', handlePageShow); // Register cleanup for these listeners. cleanupFunctions.push(() => { @@ -299,6 +889,16 @@ btnFontDecrease.removeEventListener('click', handleFontDecreaseClick); btnFontIncrease.removeEventListener('click', handleFontIncreaseClick); document.removeEventListener('DOMContentLoaded', InitializeAsync); + document.removeEventListener('visibilitychange', handleVisibilityChange); + window.removeEventListener('pagehide', stopReadingSession); + window.removeEventListener('pageshow', handlePageShow); + // Abort a section that is still loading, so its failure cannot show a notification after the reader is gone. + if (sectionLoadAbortController !== null) + sectionLoadAbortController.abort(); + // The page remains alive during an AJAX navigation, so the progress sender is awaited before the terminal request. + stopReadingSessionOnNavigationAsync().catch((error) => { + console.debug('Book reader: the consumption record could not be stopped.', error); + }); }); // Initializes the reader, loading the reading manifest of the book; the DOMContentLoaded listener covers the initial