diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaConsumption/MediaConsumptionRecordEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaConsumption/MediaConsumptionRecordEntity.cs
index f35c1123..a1ab167b 100644
--- a/src/Lumina.Application/Common/DataAccess/Entities/MediaConsumption/MediaConsumptionRecordEntity.cs
+++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaConsumption/MediaConsumptionRecordEntity.cs
@@ -20,24 +20,24 @@ public class MediaConsumptionRecordEntity : IStorageEntity, IAuditableEntity
public required Guid Id { get; init; }
///
- /// Gets the Id of the user that started the consumption session.
+ /// Gets or sets the Id of the user that started the consumption session.
///
- public required Guid UserId { get; init; }
+ public required Guid UserId { get; set; }
///
- /// Gets the Id of the media library that contains the consumed media item.
+ /// Gets or sets the Id of the media library that contains the consumed media item.
///
- public required Guid LibraryId { get; init; }
+ public required Guid LibraryId { get; set; }
///
- /// Gets the kind of media that was consumed.
+ /// Gets or sets the kind of media that was consumed.
///
- public required MediaKind MediaKind { get; init; }
+ public required MediaKind MediaKind { get; set; }
///
- /// Gets the Id of the consumed media item.
+ /// Gets or sets the Id of the consumed media item.
///
- public required Guid MediaItemId { get; init; }
+ public required Guid MediaItemId { get; set; }
///
/// Gets or sets the state of the consumption session.
@@ -45,9 +45,9 @@ public class MediaConsumptionRecordEntity : IStorageEntity, IAuditableEntity
public ConsumptionStatus Status { get; set; }
///
- /// Gets the date and time when the consumption session started.
+ /// Gets or sets the date and time when the consumption session started.
///
- public required DateTime StartedOnUtc { get; init; }
+ public required DateTime StartedOnUtc { get; set; }
///
/// Gets or sets the date and time when the consumption session last received activity.
diff --git a/src/Lumina.Application/Common/DataAccess/Entities/MediaConsumption/MediaResumePointEntity.cs b/src/Lumina.Application/Common/DataAccess/Entities/MediaConsumption/MediaResumePointEntity.cs
index 3ac22e66..b0f03f25 100644
--- a/src/Lumina.Application/Common/DataAccess/Entities/MediaConsumption/MediaResumePointEntity.cs
+++ b/src/Lumina.Application/Common/DataAccess/Entities/MediaConsumption/MediaResumePointEntity.cs
@@ -20,24 +20,24 @@ public class MediaResumePointEntity : IStorageEntity, IAuditableEntity
public required Guid Id { get; init; }
///
- /// Gets the Id of the user that owns the resume point.
+ /// Gets or sets the Id of the user that owns the resume point.
///
- public required Guid UserId { get; init; }
+ public required Guid UserId { get; set; }
///
- /// Gets the Id of the media library that contains the media item.
+ /// Gets or sets the Id of the media library that contains the media item.
///
- public required Guid LibraryId { get; init; }
+ public required Guid LibraryId { get; set; }
///
- /// Gets the kind of media that is resumed.
+ /// Gets or sets the kind of media that is resumed.
///
- public required MediaKind MediaKind { get; init; }
+ public required MediaKind MediaKind { get; set; }
///
- /// Gets the Id of the media item to resume.
+ /// Gets or sets the Id of the media item to resume.
///
- public required Guid MediaItemId { get; init; }
+ public required Guid MediaItemId { get; set; }
///
/// Gets the kind of representation used by the position at which the media item can be resumed.
diff --git a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs
index 13b7acda..e2ea758a 100644
--- a/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs
+++ b/src/Lumina.Application/Common/DataAccess/UoW/IUnitOfWork.cs
@@ -2,6 +2,7 @@
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
+using Lumina.Application.Common.DataAccess.Repositories.MediaConsumption;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
@@ -167,6 +168,16 @@ public interface IUnitOfWork
///
IFavoriteRepository FavoriteRepository { get; }
+ ///
+ /// Gets the media consumption record repository.
+ ///
+ IMediaConsumptionRecordRepository MediaConsumptionRecordRepository { get; }
+
+ ///
+ /// Gets the media resume point repository.
+ ///
+ IMediaResumePointRepository MediaResumePointRepository { get; }
+
///
/// Saves the changes made to the database.
///
diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/CompleteConsumptionRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/CompleteConsumptionRequestMapping.cs
new file mode 100644
index 00000000..98ef0741
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/CompleteConsumptionRequestMapping.cs
@@ -0,0 +1,30 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaConsumption.Commands.CompleteConsumption;
+using Lumina.Contracts.Requests.MediaConsumption;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaConsumption;
+
+///
+/// Extension methods for converting .
+///
+public static class CompleteConsumptionRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The Id of the consumption record, taken from the route.
+ /// The converted command.
+ public static CompleteConsumptionCommand ToCommand(this CompleteConsumptionRequest request, string? consumptionRecordId)
+ {
+ return new CompleteConsumptionCommand(
+ consumptionRecordId,
+ request.Position?.Kind,
+ request.Position?.TimeOffsetSeconds,
+ request.Position?.Location,
+ request.ProgressFraction,
+ request.ConsumedDurationInSeconds
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/ReportConsumptionProgressRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/ReportConsumptionProgressRequestMapping.cs
new file mode 100644
index 00000000..698173a9
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/ReportConsumptionProgressRequestMapping.cs
@@ -0,0 +1,31 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaConsumption.Commands.ReportConsumptionProgress;
+using Lumina.Contracts.Requests.MediaConsumption;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaConsumption;
+
+///
+/// Extension methods for converting .
+///
+public static class ReportConsumptionProgressRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The Id of the consumption record, taken from the route.
+ /// The converted command.
+ public static ReportConsumptionProgressCommand ToCommand(this ReportConsumptionProgressRequest request, string? consumptionRecordId)
+ {
+ return new ReportConsumptionProgressCommand(
+ consumptionRecordId,
+ request.Position?.Kind,
+ request.Position?.TimeOffsetSeconds,
+ request.Position?.Location,
+ request.ProgressFraction,
+ request.ConsumedDurationInSeconds,
+ request.ConsecutivePagesRead
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/StopConsumptionRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/StopConsumptionRequestMapping.cs
new file mode 100644
index 00000000..c9a789e3
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/StopConsumptionRequestMapping.cs
@@ -0,0 +1,30 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Core.MediaConsumption.Commands.StopConsumption;
+using Lumina.Contracts.Requests.MediaConsumption;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaConsumption;
+
+///
+/// Extension methods for converting .
+///
+public static class StopConsumptionRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The Id of the consumption record, taken from the route.
+ /// The converted command.
+ public static StopConsumptionCommand ToCommand(this StopConsumptionRequest request, string? consumptionRecordId)
+ {
+ return new StopConsumptionCommand(
+ consumptionRecordId,
+ request.Position?.Kind,
+ request.Position?.TimeOffsetSeconds,
+ request.Position?.Location,
+ request.ProgressFraction,
+ request.ConsumedDurationInSeconds
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs
index 85860594..52e3d970 100644
--- a/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/Management/LibraryEntityMapping.cs
@@ -59,9 +59,7 @@ public static class LibraryEntityMapping
if (pathTemplateResult.IsFailure)
return pathTemplateResult.Errors;
- LibraryConsumptionSettings consumptionSettings = LibraryConsumptionSettings.Create(
- repositoryEntity.ShouldTrackConsumptionProgress,
- Optional.FromNullable(repositoryEntity.CompletionThresholdPercentage));
+ LibraryConsumptionSettings consumptionSettings = repositoryEntity.ToDomainValueObject();
return Library.Create(
LibraryId.Create(repositoryEntity.Id),
@@ -81,6 +79,18 @@ public static class LibraryEntityMapping
);
}
+ ///
+ /// Converts the consumption settings stored on to .
+ ///
+ /// The repository entity whose consumption settings are converted.
+ /// The converted consumption settings.
+ public static LibraryConsumptionSettings ToDomainValueObject(this LibraryEntity repositoryEntity)
+ {
+ return LibraryConsumptionSettings.Create(
+ repositoryEntity.ShouldTrackConsumptionProgress,
+ Optional.FromNullable(repositoryEntity.CompletionThresholdPercentage));
+ }
+
///
/// Builds the path template of a media library from its ordered stored parts.
///
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommand.cs
new file mode 100644
index 00000000..e388e893
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommand.cs
@@ -0,0 +1,25 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.MediaConsumption.Commands.CompleteConsumption;
+
+///
+/// Command for reporting that a consumption session of the current user completed.
+///
+/// The unique identifier of the consumption record, taken from the route.
+/// The name of the kind of the final position reached in the media item, if the client reported one.
+/// The final position within the media item, in seconds, when the position is a time offset.
+/// 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}")]
+public record CompleteConsumptionCommand(
+ string? ConsumptionRecordId,
+ string? PositionKind,
+ double? PositionTimeOffsetInSeconds,
+ string? PositionLocation,
+ double? ProgressFraction,
+ double? ConsumedDurationInSeconds
+) : ICommand;
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandHandler.cs
new file mode 100644
index 00000000..2db8038a
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandHandler.cs
@@ -0,0 +1,146 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DomainEvents;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.MediaConsumption.Commands.CompleteConsumption;
+
+///
+/// Handler for the command to report that a consumption session of the current user completed.
+///
+public class CompleteConsumptionCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IDomainEventsQueue _domainEventsQueue;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for the queue of domain events.
+ /// Injected validator for application validation rules.
+ public CompleteConsumptionCommandHandler(
+ IUnitOfWork unitOfWork,
+ ICurrentUserService currentUserService,
+ IDomainEventsQueue domainEventsQueue,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _domainEventsQueue = domainEventsQueue;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to report that a consumption session of the current user completed.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the completed , or an error message.
+ ///
+ public async Task> HandleAsync(CompleteConsumptionCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // The validator guarantees that the route identifier and the reported measurements are valid before this point.
+ Guid consumptionRecordId = Guid.Parse(command.ConsumptionRecordId!);
+
+ // 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;
+
+ Optional position = ToMediaPosition(command.PositionKind, command.PositionTimeOffsetInSeconds, command.PositionLocation);
+
+ Result completeResult = record.Complete(position, command.ProgressFraction!.Value, TimeSpan.FromSeconds(command.ConsumedDurationInSeconds!.Value));
+ if (completeResult.IsFailure)
+ return completeResult.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;
+
+ 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();
+ }
+
+ ///
+ /// Converts reported position fields that have already been validated to a .
+ ///
+ /// The name of the kind of the reported position, or when no position was reported.
+ /// The reported position within the media item, in seconds, when the position is a time offset.
+ /// The reported opaque locator within the media item, when the position is not a time offset.
+ /// The converted position, or no position when the client did not report one.
+ private static Optional ToMediaPosition(string? positionKind, double? timeOffsetInSeconds, string? location)
+ {
+ // A missing kind means the client did not report a position at all, which is different from a position at zero.
+ if (string.IsNullOrWhiteSpace(positionKind))
+ return Optional.None();
+
+ // The validator already rejected unknown and undefined kinds, so the parse is safe here and no fallback value is invented.
+ MediaPositionKind parsedPositionKind = Enum.Parse(positionKind, ignoreCase: true);
+ // The kind names the single representation that the validator accepted, so only that representation is read.
+ return parsedPositionKind == MediaPositionKind.TimeOffset
+ ? Optional.Some(MediaPosition.CreateTimeOffset(TimeSpan.FromSeconds(timeOffsetInSeconds!.Value)))
+ : Optional.Some(MediaPosition.CreateLocation(location!));
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandValidator.cs
new file mode 100644
index 00000000..a93bacbb
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/CompleteConsumption/CompleteConsumptionCommandValidator.cs
@@ -0,0 +1,92 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
+using System;
+#endregion
+
+namespace Lumina.Application.Core.MediaConsumption.Commands.CompleteConsumption;
+
+///
+/// Validates the needed validation rules for .
+///
+public class CompleteConsumptionCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public CompleteConsumptionCommandValidator()
+ {
+ // Validates the identifier of the consumption record, taken from the route.
+ RuleFor(command => command.ConsumptionRecordId)
+ .NotEmpty()
+ .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty);
+
+ RuleFor(command => command.ConsumptionRecordId)
+ .Must(consumptionRecordId => Guid.TryParse(consumptionRecordId, out Guid parsedConsumptionRecordId) && parsedConsumptionRecordId != Guid.Empty)
+ .When(command => command.ConsumptionRecordId is not null && command.ConsumptionRecordId.Length > 0)
+ .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty);
+
+ // Validates that the reported position describes exactly one position, using the representation its kind names.
+ RuleFor(command => command.PositionKind)
+ .Must((command, positionKind) => IsPositionShapeValid(
+ positionKind, command.PositionTimeOffsetInSeconds, command.PositionLocation))
+ .WithError(Errors.MediaConsumption.InvalidMediaPosition);
+
+ RuleFor(command => command.ProgressFraction)
+ .NotNull()
+ .WithError(Errors.MediaConsumption.InvalidProgressFraction);
+
+ RuleFor(command => command.ProgressFraction)
+ .Must(progressFraction => progressFraction is null ||
+ (double.IsFinite(progressFraction.Value) && progressFraction.Value >= 0 && progressFraction.Value <= 1))
+ .WithError(Errors.MediaConsumption.InvalidProgressFraction);
+
+ RuleFor(command => command.ConsumedDurationInSeconds)
+ .NotNull()
+ .WithError(Errors.MediaConsumption.ConsumedDurationMustBeNonNegative);
+
+ RuleFor(command => command.ConsumedDurationInSeconds)
+ .Must(consumedDuration => consumedDuration is null ||
+ (double.IsFinite(consumedDuration.Value) && consumedDuration.Value >= 0))
+ .WithError(Errors.MediaConsumption.ConsumedDurationMustBeNonNegative);
+
+ RuleFor(command => command.ConsumedDurationInSeconds)
+ .Must(consumedDuration => consumedDuration is null ||
+ consumedDuration.Value <= TimeSpan.MaxValue.TotalSeconds)
+ .WithError(Errors.MediaConsumption.ConsumedDurationIsOutOfRange);
+ }
+
+ ///
+ /// Determines whether the reported position fields describe exactly one valid position.
+ ///
+ /// The name of the kind of the reported position, or when no position was reported.
+ /// The reported position within the media item, in seconds, when the position is a time offset.
+ /// The reported opaque locator within the media item, when the position is not a time offset.
+ /// if the position fields are valid, otherwise.
+ private static bool IsPositionShapeValid(string? positionKind, double? timeOffsetInSeconds, string? location)
+ {
+ // No kind means no position was reported, so a time offset or a locator without a kind would make the representation ambiguous.
+ if (string.IsNullOrWhiteSpace(positionKind))
+ return !timeOffsetInSeconds.HasValue && string.IsNullOrWhiteSpace(location);
+ // Unknown and numeric kind names are not valid positions, even when the other fields look well formed.
+ if (!Enum.TryParse(positionKind, ignoreCase: true, out MediaPositionKind parsedPositionKind) || !Enum.IsDefined(parsedPositionKind))
+ return false;
+
+ // A position uses exactly one representation, because MediaPosition stores one kind and one value, so the fields of the other
+ // representation must be absent instead of ignored.
+ return parsedPositionKind switch
+ {
+ MediaPositionKind.TimeOffset => timeOffsetInSeconds.HasValue &&
+ double.IsFinite(timeOffsetInSeconds.Value) &&
+ timeOffsetInSeconds.Value >= 0 &&
+ timeOffsetInSeconds.Value <= TimeSpan.MaxValue.TotalSeconds &&
+ string.IsNullOrWhiteSpace(location),
+ MediaPositionKind.Location => !timeOffsetInSeconds.HasValue &&
+ !string.IsNullOrWhiteSpace(location) &&
+ location.Length <= 4096,
+ _ => false
+ };
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommand.cs
new file mode 100644
index 00000000..8dd5a35e
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommand.cs
@@ -0,0 +1,27 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.MediaConsumption.Commands.ReportConsumptionProgress;
+
+///
+/// Command for reporting the progress of a consumption session of the current user.
+///
+/// The unique identifier of the consumption record, taken from the route.
+/// The name of the kind of the position reached in the media item, if the client reported one.
+/// The position within the media item, in seconds, when the position is a time offset.
+/// 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.
+[DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}; ProgressFraction: {ProgressFraction}")]
+public record ReportConsumptionProgressCommand(
+ string? ConsumptionRecordId,
+ string? PositionKind,
+ double? PositionTimeOffsetInSeconds,
+ string? PositionLocation,
+ double? ProgressFraction,
+ double? ConsumedDurationInSeconds,
+ int ConsecutivePagesRead
+) : ICommand;
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommandHandler.cs
new file mode 100644
index 00000000..2531336b
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommandHandler.cs
@@ -0,0 +1,218 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DomainEvents;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Common.Mapping.MediaLibrary.Management;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate;
+using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaResumePointAggregate;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.MediaConsumption.Commands.ReportConsumptionProgress;
+
+///
+/// Handler for the command to report the progress of a consumption session of the current user.
+///
+public class ReportConsumptionProgressCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IDomainEventsQueue _domainEventsQueue;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for the queue of domain events.
+ /// Injected validator for application validation rules.
+ public ReportConsumptionProgressCommandHandler(
+ IUnitOfWork unitOfWork,
+ ICurrentUserService currentUserService,
+ IDomainEventsQueue domainEventsQueue,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _domainEventsQueue = domainEventsQueue;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to report the progress of a consumption session of the current user.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the updated , or an error message.
+ ///
+ public async Task> HandleAsync(ReportConsumptionProgressCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // The validator guarantees that the route identifier and the reported measurements are valid before this point.
+ Guid consumptionRecordId = Guid.Parse(command.ConsumptionRecordId!);
+
+ // 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 progress is tracked. 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);
+
+ // A report never completes a session, because seeking to the end of the media item is not the same as reaching the end of the session.
+ Result reportProgressResult = record.ReportProgress(position, command.ProgressFraction!.Value, TimeSpan.FromSeconds(command.ConsumedDurationInSeconds!.Value), command.ConsecutivePagesRead);
+ if (reportProgressResult.IsFailure)
+ return reportProgressResult.Errors;
+
+ Optional ruleResult = MediaConsumptionRule.For(record.MediaKind);
+ if (!ruleResult.HasValue)
+ return DomainErrors.MediaConsumption.UnsupportedMediaKind;
+
+ // Only libraries that track progress keep a resume point, and only for kinds that support resuming. When the client reported no position,
+ // the last known position of the session is reused, so the resume point does not lose a position that an earlier report supplied.
+ if (consumptionSettings.ShouldTrackConsumptionProgress && ruleResult.Value.CanResume)
+ {
+ Optional resumePosition = position.HasValue ? position : record.LastPosition;
+ if (resumePosition.HasValue)
+ {
+ Result upsertResumePointResult = await UpsertResumePointAsync(record, resumePosition.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)
+ 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();
+ }
+
+ ///
+ /// Converts reported position fields that have already been validated to a .
+ ///
+ /// The name of the kind of the reported position, or when no position was reported.
+ /// The reported position within the media item, in seconds, when the position is a time offset.
+ /// The reported opaque locator within the media item, when the position is not a time offset.
+ /// The converted position, or no position when the client did not report one.
+ private static Optional ToMediaPosition(string? positionKind, double? timeOffsetInSeconds, string? location)
+ {
+ // A missing kind means the client did not report a position at all, which is different from a position at zero.
+ if (string.IsNullOrWhiteSpace(positionKind))
+ return Optional.None();
+
+ // The validator already rejected unknown and undefined kinds, so the parse is safe here and no fallback value is invented.
+ MediaPositionKind parsedPositionKind = Enum.Parse(positionKind, ignoreCase: true);
+ // The kind names the single representation that the validator accepted, so only that representation is read.
+ return parsedPositionKind == MediaPositionKind.TimeOffset
+ ? Optional.Some(MediaPosition.CreateTimeOffset(TimeSpan.FromSeconds(timeOffsetInSeconds!.Value)))
+ : Optional.Some(MediaPosition.CreateLocation(location!));
+ }
+
+ ///
+ /// Creates or updates the resume point of for the current user.
+ ///
+ /// The consumption record whose session is being tracked.
+ /// The position at which the media item can be resumed.
+ /// The progress fraction at which the media item can be resumed.
+ /// The Id of the user the resume point belongs to.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful save, or an error message.
+ private async Task> UpsertResumePointAsync(MediaConsumptionRecord record, MediaPosition position, double progressFraction, Guid userId, CancellationToken cancellationToken)
+ {
+ // The resume point is read without tracking because it is only used to build the domain aggregate. The upsert call locates and updates
+ // the stored row itself, so tracking this copy would put two tracked instances of the same row in the same unit of work.
+ Result getResumePointResult = await _unitOfWork.MediaResumePointRepository
+ .GetForUserAndMediaItemAsync(userId, record.MediaKind, record.MediaItemId.Value, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getResumePointResult.IsFailure)
+ return getResumePointResult.Errors;
+
+ MediaResumePoint resumePoint;
+ if (getResumePointResult.Value is null)
+ {
+ // A resume point that does not exist yet is created from the session identifiers and the effective position. The position and
+ // fraction are the ones the caller applied to the record, so the resume point and the record cannot disagree about the report.
+ Result createResumePointResult = MediaResumePoint.Create(
+ record.UserId, record.LibraryId, record.MediaItemId, record.MediaKind, position, progressFraction, record.LastActivityOnUtc);
+ if (createResumePointResult.IsFailure)
+ return createResumePointResult.Errors;
+ resumePoint = createResumePointResult.Value;
+ }
+ else
+ {
+ // An existing resume point is advanced instead of replaced, so its identifier and creation time survive and its own rules validate
+ // the new position and fraction before the update. The activity time is taken from the record, so both rows describe the same report.
+ Result toDomainEntityResult = getResumePointResult.Value.ToDomainEntity();
+ if (toDomainEntityResult.IsFailure)
+ return toDomainEntityResult.Errors;
+ Result advanceResult = toDomainEntityResult.Value.Advance(position, progressFraction, record.LastActivityOnUtc);
+ if (advanceResult.IsFailure)
+ return advanceResult.Errors;
+ resumePoint = toDomainEntityResult.Value;
+ }
+
+ // The upsert decides between the insert and the update from the unique business key, so a concurrent report that created the row
+ // between the read above and this call still ends with one resume point instead of a duplicate.
+ return await _unitOfWork.MediaResumePointRepository.UpsertForUserAsync(resumePoint.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommandValidator.cs
new file mode 100644
index 00000000..88f963b4
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/ReportConsumptionProgress/ReportConsumptionProgressCommandValidator.cs
@@ -0,0 +1,96 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
+using System;
+#endregion
+
+namespace Lumina.Application.Core.MediaConsumption.Commands.ReportConsumptionProgress;
+
+///
+/// Validates the needed validation rules for .
+///
+public class ReportConsumptionProgressCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public ReportConsumptionProgressCommandValidator()
+ {
+ // Validates the identifier of the consumption record, taken from the route.
+ RuleFor(command => command.ConsumptionRecordId)
+ .NotEmpty()
+ .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty);
+
+ RuleFor(command => command.ConsumptionRecordId)
+ .Must(consumptionRecordId => Guid.TryParse(consumptionRecordId, out Guid parsedConsumptionRecordId) && parsedConsumptionRecordId != Guid.Empty)
+ .When(command => command.ConsumptionRecordId is not null && command.ConsumptionRecordId.Length > 0)
+ .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty);
+
+ // Validates that the reported position describes exactly one position, using the representation its kind names.
+ RuleFor(command => command.PositionKind)
+ .Must((command, positionKind) => IsPositionShapeValid(
+ positionKind, command.PositionTimeOffsetInSeconds, command.PositionLocation))
+ .WithError(Errors.MediaConsumption.InvalidMediaPosition);
+
+ RuleFor(command => command.ProgressFraction)
+ .NotNull()
+ .WithError(Errors.MediaConsumption.InvalidProgressFraction);
+
+ RuleFor(command => command.ProgressFraction)
+ .Must(progressFraction => progressFraction is null ||
+ (double.IsFinite(progressFraction.Value) && progressFraction.Value >= 0 && progressFraction.Value <= 1))
+ .WithError(Errors.MediaConsumption.InvalidProgressFraction);
+
+ RuleFor(command => command.ConsumedDurationInSeconds)
+ .NotNull()
+ .WithError(Errors.MediaConsumption.ConsumedDurationMustBeNonNegative);
+
+ RuleFor(command => command.ConsumedDurationInSeconds)
+ .Must(consumedDuration => consumedDuration is null ||
+ (double.IsFinite(consumedDuration.Value) && consumedDuration.Value >= 0))
+ .WithError(Errors.MediaConsumption.ConsumedDurationMustBeNonNegative);
+
+ RuleFor(command => command.ConsumedDurationInSeconds)
+ .Must(consumedDuration => consumedDuration is null ||
+ consumedDuration.Value <= TimeSpan.MaxValue.TotalSeconds)
+ .WithError(Errors.MediaConsumption.ConsumedDurationIsOutOfRange);
+
+ RuleFor(command => command.ConsecutivePagesRead)
+ .Must(consecutivePagesRead => consecutivePagesRead >= 0)
+ .WithError(Errors.MediaConsumption.ConsecutivePagesReadMustBeNonNegative);
+ }
+
+ ///
+ /// Determines whether the reported position fields describe exactly one valid position.
+ ///
+ /// The name of the kind of the reported position, or when no position was reported.
+ /// The reported position within the media item, in seconds, when the position is a time offset.
+ /// The reported opaque locator within the media item, when the position is not a time offset.
+ /// if the position fields are valid, otherwise.
+ private static bool IsPositionShapeValid(string? positionKind, double? timeOffsetInSeconds, string? location)
+ {
+ // No kind means no position was reported, so a time offset or a locator without a kind would make the representation ambiguous.
+ if (string.IsNullOrWhiteSpace(positionKind))
+ return !timeOffsetInSeconds.HasValue && string.IsNullOrWhiteSpace(location);
+ // Unknown and numeric kind names are not valid positions, even when the other fields look well formed.
+ if (!Enum.TryParse(positionKind, ignoreCase: true, out MediaPositionKind parsedPositionKind) || !Enum.IsDefined(parsedPositionKind))
+ return false;
+
+ // A position uses exactly one representation, because MediaPosition stores one kind and one value, so the fields of the other
+ // representation must be absent instead of ignored.
+ return parsedPositionKind switch
+ {
+ MediaPositionKind.TimeOffset => timeOffsetInSeconds.HasValue &&
+ double.IsFinite(timeOffsetInSeconds.Value) &&
+ timeOffsetInSeconds.Value >= 0 &&
+ timeOffsetInSeconds.Value <= TimeSpan.MaxValue.TotalSeconds &&
+ string.IsNullOrWhiteSpace(location),
+ MediaPositionKind.Location => !timeOffsetInSeconds.HasValue &&
+ !string.IsNullOrWhiteSpace(location) &&
+ location.Length <= 4096,
+ _ => false
+ };
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommand.cs
new file mode 100644
index 00000000..fd59cc96
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommand.cs
@@ -0,0 +1,19 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.MediaConsumption.Commands.StartConsumption;
+
+///
+/// Command for starting a consumption session of a media item by the current user.
+///
+/// The unique identifier of the media library that contains the media item, taken from the route.
+/// The kind of media that is consumed, taken from the route.
+/// The unique identifier of the consumed media item, taken from the route.
+[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
+public record StartConsumptionCommand(
+ string? LibraryId,
+ string? MediaKind,
+ string? MediaItemId
+) : ICommand;
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandHandler.cs
new file mode 100644
index 00000000..9cc18c87
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandHandler.cs
@@ -0,0 +1,189 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DomainEvents;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Common.Mapping.MediaLibrary.Management;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.MediaLibraryBoundedContext.MediaItemAggregate;
+using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.UserManagementBoundedContext.UserAggregate;
+using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate;
+using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaResumePointAggregate;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using ConsumptionLibraryId = Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate.LibraryId;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.MediaConsumption.Commands.StartConsumption;
+
+///
+/// Handler for the command to start a consumption session of a media item by the current user.
+///
+public class StartConsumptionCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly IDomainEventsQueue _domainEventsQueue;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for authorization related functionality.
+ /// Injected service for the queue of domain events.
+ /// Injected validator for application validation rules.
+ public StartConsumptionCommandHandler(
+ IUnitOfWork unitOfWork,
+ ICurrentUserService currentUserService,
+ IAuthorizationService authorizationService,
+ IDomainEventsQueue domainEventsQueue,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ _domainEventsQueue = domainEventsQueue;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to start a consumption session of a media item by the current user.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the created , or an error message.
+ ///
+ public async Task> HandleAsync(StartConsumptionCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // The validator guarantees that the route identifiers are non-empty Guids and the media kind is a defined value before this point.
+ Guid libraryId = Guid.Parse(command.LibraryId!);
+ Guid mediaItemId = Guid.Parse(command.MediaItemId!);
+ MediaKind mediaKind = Enum.Parse(command.MediaKind!, ignoreCase: true);
+
+ // Admins can start sessions in the libraries of all users; for everyone else, only in the libraries they own. Authorization is evaluated
+ // before the kind is checked or any library or media item is read, so an unauthorized caller cannot probe whether a resource exists.
+ bool canAccessLibrary = await _authorizationService.EvaluatePolicyAsync(userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
+ if (!canAccessLibrary)
+ return ApplicationErrors.Authorization.NotAuthorized;
+
+ // A kind that has no consumption rule, and a kind whose catalogue does not exist yet, cannot be consumed.
+ Optional ruleResult = MediaConsumptionRule.For(mediaKind);
+ if (!ruleResult.HasValue || !ruleResult.Value.IsSupportedByCurrentCatalogues)
+ return DomainErrors.MediaConsumption.UnsupportedMediaKind;
+ MediaConsumptionRule rule = ruleResult.Value;
+
+ // The library is loaded after authorization, so an unauthorized caller cannot probe whether it exists. For an authorized caller, a missing
+ // library is reported as not found.
+ Result getLibraryResult = await _unitOfWork.LibraryRepository
+ .GetByIdAsync(libraryId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getLibraryResult.IsFailure)
+ return getLibraryResult.Errors;
+ if (getLibraryResult.Value is null)
+ return DomainErrors.Library.LibraryNotFound;
+ LibraryConsumptionSettings consumptionSettings = getLibraryResult.Value.ToDomainValueObject();
+
+ // The item is resolved through the catalogue repository of its kind, and the route library is enforced on the loaded row. A wrong-library
+ // item is reported exactly like a missing item, so the route cannot be used to probe items of other libraries.
+ if (mediaKind == MediaKind.MusicTrack)
+ {
+ Result getTrackResult = await _unitOfWork.TrackRepository
+ .GetByIdAsync(mediaItemId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getTrackResult.IsFailure)
+ return getTrackResult.Errors;
+ if (getTrackResult.Value is null || getTrackResult.Value.LibraryId != libraryId)
+ return DomainErrors.Music.TrackNotFound;
+ }
+ else if (mediaKind == MediaKind.Book)
+ {
+ Result getBookResult = await _unitOfWork.BookRepository
+ .GetByIdAsync(mediaItemId, shouldIncludeNavigationProperties: false, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getBookResult.IsFailure)
+ return getBookResult.Errors;
+ if (getBookResult.Value is null || getBookResult.Value.LibraryId != libraryId)
+ return DomainErrors.WrittenContent.BookNotFound;
+ }
+ else
+ return DomainErrors.MediaConsumption.UnsupportedMediaKind;
+
+ // When the library tracks progress and the kind can resume, the new session continues from the stored resume point. The consumed duration
+ // always starts at zero, because it measures this session only.
+ Optional initialPosition = Optional.None();
+ double initialProgressFraction = 0;
+ if (consumptionSettings.ShouldTrackConsumptionProgress && rule.CanResume)
+ {
+ Result getResumePointResult = await _unitOfWork.MediaResumePointRepository
+ .GetForUserAndMediaItemAsync(userId, mediaKind, mediaItemId, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getResumePointResult.IsFailure)
+ return getResumePointResult.Errors;
+ if (getResumePointResult.Value is not null)
+ {
+ Result toDomainEntityResult = getResumePointResult.Value.ToDomainEntity();
+ if (toDomainEntityResult.IsFailure)
+ return toDomainEntityResult.Errors;
+ initialPosition = Optional.Some(toDomainEntityResult.Value.LastPosition);
+ initialProgressFraction = toDomainEntityResult.Value.LastProgressFraction;
+ }
+ }
+
+ // A one-shot kind such as a photo completes in the same call, because a single view does not have a start and a stop request.
+ Result createRecordResult = rule.IsOneShot
+ ? MediaConsumptionRecord.StartCompleted(UserId.Create(userId), ConsumptionLibraryId.Create(libraryId), MediaItemId.Create(mediaItemId), mediaKind)
+ : MediaConsumptionRecord.Start(UserId.Create(userId), ConsumptionLibraryId.Create(libraryId), MediaItemId.Create(mediaItemId), mediaKind, initialPosition, initialProgressFraction);
+ if (createRecordResult.IsFailure)
+ return createRecordResult.Errors;
+ MediaConsumptionRecord record = createRecordResult.Value;
+
+ Result insertResult = await _unitOfWork.MediaConsumptionRecordRepository.InsertAsync(record.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
+ if (insertResult.IsFailure)
+ return insertResult.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 the auditing interceptor 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();
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandValidator.cs
new file mode 100644
index 00000000..b18b3d34
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StartConsumption/StartConsumptionCommandValidator.cs
@@ -0,0 +1,51 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+#endregion
+
+namespace Lumina.Application.Core.MediaConsumption.Commands.StartConsumption;
+
+///
+/// Validates the needed validation rules for .
+///
+public class StartConsumptionCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public StartConsumptionCommandValidator()
+ {
+ // Validates the identifier of the media library that contains the media item, taken from the route.
+ RuleFor(command => command.LibraryId)
+ .NotEmpty()
+ .WithError(Errors.Library.LibraryIdCannotBeEmpty);
+
+ RuleFor(command => command.LibraryId)
+ .Must(libraryId => Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty)
+ .When(command => command.LibraryId is not null && command.LibraryId.Length > 0)
+ .WithError(Errors.Library.LibraryIdCannotBeEmpty);
+
+ // Validates the kind of media that is consumed, taken from the route. Kinds that are not supported by the current catalogues are rejected by the handler, because that is a business rule.
+ RuleFor(command => command.MediaKind)
+ .NotEmpty()
+ .WithError(Errors.MediaConsumption.UnsupportedMediaKind);
+
+ RuleFor(command => command.MediaKind)
+ .Must(mediaKind => Enum.TryParse(mediaKind, ignoreCase: true, out MediaKind parsedMediaKind) && Enum.IsDefined(parsedMediaKind))
+ .When(command => command.MediaKind is not null && command.MediaKind.Length > 0)
+ .WithError(Errors.MediaConsumption.UnsupportedMediaKind);
+
+ // Validates the identifier of the consumed media item, taken from the route.
+ RuleFor(command => command.MediaItemId)
+ .NotEmpty()
+ .WithError(Errors.MediaConsumption.MediaItemIdCannotBeEmpty);
+
+ RuleFor(command => command.MediaItemId)
+ .Must(mediaItemId => Guid.TryParse(mediaItemId, out Guid parsedMediaItemId) && parsedMediaItemId != Guid.Empty)
+ .When(command => command.MediaItemId is not null && command.MediaItemId.Length > 0)
+ .WithError(Errors.MediaConsumption.MediaItemIdCannotBeEmpty);
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommand.cs
new file mode 100644
index 00000000..eecb06db
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommand.cs
@@ -0,0 +1,25 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.MediaConsumption.Commands.StopConsumption;
+
+///
+/// Command for reporting that a consumption session of the current user stopped before it completed.
+///
+/// The unique identifier of the consumption record, taken from the route.
+/// The name of the kind of the final position reached in the media item, if the client reported one.
+/// The final position within the media item, in seconds, when the position is a time offset.
+/// 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}")]
+public record StopConsumptionCommand(
+ string? ConsumptionRecordId,
+ string? PositionKind,
+ double? PositionTimeOffsetInSeconds,
+ string? PositionLocation,
+ double? ProgressFraction,
+ double? ConsumedDurationInSeconds
+) : ICommand;
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandHandler.cs
new file mode 100644
index 00000000..bcbb472d
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandHandler.cs
@@ -0,0 +1,230 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DomainEvents;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Common.Mapping.MediaLibrary.Management;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.Common.Events;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryAggregate.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
+using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaConsumptionRecordAggregate;
+using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.MediaResumePointAggregate;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.Application.Core.MediaConsumption.Commands.StopConsumption;
+
+///
+/// Handler for the command to report that a consumption session of the current user stopped before it completed.
+///
+public class StopConsumptionCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IDomainEventsQueue _domainEventsQueue;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for the queue of domain events.
+ /// Injected validator for application validation rules.
+ public StopConsumptionCommandHandler(
+ IUnitOfWork unitOfWork,
+ ICurrentUserService currentUserService,
+ IDomainEventsQueue domainEventsQueue,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _domainEventsQueue = domainEventsQueue;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to report that a consumption session of the current user stopped before it completed.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the stopped or completed , or an error message.
+ ///
+ public async Task> HandleAsync(StopConsumptionCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // The validator guarantees that the route identifier and the reported measurements are valid before this point.
+ Guid consumptionRecordId = Guid.Parse(command.ConsumptionRecordId!);
+
+ // 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();
+
+ Optional position = ToMediaPosition(command.PositionKind, command.PositionTimeOffsetInSeconds, command.PositionLocation);
+ 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)
+ {
+ // 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)
+ 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();
+ }
+
+ ///
+ /// Converts reported position fields that have already been validated to a .
+ ///
+ /// The name of the kind of the reported position, or when no position was reported.
+ /// The reported position within the media item, in seconds, when the position is a time offset.
+ /// The reported opaque locator within the media item, when the position is not a time offset.
+ /// The converted position, or no position when the client did not report one.
+ private static Optional ToMediaPosition(string? positionKind, double? timeOffsetInSeconds, string? location)
+ {
+ // A missing kind means the client did not report a position at all, which is different from a position at zero.
+ if (string.IsNullOrWhiteSpace(positionKind))
+ return Optional.None();
+
+ // The validator already rejected unknown and undefined kinds, so the parse is safe here and no fallback value is invented.
+ MediaPositionKind parsedPositionKind = Enum.Parse(positionKind, ignoreCase: true);
+ // The kind names the single representation that the validator accepted, so only that representation is read.
+ return parsedPositionKind == MediaPositionKind.TimeOffset
+ ? Optional.Some(MediaPosition.CreateTimeOffset(TimeSpan.FromSeconds(timeOffsetInSeconds!.Value)))
+ : Optional.Some(MediaPosition.CreateLocation(location!));
+ }
+
+ ///
+ /// Creates or updates the resume point of for the current user.
+ ///
+ /// The consumption record whose session is being tracked.
+ /// The position at which the media item can be resumed.
+ /// The progress fraction at which the media item can be resumed.
+ /// The Id of the user the resume point belongs to.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful save, or an error message.
+ private async Task> UpsertResumePointAsync(
+ MediaConsumptionRecord record, MediaPosition position, double progressFraction, Guid userId, CancellationToken cancellationToken)
+ {
+ // The resume point is read without tracking because it is only used to build the domain aggregate. The upsert call locates and updates
+ // the stored row itself, so tracking this copy would put two tracked instances of the same row in the same unit of work.
+ Result getResumePointResult = await _unitOfWork.MediaResumePointRepository
+ .GetForUserAndMediaItemAsync(userId, record.MediaKind, record.MediaItemId.Value, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
+ if (getResumePointResult.IsFailure)
+ return getResumePointResult.Errors;
+
+ MediaResumePoint resumePoint;
+ if (getResumePointResult.Value is null)
+ {
+ // A resume point that does not exist yet is created from the session identifiers and the effective position. The position and
+ // fraction are the ones the caller applied to the record, so the resume point and the record cannot disagree about the report.
+ Result createResumePointResult = MediaResumePoint.Create(
+ record.UserId, record.LibraryId, record.MediaItemId, record.MediaKind, position, progressFraction, record.LastActivityOnUtc);
+ if (createResumePointResult.IsFailure)
+ return createResumePointResult.Errors;
+ resumePoint = createResumePointResult.Value;
+ }
+ else
+ {
+ // An existing resume point is advanced instead of replaced, so its identifier and creation time survive and its own rules validate
+ // the new position and fraction before the update. The activity time is taken from the record, so both rows describe the same report.
+ Result toDomainEntityResult = getResumePointResult.Value.ToDomainEntity();
+ if (toDomainEntityResult.IsFailure)
+ return toDomainEntityResult.Errors;
+ Result advanceResult = toDomainEntityResult.Value.Advance(position, progressFraction, record.LastActivityOnUtc);
+ if (advanceResult.IsFailure)
+ return advanceResult.Errors;
+ resumePoint = toDomainEntityResult.Value;
+ }
+
+ // The upsert decides between the insert and the update from the unique business key, so a concurrent report that created the row
+ // between the read above and this call still ends with one resume point instead of a duplicate.
+ return await _unitOfWork.MediaResumePointRepository.UpsertForUserAsync(resumePoint.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false);
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandValidator.cs
new file mode 100644
index 00000000..2351fa76
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/StopConsumption/StopConsumptionCommandValidator.cs
@@ -0,0 +1,92 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.Infrastructure.Validation;
+using Lumina.Application.Common.Utilities;
+using Lumina.Domain.Common.Errors;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
+using System;
+#endregion
+
+namespace Lumina.Application.Core.MediaConsumption.Commands.StopConsumption;
+
+///
+/// Validates the needed validation rules for .
+///
+public class StopConsumptionCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public StopConsumptionCommandValidator()
+ {
+ // Validates the identifier of the consumption record, taken from the route.
+ RuleFor(command => command.ConsumptionRecordId)
+ .NotEmpty()
+ .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty);
+
+ RuleFor(command => command.ConsumptionRecordId)
+ .Must(consumptionRecordId => Guid.TryParse(consumptionRecordId, out Guid parsedConsumptionRecordId) && parsedConsumptionRecordId != Guid.Empty)
+ .When(command => command.ConsumptionRecordId is not null && command.ConsumptionRecordId.Length > 0)
+ .WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty);
+
+ // Validates that the reported position describes exactly one position, using the representation its kind names.
+ RuleFor(command => command.PositionKind)
+ .Must((command, positionKind) => IsPositionShapeValid(
+ positionKind, command.PositionTimeOffsetInSeconds, command.PositionLocation))
+ .WithError(Errors.MediaConsumption.InvalidMediaPosition);
+
+ RuleFor(command => command.ProgressFraction)
+ .NotNull()
+ .WithError(Errors.MediaConsumption.InvalidProgressFraction);
+
+ RuleFor(command => command.ProgressFraction)
+ .Must(progressFraction => progressFraction is null ||
+ (double.IsFinite(progressFraction.Value) && progressFraction.Value >= 0 && progressFraction.Value <= 1))
+ .WithError(Errors.MediaConsumption.InvalidProgressFraction);
+
+ RuleFor(command => command.ConsumedDurationInSeconds)
+ .NotNull()
+ .WithError(Errors.MediaConsumption.ConsumedDurationMustBeNonNegative);
+
+ RuleFor(command => command.ConsumedDurationInSeconds)
+ .Must(consumedDuration => consumedDuration is null ||
+ (double.IsFinite(consumedDuration.Value) && consumedDuration.Value >= 0))
+ .WithError(Errors.MediaConsumption.ConsumedDurationMustBeNonNegative);
+
+ RuleFor(command => command.ConsumedDurationInSeconds)
+ .Must(consumedDuration => consumedDuration is null ||
+ consumedDuration.Value <= TimeSpan.MaxValue.TotalSeconds)
+ .WithError(Errors.MediaConsumption.ConsumedDurationIsOutOfRange);
+ }
+
+ ///
+ /// Determines whether the reported position fields describe exactly one valid position.
+ ///
+ /// The name of the kind of the reported position, or when no position was reported.
+ /// The reported position within the media item, in seconds, when the position is a time offset.
+ /// The reported opaque locator within the media item, when the position is not a time offset.
+ /// if the position fields are valid, otherwise.
+ private static bool IsPositionShapeValid(string? positionKind, double? timeOffsetInSeconds, string? location)
+ {
+ // No kind means no position was reported, so a time offset or a locator without a kind would make the representation ambiguous.
+ if (string.IsNullOrWhiteSpace(positionKind))
+ return !timeOffsetInSeconds.HasValue && string.IsNullOrWhiteSpace(location);
+ // Unknown and numeric kind names are not valid positions, even when the other fields look well formed.
+ if (!Enum.TryParse(positionKind, ignoreCase: true, out MediaPositionKind parsedPositionKind) || !Enum.IsDefined(parsedPositionKind))
+ return false;
+
+ // A position uses exactly one representation, because MediaPosition stores one kind and one value, so the fields of the other
+ // representation must be absent instead of ignored.
+ return parsedPositionKind switch
+ {
+ MediaPositionKind.TimeOffset => timeOffsetInSeconds.HasValue &&
+ double.IsFinite(timeOffsetInSeconds.Value) &&
+ timeOffsetInSeconds.Value >= 0 &&
+ timeOffsetInSeconds.Value <= TimeSpan.MaxValue.TotalSeconds &&
+ string.IsNullOrWhiteSpace(location),
+ MediaPositionKind.Location => !timeOffsetInSeconds.HasValue &&
+ !string.IsNullOrWhiteSpace(location) &&
+ location.Length <= 4096,
+ _ => false
+ };
+ }
+}
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/CompleteConsumptionRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/CompleteConsumptionRequest.cs
index 79b76e5a..f1d79885 100644
--- a/src/Lumina.Contracts/Requests/MediaConsumption/CompleteConsumptionRequest.cs
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/CompleteConsumptionRequest.cs
@@ -13,6 +13,6 @@ namespace Lumina.Contracts.Requests.MediaConsumption;
[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}")]
public sealed record CompleteConsumptionRequest(
MediaPositionRequest? Position,
- double ProgressFraction,
- double ConsumedDurationInSeconds
+ double? ProgressFraction,
+ double? ConsumedDurationInSeconds
);
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs
index 53a6cb56..7d0760c2 100644
--- a/src/Lumina.Contracts/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/ReportConsumptionProgressRequest.cs
@@ -14,7 +14,7 @@ namespace Lumina.Contracts.Requests.MediaConsumption;
[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}; ConsecutivePagesRead: {ConsecutivePagesRead}")]
public sealed record ReportConsumptionProgressRequest(
MediaPositionRequest? Position,
- double ProgressFraction,
- double ConsumedDurationInSeconds,
+ double? ProgressFraction,
+ double? ConsumedDurationInSeconds,
int ConsecutivePagesRead = 0
);
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/StopConsumptionRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/StopConsumptionRequest.cs
index 9295cc65..f566e815 100644
--- a/src/Lumina.Contracts/Requests/MediaConsumption/StopConsumptionRequest.cs
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/StopConsumptionRequest.cs
@@ -13,6 +13,6 @@ namespace Lumina.Contracts.Requests.MediaConsumption;
[DebuggerDisplay("ProgressFraction: {ProgressFraction}; ConsumedDurationInSeconds: {ConsumedDurationInSeconds}")]
public sealed record StopConsumptionRequest(
MediaPositionRequest? Position,
- double ProgressFraction,
- double ConsumedDurationInSeconds
+ double? ProgressFraction,
+ double? ConsumedDurationInSeconds
);
diff --git a/src/Lumina.DataAccess/Common/Configuration/MediaConsumptionRecordConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/MediaConsumptionRecordConfiguration.cs
new file mode 100644
index 00000000..0282a73f
--- /dev/null
+++ b/src/Lumina.DataAccess/Common/Configuration/MediaConsumptionRecordConfiguration.cs
@@ -0,0 +1,127 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+#endregion
+
+namespace Lumina.DataAccess.Common.Configuration;
+
+///
+/// Configures the entity mapping for the entity.
+///
+public class MediaConsumptionRecordConfiguration : IEntityTypeConfiguration
+{
+ ///
+ /// Configures the entity.
+ ///
+ /// The builder to be used to configure the entity.
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("MediaConsumptionRecords");
+ builder.HasKey(record => record.Id);
+ builder.Property(record => record.Id)
+ .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
+ .HasColumnOrder(0);
+
+ // A consumption record belongs to the user that started it, and it is removed with that user.
+ builder.HasOne()
+ .WithMany()
+ .HasForeignKey(record => record.UserId)
+ .IsRequired()
+ .OnDelete(DeleteBehavior.Cascade);
+
+ builder.Property(record => record.UserId)
+ .IsRequired()
+ .HasColumnOrder(1);
+
+ builder.Property(record => record.LibraryId)
+ .IsRequired()
+ .HasColumnOrder(2);
+
+ builder.Property(record => record.MediaItemId)
+ .IsRequired()
+ .HasColumnOrder(3);
+
+ builder.Property(record => record.MediaKind)
+ .IsRequired()
+ .HasConversion()
+ .HasMaxLength(20)
+ .HasColumnOrder(4);
+
+ builder.Property(record => record.Status)
+ .IsRequired()
+ .HasConversion()
+ .HasMaxLength(20)
+ .HasColumnOrder(5);
+
+ builder.Property(record => record.StartedOnUtc)
+ .IsRequired()
+ .HasColumnOrder(6);
+
+ builder.Property(record => record.LastActivityOnUtc)
+ .IsRequired()
+ .HasColumnOrder(7);
+
+ builder.Property(record => record.EndedOnUtc)
+ .HasColumnOrder(8);
+
+ builder.Property(record => record.ConsumedDurationMilliseconds)
+ .IsRequired()
+ .HasColumnOrder(9);
+
+ builder.Property(record => record.LastPositionKind)
+ .HasConversion()
+ .HasMaxLength(20)
+ .IsRequired(false)
+ .HasColumnOrder(10);
+
+ builder.Property(record => record.LastPositionTimeOffsetMilliseconds)
+ .HasColumnOrder(11);
+
+ builder.Property(record => record.LastPositionLocation)
+ .HasMaxLength(4096)
+ .HasColumnOrder(12);
+
+ builder.Property(record => record.LastProgressFraction)
+ .IsRequired()
+ .HasColumnOrder(13);
+
+ builder.Property(record => record.ConsecutivePagesRead)
+ .IsRequired()
+ .HasDefaultValue(0)
+ .HasColumnOrder(14);
+
+ // The version is the optimistic concurrency token: every update increments it, and an update whose loaded version no longer matches
+ // the stored one affects no row and fails, instead of reverting a session that another report already completed or stopped.
+ builder.Property(record => record.Version)
+ .IsRequired()
+ .IsConcurrencyToken()
+ .HasColumnOrder(15);
+
+ // Audit.
+ builder.Property(record => record.CreatedOnUtc)
+ .IsRequired()
+ .HasColumnOrder(16);
+
+ builder.Property(record => record.CreatedBy)
+ .IsRequired()
+ .HasColumnOrder(17);
+
+ builder.Property(record => record.UpdatedOnUtc)
+ .HasDefaultValue(null)
+ .HasColumnOrder(18);
+
+ builder.Property(record => record.UpdatedBy)
+ .HasDefaultValue(null)
+ .HasColumnOrder(19);
+
+ // The referenced media item is kept by kind and Id only, without a foreign key: one table serves every media kind, so no single table
+ // can be referenced, and a session survives the deletion of the item it references.
+ // Enables listing the history of a user from the most recent activity, optionally restricted to one media kind and item.
+ builder.HasIndex(record => new { record.UserId, record.MediaKind, record.MediaItemId, record.LastActivityOnUtc });
+
+ // Enables the statistics of a user restricted by media kind and date range.
+ builder.HasIndex(record => new { record.UserId, record.MediaKind, record.StartedOnUtc });
+ }
+}
diff --git a/src/Lumina.DataAccess/Common/Configuration/MediaResumePointConfiguration.cs b/src/Lumina.DataAccess/Common/Configuration/MediaResumePointConfiguration.cs
new file mode 100644
index 00000000..1a237733
--- /dev/null
+++ b/src/Lumina.DataAccess/Common/Configuration/MediaResumePointConfiguration.cs
@@ -0,0 +1,103 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.Entities.UsersManagement;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.EntityFrameworkCore.Metadata.Builders;
+#endregion
+
+namespace Lumina.DataAccess.Common.Configuration;
+
+///
+/// Configures the entity mapping for the entity.
+///
+public class MediaResumePointConfiguration : IEntityTypeConfiguration
+{
+ ///
+ /// Configures the entity.
+ ///
+ /// The builder to be used to configure the entity.
+ public void Configure(EntityTypeBuilder builder)
+ {
+ builder.ToTable("MediaResumePoints");
+ builder.HasKey(resumePoint => resumePoint.Id);
+ builder.Property(resumePoint => resumePoint.Id)
+ .ValueGeneratedNever() // because EF always tries to generate the value for the Id, and because we generate it as part of the aggregate root, we need to tell EF not to generate it
+ .HasColumnOrder(0);
+
+ // A resume point belongs to the user that owns it, and it is removed with that user.
+ builder.HasOne()
+ .WithMany()
+ .HasForeignKey(resumePoint => resumePoint.UserId)
+ .IsRequired()
+ .OnDelete(DeleteBehavior.Cascade);
+
+ builder.Property(resumePoint => resumePoint.UserId)
+ .IsRequired()
+ .HasColumnOrder(1);
+
+ builder.Property(resumePoint => resumePoint.LibraryId)
+ .IsRequired()
+ .HasColumnOrder(2);
+
+ builder.Property(resumePoint => resumePoint.MediaKind)
+ .IsRequired()
+ .HasConversion()
+ .HasMaxLength(20)
+ .HasColumnOrder(3);
+
+ builder.Property(resumePoint => resumePoint.MediaItemId)
+ .IsRequired()
+ .HasColumnOrder(4);
+
+ builder.Property(resumePoint => resumePoint.LastPositionKind)
+ .IsRequired()
+ .HasConversion()
+ .HasMaxLength(20)
+ .HasColumnOrder(5);
+
+ builder.Property(resumePoint => resumePoint.LastPositionTimeOffsetMilliseconds)
+ .HasColumnOrder(6);
+
+ builder.Property(resumePoint => resumePoint.LastPositionLocation)
+ .HasMaxLength(4096)
+ .HasColumnOrder(7);
+
+ builder.Property(resumePoint => resumePoint.LastProgressFraction)
+ .IsRequired()
+ .HasColumnOrder(8);
+
+ builder.Property(resumePoint => resumePoint.LastConsumedOnUtc)
+ .IsRequired()
+ .HasColumnOrder(9);
+
+ // The version is the optimistic concurrency token: every update increments it, and an update whose loaded version no longer matches
+ // the stored one affects no row and fails, instead of reverting a resume point that another report already advanced.
+ builder.Property(resumePoint => resumePoint.Version)
+ .IsRequired()
+ .IsConcurrencyToken()
+ .HasColumnOrder(10);
+
+ // Audit.
+ builder.Property(resumePoint => resumePoint.CreatedOnUtc)
+ .IsRequired()
+ .HasColumnOrder(11);
+
+ builder.Property(resumePoint => resumePoint.CreatedBy)
+ .IsRequired()
+ .HasColumnOrder(12);
+
+ builder.Property(resumePoint => resumePoint.UpdatedOnUtc)
+ .HasDefaultValue(null)
+ .HasColumnOrder(13);
+
+ builder.Property(resumePoint => resumePoint.UpdatedBy)
+ .HasDefaultValue(null)
+ .HasColumnOrder(14);
+
+ // The referenced media item is kept by kind and Id only, without a foreign key: one table serves every media kind, so no single table
+ // can be referenced, and a resume point survives the deletion of the item it references.
+ // The unique index makes the storage medium the owner of the "one resume point per user and item" invariant.
+ builder.HasIndex(resumePoint => new { resumePoint.UserId, resumePoint.MediaKind, resumePoint.MediaItemId })
+ .IsUnique();
+ }
+}
diff --git a/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaConsumptionRecordRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaConsumptionRecordRepository.cs
new file mode 100644
index 00000000..3732ecb8
--- /dev/null
+++ b/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaConsumptionRecordRepository.cs
@@ -0,0 +1,167 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.Repositories.MediaConsumption;
+using Lumina.DataAccess.Common.Persistence;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Microsoft.EntityFrameworkCore;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using DomainErrors = Lumina.Domain.Common.Errors.Errors;
+#endregion
+
+namespace Lumina.DataAccess.Core.Repositories.MediaConsumption;
+
+///
+/// Repository for media consumption records.
+///
+///
+/// Records are always read, updated, and deleted scoped to their owner. The media item they reference is kept by kind and Id only, so a deleted media item leaves the record and its statistics intact.
+///
+internal sealed class MediaConsumptionRecordRepository : IMediaConsumptionRecordRepository
+{
+ private readonly LuminaDbContext _luminaDbContext;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Entity Framework DbContext.
+ public MediaConsumptionRecordRepository(LuminaDbContext luminaDbContext)
+ {
+ _luminaDbContext = luminaDbContext;
+ }
+
+ ///
+ /// Adds a new consumption record.
+ ///
+ /// The consumption record to add.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful operation, or an error.
+ public Task> InsertAsync(MediaConsumptionRecordEntity data, CancellationToken cancellationToken)
+ {
+ // The handler creates a new session with a newly generated Id, so this always adds a row.
+ _luminaDbContext.MediaConsumptionRecords.Add(data);
+ return Task.FromResult>(Result.Created);
+ }
+
+ ///
+ /// Gets the consumption record identified by when it belongs to the user identified by , if it exists.
+ ///
+ /// The Id of the consumption record to get.
+ /// The Id of the user the consumption record must belong to.
+ /// Whether the retrieved record should be tracked by the persistence medium, so that changes to it can be saved.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the consumption record identified by and owned by
+ /// , when no such record exists, or an error.
+ ///
+ public async Task> GetByIdForUserAsync(Guid id, Guid userId, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
+ {
+ // The user is part of the filter rather than a check performed after the read, so the storage medium never returns a record that belongs to another user in the first place.
+ IQueryable query = _luminaDbContext.MediaConsumptionRecords
+ .Where(record => record.Id == id && record.UserId == userId);
+ if (!shouldTrackEntities)
+ query = query.AsNoTracking();
+ return await query.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Updates the consumption record of the user identified by , when the record belongs to that user and still holds the version it was read with.
+ ///
+ /// The consumption record whose editable values are applied to the stored record. Its owner must match .
+ /// The Id of the user the consumption record must belong to. It is authoritative for locating the stored record; the owner carried by is not used to select it.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful update, or an error.
+ public async Task> UpdateForUserAsync(MediaConsumptionRecordEntity data, Guid userId, CancellationToken cancellationToken)
+ {
+ // The user is part of both the tracked and the stored lookup, so a caller can never update a record that belongs to another user merely by knowing its Id.
+ MediaConsumptionRecordEntity? foundRecord = _luminaDbContext.MediaConsumptionRecords.Local
+ .FirstOrDefault(record => record.Id == data.Id && record.UserId == userId)
+ ?? await _luminaDbContext.MediaConsumptionRecords
+ .FirstOrDefaultAsync(record => record.Id == data.Id && record.UserId == userId, cancellationToken).ConfigureAwait(false);
+ if (foundRecord is null)
+ return DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
+
+ // A report that carries the values that are already stored is a no-op: writing it would bump the version for nothing, and a
+ // concurrent stop or complete that read the same version could then fail for a report that changed no data.
+ if (!HasEditableChanges(foundRecord, data))
+ return Result.Updated;
+
+ // The stored identity is never overwritten by an edit, and the audit columns are only ever written by the auditing interceptor.
+ // The version is captured before the copy and incremented after it, so the update is only applied when the row still holds the version the report read.
+ Guid storedUserId = foundRecord.UserId;
+ Guid libraryId = foundRecord.LibraryId;
+ Guid mediaItemId = foundRecord.MediaItemId;
+ MediaKind mediaKind = foundRecord.MediaKind;
+ DateTime startedOnUtc = foundRecord.StartedOnUtc;
+ long version = foundRecord.Version;
+ EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundRecord, data);
+ foundRecord.UserId = storedUserId;
+ foundRecord.LibraryId = libraryId;
+ foundRecord.MediaItemId = mediaItemId;
+ foundRecord.MediaKind = mediaKind;
+ foundRecord.StartedOnUtc = startedOnUtc;
+ foundRecord.Version = version + 1;
+ return Result.Updated;
+ }
+
+ ///
+ /// Deletes the consumption record identified by when it belongs to the user identified by . A record that does not exist is not an error.
+ ///
+ /// The Id of the consumption record to delete.
+ /// The Id of the user the consumption record must belong to.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful deletion, or an error.
+ public async Task> DeleteForUserAsync(Guid id, Guid userId, CancellationToken cancellationToken)
+ {
+ // A handler may already have loaded the same record in this unit of work, so the tracked instance is preferred over materializing a second copy.
+ MediaConsumptionRecordEntity? record = _luminaDbContext.MediaConsumptionRecords.Local
+ .FirstOrDefault(trackedRecord => trackedRecord.Id == id && trackedRecord.UserId == userId)
+ ?? await _luminaDbContext.MediaConsumptionRecords
+ .FirstOrDefaultAsync(foundRecord => foundRecord.Id == id && foundRecord.UserId == userId, cancellationToken).ConfigureAwait(false);
+ if (record is null)
+ return Result.Deleted;
+
+ _luminaDbContext.MediaConsumptionRecords.Remove(record);
+ return Result.Deleted;
+ }
+
+ ///
+ /// Deletes every consumption record of the user identified by .
+ ///
+ /// The Id of the user whose consumption records are deleted.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful deletion, or an error.
+ public async Task> DeleteAllForUserAsync(Guid userId, CancellationToken cancellationToken)
+ {
+ List records = await _luminaDbContext.MediaConsumptionRecords
+ .Where(record => record.UserId == userId)
+ .ToListAsync(cancellationToken).ConfigureAwait(false);
+ if (records.Count > 0)
+ _luminaDbContext.MediaConsumptionRecords.RemoveRange(records);
+ return Result.Deleted;
+ }
+
+ ///
+ /// Determines whether carries values that differ from the stored record.
+ ///
+ /// The record currently stored in the persistence medium.
+ /// The record carrying the values to apply.
+ /// if an editable value changed, otherwise.
+ private static bool HasEditableChanges(MediaConsumptionRecordEntity stored, MediaConsumptionRecordEntity incoming)
+ {
+ return stored.Status != incoming.Status ||
+ stored.LastActivityOnUtc != incoming.LastActivityOnUtc ||
+ stored.EndedOnUtc != incoming.EndedOnUtc ||
+ stored.ConsumedDurationMilliseconds != incoming.ConsumedDurationMilliseconds ||
+ stored.LastPositionKind != incoming.LastPositionKind ||
+ stored.LastPositionTimeOffsetMilliseconds != incoming.LastPositionTimeOffsetMilliseconds ||
+ stored.LastPositionLocation != incoming.LastPositionLocation ||
+ stored.LastProgressFraction != incoming.LastProgressFraction ||
+ stored.ConsecutivePagesRead != incoming.ConsecutivePagesRead;
+ }
+}
diff --git a/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaResumePointRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaResumePointRepository.cs
new file mode 100644
index 00000000..3af4edfa
--- /dev/null
+++ b/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaResumePointRepository.cs
@@ -0,0 +1,179 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
+using Lumina.Application.Common.DataAccess.Repositories.MediaConsumption;
+using Lumina.DataAccess.Common.Persistence;
+using Lumina.DataAccess.Core.UoW;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Microsoft.EntityFrameworkCore;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.DataAccess.Core.Repositories.MediaConsumption;
+
+///
+/// Repository for media resume points.
+///
+///
+/// The business key of a resume point is the user, the media kind, and the media item. The unique index on those columns makes the storage
+/// medium the owner of the "one resume point per user and item" invariant, and an upsert updates the existing row instead of inserting a second one.
+///
+internal sealed class MediaResumePointRepository : IMediaResumePointRepository
+{
+ private readonly LuminaDbContext _luminaDbContext;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected Entity Framework DbContext.
+ public MediaResumePointRepository(LuminaDbContext luminaDbContext)
+ {
+ _luminaDbContext = luminaDbContext;
+ }
+
+ ///
+ /// Gets the resume point of the user identified by for the media item identified by and , if it exists.
+ ///
+ /// The Id of the user the resume point must belong to.
+ /// The kind of the media item to resume.
+ /// The Id of the media item to resume.
+ /// Whether the retrieved resume point should be tracked by the persistence medium, so that changes to it can be saved.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the resume point of the user for the media item, when no such resume point exists, or an error.
+ ///
+ public async Task> GetForUserAndMediaItemAsync(Guid userId, MediaKind mediaKind, Guid mediaItemId, bool shouldTrackEntities = true, CancellationToken cancellationToken = default)
+ {
+ // The user is part of the filter rather than a check performed after the read, so the storage medium never returns a resume point that belongs to another user in the first place.
+ IQueryable query = _luminaDbContext.MediaResumePoints
+ .Where(resumePoint => resumePoint.UserId == userId &&
+ resumePoint.MediaKind == mediaKind &&
+ resumePoint.MediaItemId == mediaItemId);
+ if (!shouldTrackEntities)
+ query = query.AsNoTracking();
+ return await query.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Saves the resume point of the user identified by , inserting it when it does not exist and updating it otherwise. The
+ /// business key of the resume point, made of the user, the media kind, and the media item, is preserved.
+ ///
+ /// The resume point whose values are saved. Its owner must match .
+ /// The Id of the user the resume point must belong to. It is authoritative for locating the stored resume point and for the owner of a new one; the owner carried by is not used to select it.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful save, or an error.
+ public async Task> UpsertForUserAsync(MediaResumePointEntity data, Guid userId, CancellationToken cancellationToken)
+ {
+ // The business key is located in the tracked entities first, so an upsert of a resume point that this unit of work already loaded updates that instance instead of materializing a second copy.
+ MediaResumePointEntity? foundResumePoint = _luminaDbContext.MediaResumePoints.Local
+ .FirstOrDefault(resumePoint => resumePoint.UserId == userId &&
+ resumePoint.MediaKind == data.MediaKind &&
+ resumePoint.MediaItemId == data.MediaItemId)
+ ?? await _luminaDbContext.MediaResumePoints
+ .FirstOrDefaultAsync(resumePoint => resumePoint.UserId == userId &&
+ resumePoint.MediaKind == data.MediaKind &&
+ resumePoint.MediaItemId == data.MediaItemId, cancellationToken).ConfigureAwait(false);
+ if (foundResumePoint is null)
+ {
+ // The user argument is authoritative for the owner of the new row, not the owner carried by the caller.
+ data.UserId = userId;
+ _luminaDbContext.MediaResumePoints.Add(data);
+ return Result.Updated;
+ }
+
+ // A report that carries the values that are already stored is a no-op: writing it would bump the version for nothing.
+ if (!HasEditableChanges(foundResumePoint, data))
+ return Result.Updated;
+
+ // The business key is never reassigned by an upsert. The version is captured before the copy and incremented after it, so the update is only applied when the row still holds the version the report read.
+ Guid storedUserId = foundResumePoint.UserId;
+ MediaKind mediaKind = foundResumePoint.MediaKind;
+ Guid mediaItemId = foundResumePoint.MediaItemId;
+ long version = foundResumePoint.Version;
+ EditableValuesCopier.CopyEditableValues(_luminaDbContext, foundResumePoint, data);
+ foundResumePoint.UserId = storedUserId;
+ foundResumePoint.MediaKind = mediaKind;
+ foundResumePoint.MediaItemId = mediaItemId;
+ foundResumePoint.Version = version + 1;
+ return Result.Updated;
+ }
+
+ ///
+ /// Deletes the resume point of the user identified by for the media item identified by and
+ /// . A resume point that does not exist is not an error.
+ ///
+ /// The Id of the user the resume point must belong to.
+ /// The kind of the media item to resume.
+ /// The Id of the media item to resume.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful deletion, or an error.
+ public async Task> DeleteForUserAndMediaItemAsync(Guid userId, MediaKind mediaKind, Guid mediaItemId, CancellationToken cancellationToken)
+ {
+ MediaResumePointEntity? resumePoint = _luminaDbContext.MediaResumePoints.Local
+ .FirstOrDefault(trackedResumePoint => trackedResumePoint.UserId == userId &&
+ trackedResumePoint.MediaKind == mediaKind &&
+ trackedResumePoint.MediaItemId == mediaItemId)
+ ?? await _luminaDbContext.MediaResumePoints
+ .FirstOrDefaultAsync(foundResumePoint => foundResumePoint.UserId == userId &&
+ foundResumePoint.MediaKind == mediaKind &&
+ foundResumePoint.MediaItemId == mediaItemId, cancellationToken).ConfigureAwait(false);
+ if (resumePoint is null)
+ return Result.Deleted;
+
+ _luminaDbContext.MediaResumePoints.Remove(resumePoint);
+ return Result.Deleted;
+ }
+
+ ///
+ /// Deletes every resume point of the user identified by .
+ ///
+ /// The Id of the user whose resume points are deleted.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful deletion, or an error.
+ public async Task> DeleteAllForUserAsync(Guid userId, CancellationToken cancellationToken)
+ {
+ List resumePoints = await _luminaDbContext.MediaResumePoints
+ .Where(resumePoint => resumePoint.UserId == userId)
+ .ToListAsync(cancellationToken).ConfigureAwait(false);
+ if (resumePoints.Count > 0)
+ _luminaDbContext.MediaResumePoints.RemoveRange(resumePoints);
+ return Result.Deleted;
+ }
+
+ ///
+ /// Deletes every resume point of the user identified by in the media library identified by .
+ ///
+ /// The Id of the user whose resume points are deleted.
+ /// The Id of the media library whose resume points are deleted.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful deletion, or an error.
+ public async Task> DeleteAllForUserInLibraryAsync(Guid userId, Guid libraryId, CancellationToken cancellationToken)
+ {
+ List resumePoints = await _luminaDbContext.MediaResumePoints
+ .Where(resumePoint => resumePoint.UserId == userId && resumePoint.LibraryId == libraryId)
+ .ToListAsync(cancellationToken).ConfigureAwait(false);
+ if (resumePoints.Count > 0)
+ _luminaDbContext.MediaResumePoints.RemoveRange(resumePoints);
+ return Result.Deleted;
+ }
+
+ ///
+ /// Determines whether carries values that differ from the stored resume point.
+ ///
+ /// The resume point currently stored in the persistence medium.
+ /// The resume point carrying the values to apply.
+ /// if an editable value changed, otherwise.
+ private static bool HasEditableChanges(MediaResumePointEntity stored, MediaResumePointEntity incoming)
+ {
+ return stored.LibraryId != incoming.LibraryId ||
+ stored.LastPositionKind != incoming.LastPositionKind ||
+ stored.LastPositionTimeOffsetMilliseconds != incoming.LastPositionTimeOffsetMilliseconds ||
+ stored.LastPositionLocation != incoming.LastPositionLocation ||
+ stored.LastProgressFraction != incoming.LastProgressFraction ||
+ stored.LastConsumedOnUtc != incoming.LastConsumedOnUtc;
+ }
+}
diff --git a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs
index 77860b02..e30b5ecf 100644
--- a/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs
+++ b/src/Lumina.DataAccess/Core/UoW/LuminaDbContext.cs
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.Authorization;
using Lumina.Application.Common.DataAccess.Entities.Favorites;
+using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.Management;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
@@ -56,6 +57,8 @@ public class LuminaDbContext : DbContext
public virtual DbSet Playlists { get; set; } = null!;
public virtual DbSet PlaylistEntries { get; set; } = null!;
public virtual DbSet Favorites { get; set; } = null!;
+ public virtual DbSet MediaConsumptionRecords { get; set; } = null!;
+ public virtual DbSet MediaResumePoints { get; set; } = null!;
///
/// Initializes a new instance of the class.
diff --git a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs
index cf9daed8..4ba75cf1 100644
--- a/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs
+++ b/src/Lumina.DataAccess/Core/UoW/UnitOfWork.cs
@@ -2,6 +2,7 @@
using Lumina.Application.Common.DataAccess.Repositories.Authorization;
using Lumina.Application.Common.DataAccess.Repositories.BookLibrary;
using Lumina.Application.Common.DataAccess.Repositories.Favorites;
+using Lumina.Application.Common.DataAccess.Repositories.MediaConsumption;
using Lumina.Application.Common.DataAccess.Repositories.MediaContributors;
using Lumina.Application.Common.DataAccess.Repositories.MediaLibrary;
using Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
@@ -16,6 +17,7 @@ using Lumina.DataAccess.Core.Repositories.Authorization;
using Lumina.DataAccess.Core.Repositories.BookLibrary;
using Lumina.DataAccess.Core.Repositories.Favorites;
using Lumina.DataAccess.Core.Repositories.Libraries;
+using Lumina.DataAccess.Core.Repositories.MediaConsumption;
using Lumina.DataAccess.Core.Repositories.MediaContributors;
using Lumina.DataAccess.Core.Repositories.MusicLibrary;
using Lumina.DataAccess.Core.Repositories.Playlists;
@@ -71,6 +73,8 @@ public class UnitOfWork : IUnitOfWork, IDisposable
private IMusicPlayRecordRepository? _musicPlayRecordRepository;
private IPlaylistRepository? _playlistRepository;
private IFavoriteRepository? _favoriteRepository;
+ private IMediaConsumptionRecordRepository? _mediaConsumptionRecordRepository;
+ private IMediaResumePointRepository? _mediaResumePointRepository;
///
/// Gets the permission repository.
@@ -417,6 +421,30 @@ public class UnitOfWork : IUnitOfWork, IDisposable
}
}
+ ///
+ /// Gets the media consumption record repository.
+ ///
+ public IMediaConsumptionRecordRepository MediaConsumptionRecordRepository
+ {
+ get
+ {
+ _mediaConsumptionRecordRepository ??= new MediaConsumptionRecordRepository(_luminaDbContext);
+ return _mediaConsumptionRecordRepository;
+ }
+ }
+
+ ///
+ /// Gets the media resume point repository.
+ ///
+ public IMediaResumePointRepository MediaResumePointRepository
+ {
+ get
+ {
+ _mediaResumePointRepository ??= new MediaResumePointRepository(_luminaDbContext);
+ return _mediaResumePointRepository;
+ }
+ }
+
///
/// Initializes a new instance of the class.
///
diff --git a/src/Lumina.Domain/Common/Errors/Errors.MediaConsumption.cs b/src/Lumina.Domain/Common/Errors/Errors.MediaConsumption.cs
index 9c57698c..b16717dd 100644
--- a/src/Lumina.Domain/Common/Errors/Errors.MediaConsumption.cs
+++ b/src/Lumina.Domain/Common/Errors/Errors.MediaConsumption.cs
@@ -16,9 +16,12 @@ public static partial class Errors
public static Error MediaKindCannotResume => Error.Forbidden(description: nameof(MediaKindCannotResume));
public static Error ConsumptionRecordNotFound => Error.NotFound(description: nameof(ConsumptionRecordNotFound));
public static Error MediaResumePointNotFound => Error.NotFound(description: nameof(MediaResumePointNotFound));
+ public static Error ConsumptionRecordIdCannotBeEmpty => Error.Validation(description: nameof(ConsumptionRecordIdCannotBeEmpty));
+ public static Error MediaItemIdCannotBeEmpty => Error.Validation(description: nameof(MediaItemIdCannotBeEmpty));
public static Error InvalidMediaPosition => Error.Validation(description: nameof(InvalidMediaPosition));
public static Error InvalidProgressFraction => Error.Validation(description: nameof(InvalidProgressFraction));
public static Error ConsumedDurationMustBeNonNegative => Error.Validation(description: nameof(ConsumedDurationMustBeNonNegative));
+ public static Error ConsumedDurationIsOutOfRange => Error.Validation(description: nameof(ConsumedDurationIsOutOfRange));
public static Error ConsumedDurationCannotDecrease => Error.Forbidden(description: nameof(ConsumedDurationCannotDecrease));
public static Error ConsecutivePagesReadMustBeNonNegative => Error.Validation(description: nameof(ConsecutivePagesReadMustBeNonNegative));
public static Error ConsecutivePagesReadIsOnlySupportedForPageBasedMedia => Error.Forbidden(description: nameof(ConsecutivePagesReadIsOnlySupportedForPageBasedMedia));
diff --git a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs
index 6da1c5d9..e635d03c 100644
--- a/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs
+++ b/tests/IntegrationTests/Lumina.DataAccess.IntegrationTests/Core/UoW/LuminaDbContextTests.cs
@@ -48,7 +48,7 @@ public class LuminaDbContextTests : IDisposable
// Assert
// The count assertion fails when a table is added or removed, reminding to update the assertions below.
- Assert.Equal(65, tableNames.Length);
+ Assert.Equal(67, tableNames.Length);
Assert.Contains("Books", tableNames);
Assert.Contains("Users", tableNames);
Assert.Contains("UserSettings", tableNames);
@@ -109,6 +109,8 @@ public class LuminaDbContextTests : IDisposable
Assert.Contains("MusicArtwork", tableNames);
Assert.Contains("MusicLibraryScanItemMetadata", tableNames);
Assert.Contains("MusicPlayRecords", tableNames);
+ Assert.Contains("MediaConsumptionRecords", tableNames);
+ Assert.Contains("MediaResumePoints", tableNames);
Assert.Contains("Playlists", tableNames);
Assert.Contains("PlaylistEntries", tableNames);
}