mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-01 18:57:24 +00:00
Adds the media consumption lifecycle commands and repository wiring
This commit is contained in:
1 parent
2ffacb5360
commit
bde7ee4b1f
30 files changed
+1962
-28
No files matched your search
+10
-10
@@ -20,24 +20,24 @@ public class MediaConsumptionRecordEntity : IStorageEntity, IAuditableEntity
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the user that started the consumption session.
|
||||
/// Gets or sets the Id of the user that started the consumption session.
|
||||
/// </summary>
|
||||
public required Guid UserId { get; init; }
|
||||
public required Guid UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public required Guid LibraryId { get; init; }
|
||||
public required Guid LibraryId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the kind of media that was consumed.
|
||||
/// Gets or sets the kind of media that was consumed.
|
||||
/// </summary>
|
||||
public required MediaKind MediaKind { get; init; }
|
||||
public required MediaKind MediaKind { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the consumed media item.
|
||||
/// Gets or sets the Id of the consumed media item.
|
||||
/// </summary>
|
||||
public required Guid MediaItemId { get; init; }
|
||||
public required Guid MediaItemId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the state of the consumption session.
|
||||
@@ -45,9 +45,9 @@ public class MediaConsumptionRecordEntity : IStorageEntity, IAuditableEntity
|
||||
public ConsumptionStatus Status { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the date and time when the consumption session started.
|
||||
/// Gets or sets the date and time when the consumption session started.
|
||||
/// </summary>
|
||||
public required DateTime StartedOnUtc { get; init; }
|
||||
public required DateTime StartedOnUtc { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the date and time when the consumption session last received activity.
|
||||
|
||||
+8
-8
@@ -20,24 +20,24 @@ public class MediaResumePointEntity : IStorageEntity, IAuditableEntity
|
||||
public required Guid Id { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the user that owns the resume point.
|
||||
/// Gets or sets the Id of the user that owns the resume point.
|
||||
/// </summary>
|
||||
public required Guid UserId { get; init; }
|
||||
public required Guid UserId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public required Guid LibraryId { get; init; }
|
||||
public required Guid LibraryId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the kind of media that is resumed.
|
||||
/// Gets or sets the kind of media that is resumed.
|
||||
/// </summary>
|
||||
public required MediaKind MediaKind { get; init; }
|
||||
public required MediaKind MediaKind { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the Id of the media item to resume.
|
||||
/// Gets or sets the Id of the media item to resume.
|
||||
/// </summary>
|
||||
public required Guid MediaItemId { get; init; }
|
||||
public required Guid MediaItemId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the kind of representation used by the position at which the media item can be resumed.
|
||||
|
||||
@@ -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
|
||||
/// </summary>
|
||||
IFavoriteRepository FavoriteRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media consumption record repository.
|
||||
/// </summary>
|
||||
IMediaConsumptionRecordRepository MediaConsumptionRecordRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media resume point repository.
|
||||
/// </summary>
|
||||
IMediaResumePointRepository MediaResumePointRepository { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Saves the changes made to the database.
|
||||
/// </summary>
|
||||
|
||||
+30
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="CompleteConsumptionRequest"/>.
|
||||
/// </summary>
|
||||
public static class CompleteConsumptionRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="CompleteConsumptionCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="consumptionRecordId">The Id of the consumption record, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
+31
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="ReportConsumptionProgressRequest"/>.
|
||||
/// </summary>
|
||||
public static class ReportConsumptionProgressRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="ReportConsumptionProgressCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="consumptionRecordId">The Id of the consumption record, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
+30
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="StopConsumptionRequest"/>.
|
||||
/// </summary>
|
||||
public static class StopConsumptionRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="StopConsumptionCommand"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="consumptionRecordId">The Id of the consumption record, taken from the route.</param>
|
||||
/// <returns>The converted command.</returns>
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
+13
-3
@@ -59,9 +59,7 @@ public static class LibraryEntityMapping
|
||||
if (pathTemplateResult.IsFailure)
|
||||
return pathTemplateResult.Errors;
|
||||
|
||||
LibraryConsumptionSettings consumptionSettings = LibraryConsumptionSettings.Create(
|
||||
repositoryEntity.ShouldTrackConsumptionProgress,
|
||||
Optional<int>.FromNullable(repositoryEntity.CompletionThresholdPercentage));
|
||||
LibraryConsumptionSettings consumptionSettings = repositoryEntity.ToDomainValueObject();
|
||||
|
||||
return Library.Create(
|
||||
LibraryId.Create(repositoryEntity.Id),
|
||||
@@ -81,6 +79,18 @@ public static class LibraryEntityMapping
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts the consumption settings stored on <paramref name="repositoryEntity"/> to <see cref="LibraryConsumptionSettings"/>.
|
||||
/// </summary>
|
||||
/// <param name="repositoryEntity">The repository entity whose consumption settings are converted.</param>
|
||||
/// <returns>The converted consumption settings.</returns>
|
||||
public static LibraryConsumptionSettings ToDomainValueObject(this LibraryEntity repositoryEntity)
|
||||
{
|
||||
return LibraryConsumptionSettings.Create(
|
||||
repositoryEntity.ShouldTrackConsumptionProgress,
|
||||
Optional<int>.FromNullable(repositoryEntity.CompletionThresholdPercentage));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the path template of a media library from its ordered stored parts.
|
||||
/// </summary>
|
||||
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaConsumption.Commands.CompleteConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Command for reporting that a consumption session of the current user completed.
|
||||
/// </summary>
|
||||
/// <param name="ConsumptionRecordId">The unique identifier of the consumption record, taken from the route.</param>
|
||||
/// <param name="PositionKind">The name of the kind of the final position reached in the media item, if the client reported one.</param>
|
||||
/// <param name="PositionTimeOffsetInSeconds">The final position within the media item, in seconds, when the position is a time offset.</param>
|
||||
/// <param name="PositionLocation">The final opaque locator within the media item, when the position is not a time offset.</param>
|
||||
/// <param name="ProgressFraction">The final fraction of the media item that the client reached, between 0 and 1.</param>
|
||||
/// <param name="ConsumedDurationInSeconds">The active duration consumed by the session, in seconds.</param>
|
||||
[DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}; ProgressFraction: {ProgressFraction}")]
|
||||
public record CompleteConsumptionCommand(
|
||||
string? ConsumptionRecordId,
|
||||
string? PositionKind,
|
||||
double? PositionTimeOffsetInSeconds,
|
||||
string? PositionLocation,
|
||||
double? ProgressFraction,
|
||||
double? ConsumedDurationInSeconds
|
||||
) : ICommand;
|
||||
+146
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to report that a consumption session of the current user completed.
|
||||
/// </summary>
|
||||
public class CompleteConsumptionCommandHandler : ICommandHandler<CompleteConsumptionCommand, Result<ConsumptionRecordResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<CompleteConsumptionCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CompleteConsumptionCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public CompleteConsumptionCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<CompleteConsumptionCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to report that a consumption session of the current user completed.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the completed <see cref="ConsumptionRecordResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<ConsumptionRecordResponse>> HandleAsync(CompleteConsumptionCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> 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<MediaConsumptionRecordEntity?> 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<MediaConsumptionRecord> toDomainEntityResult = getRecordResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
MediaConsumptionRecord record = toDomainEntityResult.Value;
|
||||
|
||||
Optional<MediaPosition> position = ToMediaPosition(command.PositionKind, command.PositionTimeOffsetInSeconds, command.PositionLocation);
|
||||
|
||||
Result<Updated> 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<Deleted> deleteResumePointResult = await _unitOfWork.MediaResumePointRepository
|
||||
.DeleteForUserAndMediaItemAsync(userId, record.MediaKind, record.MediaItemId.Value, cancellationToken).ConfigureAwait(false);
|
||||
if (deleteResumePointResult.IsFailure)
|
||||
return deleteResumePointResult.Errors;
|
||||
|
||||
Result<Updated> updateResult = await _unitOfWork.MediaConsumptionRecordRepository.UpdateForUserAsync(record.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false);
|
||||
if (updateResult.IsFailure)
|
||||
return updateResult.Errors;
|
||||
|
||||
Result<Success> 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<MediaConsumptionRecordEntity?> 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts reported position fields that have already been validated to a <see cref="MediaPosition"/>.
|
||||
/// </summary>
|
||||
/// <param name="positionKind">The name of the kind of the reported position, or <see langword="null"/> when no position was reported.</param>
|
||||
/// <param name="timeOffsetInSeconds">The reported position within the media item, in seconds, when the position is a time offset.</param>
|
||||
/// <param name="location">The reported opaque locator within the media item, when the position is not a time offset.</param>
|
||||
/// <returns>The converted position, or no position when the client did not report one.</returns>
|
||||
private static Optional<MediaPosition> 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<MediaPosition>.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<MediaPositionKind>(positionKind, ignoreCase: true);
|
||||
// The kind names the single representation that the validator accepted, so only that representation is read.
|
||||
return parsedPositionKind == MediaPositionKind.TimeOffset
|
||||
? Optional<MediaPosition>.Some(MediaPosition.CreateTimeOffset(TimeSpan.FromSeconds(timeOffsetInSeconds!.Value)))
|
||||
: Optional<MediaPosition>.Some(MediaPosition.CreateLocation(location!));
|
||||
}
|
||||
}
|
||||
+92
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="CompleteConsumptionCommand"/>.
|
||||
/// </summary>
|
||||
public class CompleteConsumptionCommandValidator : AbstractValidator<CompleteConsumptionCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CompleteConsumptionCommandValidator"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the reported position fields describe exactly one valid position.
|
||||
/// </summary>
|
||||
/// <param name="positionKind">The name of the kind of the reported position, or <see langword="null"/> when no position was reported.</param>
|
||||
/// <param name="timeOffsetInSeconds">The reported position within the media item, in seconds, when the position is a time offset.</param>
|
||||
/// <param name="location">The reported opaque locator within the media item, when the position is not a time offset.</param>
|
||||
/// <returns><see langword="true"/> if the position fields are valid, <see langword="false"/> otherwise.</returns>
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaConsumption.Commands.ReportConsumptionProgress;
|
||||
|
||||
/// <summary>
|
||||
/// Command for reporting the progress of a consumption session of the current user.
|
||||
/// </summary>
|
||||
/// <param name="ConsumptionRecordId">The unique identifier of the consumption record, taken from the route.</param>
|
||||
/// <param name="PositionKind">The name of the kind of the position reached in the media item, if the client reported one.</param>
|
||||
/// <param name="PositionTimeOffsetInSeconds">The position within the media item, in seconds, when the position is a time offset.</param>
|
||||
/// <param name="PositionLocation">The opaque locator within the media item, when the position is not a time offset.</param>
|
||||
/// <param name="ProgressFraction">The fraction of the media item that the client reached, between 0 and 1.</param>
|
||||
/// <param name="ConsumedDurationInSeconds">The active duration consumed by the session, in seconds.</param>
|
||||
/// <param name="ConsecutivePagesRead">The number of consecutive pages read in the current session, used by page based media such as books.</param>
|
||||
[DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}; ProgressFraction: {ProgressFraction}")]
|
||||
public record ReportConsumptionProgressCommand(
|
||||
string? ConsumptionRecordId,
|
||||
string? PositionKind,
|
||||
double? PositionTimeOffsetInSeconds,
|
||||
string? PositionLocation,
|
||||
double? ProgressFraction,
|
||||
double? ConsumedDurationInSeconds,
|
||||
int ConsecutivePagesRead
|
||||
) : ICommand;
|
||||
+218
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to report the progress of a consumption session of the current user.
|
||||
/// </summary>
|
||||
public class ReportConsumptionProgressCommandHandler : ICommandHandler<ReportConsumptionProgressCommand, Result<ConsumptionRecordResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<ReportConsumptionProgressCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReportConsumptionProgressCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public ReportConsumptionProgressCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<ReportConsumptionProgressCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to report the progress of a consumption session of the current user.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the updated <see cref="ConsumptionRecordResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<ConsumptionRecordResponse>> HandleAsync(ReportConsumptionProgressCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> 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<MediaConsumptionRecordEntity?> 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<MediaConsumptionRecord> 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<LibraryEntity?> 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<MediaPosition> 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<Updated> reportProgressResult = record.ReportProgress(position, command.ProgressFraction!.Value, TimeSpan.FromSeconds(command.ConsumedDurationInSeconds!.Value), command.ConsecutivePagesRead);
|
||||
if (reportProgressResult.IsFailure)
|
||||
return reportProgressResult.Errors;
|
||||
|
||||
Optional<MediaConsumptionRule> 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<MediaPosition> resumePosition = position.HasValue ? position : record.LastPosition;
|
||||
if (resumePosition.HasValue)
|
||||
{
|
||||
Result<Updated> upsertResumePointResult = await UpsertResumePointAsync(record, resumePosition.Value, record.LastProgressFraction, userId, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResumePointResult.IsFailure)
|
||||
return upsertResumePointResult.Errors;
|
||||
}
|
||||
}
|
||||
|
||||
Result<Updated> updateResult = await _unitOfWork.MediaConsumptionRecordRepository.UpdateForUserAsync(record.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false);
|
||||
if (updateResult.IsFailure)
|
||||
return updateResult.Errors;
|
||||
|
||||
Result<Success> 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<MediaConsumptionRecordEntity?> 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts reported position fields that have already been validated to a <see cref="MediaPosition"/>.
|
||||
/// </summary>
|
||||
/// <param name="positionKind">The name of the kind of the reported position, or <see langword="null"/> when no position was reported.</param>
|
||||
/// <param name="timeOffsetInSeconds">The reported position within the media item, in seconds, when the position is a time offset.</param>
|
||||
/// <param name="location">The reported opaque locator within the media item, when the position is not a time offset.</param>
|
||||
/// <returns>The converted position, or no position when the client did not report one.</returns>
|
||||
private static Optional<MediaPosition> 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<MediaPosition>.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<MediaPositionKind>(positionKind, ignoreCase: true);
|
||||
// The kind names the single representation that the validator accepted, so only that representation is read.
|
||||
return parsedPositionKind == MediaPositionKind.TimeOffset
|
||||
? Optional<MediaPosition>.Some(MediaPosition.CreateTimeOffset(TimeSpan.FromSeconds(timeOffsetInSeconds!.Value)))
|
||||
: Optional<MediaPosition>.Some(MediaPosition.CreateLocation(location!));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates or updates the resume point of <paramref name="record"/> for the current user.
|
||||
/// </summary>
|
||||
/// <param name="record">The consumption record whose session is being tracked.</param>
|
||||
/// <param name="position">The position at which the media item can be resumed.</param>
|
||||
/// <param name="progressFraction">The progress fraction at which the media item can be resumed.</param>
|
||||
/// <param name="userId">The Id of the user the resume point belongs to.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful save, or an error message.</returns>
|
||||
private async Task<Result<Updated>> 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<MediaResumePointEntity?> 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<MediaResumePoint> 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<MediaResumePoint> toDomainEntityResult = getResumePointResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
Result<Updated> 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);
|
||||
}
|
||||
}
|
||||
+96
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="ReportConsumptionProgressCommand"/>.
|
||||
/// </summary>
|
||||
public class ReportConsumptionProgressCommandValidator : AbstractValidator<ReportConsumptionProgressCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="ReportConsumptionProgressCommandValidator"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the reported position fields describe exactly one valid position.
|
||||
/// </summary>
|
||||
/// <param name="positionKind">The name of the kind of the reported position, or <see langword="null"/> when no position was reported.</param>
|
||||
/// <param name="timeOffsetInSeconds">The reported position within the media item, in seconds, when the position is a time offset.</param>
|
||||
/// <param name="location">The reported opaque locator within the media item, when the position is not a time offset.</param>
|
||||
/// <returns><see langword="true"/> if the position fields are valid, <see langword="false"/> otherwise.</returns>
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaConsumption.Commands.StartConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Command for starting a consumption session of a media item by the current user.
|
||||
/// </summary>
|
||||
/// <param name="LibraryId">The unique identifier of the media library that contains the media item, taken from the route.</param>
|
||||
/// <param name="MediaKind">The kind of media that is consumed, taken from the route.</param>
|
||||
/// <param name="MediaItemId">The unique identifier of the consumed media item, taken from the route.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public record StartConsumptionCommand(
|
||||
string? LibraryId,
|
||||
string? MediaKind,
|
||||
string? MediaItemId
|
||||
) : ICommand;
|
||||
+189
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to start a consumption session of a media item by the current user.
|
||||
/// </summary>
|
||||
public class StartConsumptionCommandHandler : ICommandHandler<StartConsumptionCommand, Result<ConsumptionRecordResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<StartConsumptionCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StartConsumptionCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public StartConsumptionCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IAuthorizationService authorizationService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<StartConsumptionCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to start a consumption session of a media item by the current user.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the created <see cref="ConsumptionRecordResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<ConsumptionRecordResponse>> HandleAsync(StartConsumptionCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> 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<MediaKind>(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<ILibraryOwnershipPolicy>(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<MediaConsumptionRule> 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<LibraryEntity?> 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<TrackEntity?> 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<BookEntity?> 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<MediaPosition> initialPosition = Optional<MediaPosition>.None();
|
||||
double initialProgressFraction = 0;
|
||||
if (consumptionSettings.ShouldTrackConsumptionProgress && rule.CanResume)
|
||||
{
|
||||
Result<MediaResumePointEntity?> 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<MediaResumePoint> toDomainEntityResult = getResumePointResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
initialPosition = Optional<MediaPosition>.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<MediaConsumptionRecord> 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<Created> insertResult = await _unitOfWork.MediaConsumptionRecordRepository.InsertAsync(record.ToRepositoryEntity(), cancellationToken).ConfigureAwait(false);
|
||||
if (insertResult.IsFailure)
|
||||
return insertResult.Errors;
|
||||
|
||||
Result<Success> 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<MediaConsumptionRecordEntity?> 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();
|
||||
}
|
||||
}
|
||||
+51
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="StartConsumptionCommand"/>.
|
||||
/// </summary>
|
||||
public class StartConsumptionCommandValidator : AbstractValidator<StartConsumptionCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StartConsumptionCommandValidator"/> class.
|
||||
/// </summary>
|
||||
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>(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);
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaConsumption.Commands.StopConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Command for reporting that a consumption session of the current user stopped before it completed.
|
||||
/// </summary>
|
||||
/// <param name="ConsumptionRecordId">The unique identifier of the consumption record, taken from the route.</param>
|
||||
/// <param name="PositionKind">The name of the kind of the final position reached in the media item, if the client reported one.</param>
|
||||
/// <param name="PositionTimeOffsetInSeconds">The final position within the media item, in seconds, when the position is a time offset.</param>
|
||||
/// <param name="PositionLocation">The final opaque locator within the media item, when the position is not a time offset.</param>
|
||||
/// <param name="ProgressFraction">The final fraction of the media item that the client reached, between 0 and 1.</param>
|
||||
/// <param name="ConsumedDurationInSeconds">The active duration consumed by the session, in seconds.</param>
|
||||
[DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}; ProgressFraction: {ProgressFraction}")]
|
||||
public record StopConsumptionCommand(
|
||||
string? ConsumptionRecordId,
|
||||
string? PositionKind,
|
||||
double? PositionTimeOffsetInSeconds,
|
||||
string? PositionLocation,
|
||||
double? ProgressFraction,
|
||||
double? ConsumedDurationInSeconds
|
||||
) : ICommand;
|
||||
+230
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to report that a consumption session of the current user stopped before it completed.
|
||||
/// </summary>
|
||||
public class StopConsumptionCommandHandler : ICommandHandler<StopConsumptionCommand, Result<ConsumptionRecordResponse>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IDomainEventsQueue _domainEventsQueue;
|
||||
private readonly IValidator<StopConsumptionCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StopConsumptionCommandHandler"/> class.
|
||||
/// </summary>
|
||||
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
|
||||
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
|
||||
/// <param name="domainEventsQueue">Injected service for the queue of domain events.</param>
|
||||
/// <param name="validator">Injected validator for application validation rules.</param>
|
||||
public StopConsumptionCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IDomainEventsQueue domainEventsQueue,
|
||||
IValidator<StopConsumptionCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_domainEventsQueue = domainEventsQueue;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to report that a consumption session of the current user stopped before it completed.
|
||||
/// </summary>
|
||||
/// <param name="command">The command to be handled.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the stopped or completed <see cref="ConsumptionRecordResponse"/>, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<ConsumptionRecordResponse>> HandleAsync(StopConsumptionCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
List<Error> 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<MediaConsumptionRecordEntity?> 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<MediaConsumptionRecord> 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<LibraryEntity?> 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<MediaPosition> 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<Updated> terminalResult = isAtCompletionThreshold
|
||||
? record.Complete(position, progressFraction, consumedDuration)
|
||||
: record.Stop(position, progressFraction, consumedDuration);
|
||||
if (terminalResult.IsFailure)
|
||||
return terminalResult.Errors;
|
||||
|
||||
Optional<MediaConsumptionRule> 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<Deleted> 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<Updated> upsertResumePointResult = await UpsertResumePointAsync(record, record.LastPosition.Value, record.LastProgressFraction, userId, cancellationToken).ConfigureAwait(false);
|
||||
if (upsertResumePointResult.IsFailure)
|
||||
return upsertResumePointResult.Errors;
|
||||
}
|
||||
|
||||
Result<Updated> updateResult = await _unitOfWork.MediaConsumptionRecordRepository.UpdateForUserAsync(record.ToRepositoryEntity(), userId, cancellationToken).ConfigureAwait(false);
|
||||
if (updateResult.IsFailure)
|
||||
return updateResult.Errors;
|
||||
|
||||
Result<Success> 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<MediaConsumptionRecordEntity?> 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts reported position fields that have already been validated to a <see cref="MediaPosition"/>.
|
||||
/// </summary>
|
||||
/// <param name="positionKind">The name of the kind of the reported position, or <see langword="null"/> when no position was reported.</param>
|
||||
/// <param name="timeOffsetInSeconds">The reported position within the media item, in seconds, when the position is a time offset.</param>
|
||||
/// <param name="location">The reported opaque locator within the media item, when the position is not a time offset.</param>
|
||||
/// <returns>The converted position, or no position when the client did not report one.</returns>
|
||||
private static Optional<MediaPosition> 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<MediaPosition>.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<MediaPositionKind>(positionKind, ignoreCase: true);
|
||||
// The kind names the single representation that the validator accepted, so only that representation is read.
|
||||
return parsedPositionKind == MediaPositionKind.TimeOffset
|
||||
? Optional<MediaPosition>.Some(MediaPosition.CreateTimeOffset(TimeSpan.FromSeconds(timeOffsetInSeconds!.Value)))
|
||||
: Optional<MediaPosition>.Some(MediaPosition.CreateLocation(location!));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates or updates the resume point of <paramref name="record"/> for the current user.
|
||||
/// </summary>
|
||||
/// <param name="record">The consumption record whose session is being tracked.</param>
|
||||
/// <param name="position">The position at which the media item can be resumed.</param>
|
||||
/// <param name="progressFraction">The progress fraction at which the media item can be resumed.</param>
|
||||
/// <param name="userId">The Id of the user the resume point belongs to.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful save, or an error message.</returns>
|
||||
private async Task<Result<Updated>> 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<MediaResumePointEntity?> 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<MediaResumePoint> 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<MediaResumePoint> toDomainEntityResult = getResumePointResult.Value.ToDomainEntity();
|
||||
if (toDomainEntityResult.IsFailure)
|
||||
return toDomainEntityResult.Errors;
|
||||
Result<Updated> 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);
|
||||
}
|
||||
}
|
||||
+92
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="StopConsumptionCommand"/>.
|
||||
/// </summary>
|
||||
public class StopConsumptionCommandValidator : AbstractValidator<StopConsumptionCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="StopConsumptionCommandValidator"/> class.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether the reported position fields describe exactly one valid position.
|
||||
/// </summary>
|
||||
/// <param name="positionKind">The name of the kind of the reported position, or <see langword="null"/> when no position was reported.</param>
|
||||
/// <param name="timeOffsetInSeconds">The reported position within the media item, in seconds, when the position is a time offset.</param>
|
||||
/// <param name="location">The reported opaque locator within the media item, when the position is not a time offset.</param>
|
||||
/// <returns><see langword="true"/> if the position fields are valid, <see langword="false"/> otherwise.</returns>
|
||||
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
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
);
|
||||
@@ -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
|
||||
);
|
||||
@@ -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
|
||||
);
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="MediaConsumptionRecordEntity"/> entity.
|
||||
/// </summary>
|
||||
public class MediaConsumptionRecordConfiguration : IEntityTypeConfiguration<MediaConsumptionRecordEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="MediaConsumptionRecordEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<MediaConsumptionRecordEntity> 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<UserEntity>()
|
||||
.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<string>()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnOrder(4);
|
||||
|
||||
builder.Property(record => record.Status)
|
||||
.IsRequired()
|
||||
.HasConversion<string>()
|
||||
.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<string>()
|
||||
.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 });
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Configures the entity mapping for the <see cref="MediaResumePointEntity"/> entity.
|
||||
/// </summary>
|
||||
public class MediaResumePointConfiguration : IEntityTypeConfiguration<MediaResumePointEntity>
|
||||
{
|
||||
/// <summary>
|
||||
/// Configures the <see cref="MediaResumePointEntity"/> entity.
|
||||
/// </summary>
|
||||
/// <param name="builder">The builder to be used to configure the entity.</param>
|
||||
public void Configure(EntityTypeBuilder<MediaResumePointEntity> 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<UserEntity>()
|
||||
.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<string>()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnOrder(3);
|
||||
|
||||
builder.Property(resumePoint => resumePoint.MediaItemId)
|
||||
.IsRequired()
|
||||
.HasColumnOrder(4);
|
||||
|
||||
builder.Property(resumePoint => resumePoint.LastPositionKind)
|
||||
.IsRequired()
|
||||
.HasConversion<string>()
|
||||
.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();
|
||||
}
|
||||
}
|
||||
+167
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Repository for media consumption records.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
internal sealed class MediaConsumptionRecordRepository : IMediaConsumptionRecordRepository
|
||||
{
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaConsumptionRecordRepository"/> class.
|
||||
/// </summary>
|
||||
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
|
||||
public MediaConsumptionRecordRepository(LuminaDbContext luminaDbContext)
|
||||
{
|
||||
_luminaDbContext = luminaDbContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a new consumption record.
|
||||
/// </summary>
|
||||
/// <param name="data">The consumption record to add.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful operation, or an error.</returns>
|
||||
public Task<Result<Created>> 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>>(Result.Created);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the consumption record identified by <paramref name="id"/> when it belongs to the user identified by <paramref name="userId"/>, if it exists.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the consumption record to get.</param>
|
||||
/// <param name="userId">The Id of the user the consumption record must belong to.</param>
|
||||
/// <param name="shouldTrackEntities">Whether the retrieved record should be tracked by the persistence medium, so that changes to it can be saved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the consumption record identified by <paramref name="id"/> and owned by
|
||||
/// <paramref name="userId"/>, <see langword="null"/> when no such record exists, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<MediaConsumptionRecordEntity?>> 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<MediaConsumptionRecordEntity> query = _luminaDbContext.MediaConsumptionRecords
|
||||
.Where(record => record.Id == id && record.UserId == userId);
|
||||
if (!shouldTrackEntities)
|
||||
query = query.AsNoTracking();
|
||||
return await query.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Updates the consumption record of the user identified by <paramref name="userId"/>, when the record belongs to that user and still holds the version it was read with.
|
||||
/// </summary>
|
||||
/// <param name="data">The consumption record whose editable values are applied to the stored record. Its owner must match <paramref name="userId"/>.</param>
|
||||
/// <param name="userId">The Id of the user the consumption record must belong to. It is authoritative for locating the stored record; the owner carried by <paramref name="data"/> is not used to select it.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful update, or an error.</returns>
|
||||
public async Task<Result<Updated>> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the consumption record identified by <paramref name="id"/> when it belongs to the user identified by <paramref name="userId"/>. A record that does not exist is not an error.
|
||||
/// </summary>
|
||||
/// <param name="id">The Id of the consumption record to delete.</param>
|
||||
/// <param name="userId">The Id of the user the consumption record must belong to.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful deletion, or an error.</returns>
|
||||
public async Task<Result<Deleted>> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes every consumption record of the user identified by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose consumption records are deleted.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful deletion, or an error.</returns>
|
||||
public async Task<Result<Deleted>> DeleteAllForUserAsync(Guid userId, CancellationToken cancellationToken)
|
||||
{
|
||||
List<MediaConsumptionRecordEntity> records = await _luminaDbContext.MediaConsumptionRecords
|
||||
.Where(record => record.UserId == userId)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (records.Count > 0)
|
||||
_luminaDbContext.MediaConsumptionRecords.RemoveRange(records);
|
||||
return Result.Deleted;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether <paramref name="incoming"/> carries values that differ from the stored <paramref name="stored"/> record.
|
||||
/// </summary>
|
||||
/// <param name="stored">The record currently stored in the persistence medium.</param>
|
||||
/// <param name="incoming">The record carrying the values to apply.</param>
|
||||
/// <returns><see langword="true"/> if an editable value changed, <see langword="false"/> otherwise.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
+179
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Repository for media resume points.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
internal sealed class MediaResumePointRepository : IMediaResumePointRepository
|
||||
{
|
||||
private readonly LuminaDbContext _luminaDbContext;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaResumePointRepository"/> class.
|
||||
/// </summary>
|
||||
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
|
||||
public MediaResumePointRepository(LuminaDbContext luminaDbContext)
|
||||
{
|
||||
_luminaDbContext = luminaDbContext;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the resume point of the user identified by <paramref name="userId"/> for the media item identified by <paramref name="mediaKind"/> and <paramref name="mediaItemId"/>, if it exists.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user the resume point must belong to.</param>
|
||||
/// <param name="mediaKind">The kind of the media item to resume.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <param name="shouldTrackEntities">Whether the retrieved resume point should be tracked by the persistence medium, so that changes to it can be saved.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>
|
||||
/// An <see cref="Result{TValue}"/> containing either the resume point of the user for the media item, <see langword="null"/> when no such resume point exists, or an error.
|
||||
/// </returns>
|
||||
public async Task<Result<MediaResumePointEntity?>> 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<MediaResumePointEntity> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Saves the resume point of the user identified by <paramref name="userId"/>, 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.
|
||||
/// </summary>
|
||||
/// <param name="data">The resume point whose values are saved. Its owner must match <paramref name="userId"/>.</param>
|
||||
/// <param name="userId">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 <paramref name="data"/> is not used to select it.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful save, or an error.</returns>
|
||||
public async Task<Result<Updated>> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the resume point of the user identified by <paramref name="userId"/> for the media item identified by <paramref name="mediaKind"/> and
|
||||
/// <paramref name="mediaItemId"/>. A resume point that does not exist is not an error.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user the resume point must belong to.</param>
|
||||
/// <param name="mediaKind">The kind of the media item to resume.</param>
|
||||
/// <param name="mediaItemId">The Id of the media item to resume.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful deletion, or an error.</returns>
|
||||
public async Task<Result<Deleted>> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes every resume point of the user identified by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose resume points are deleted.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful deletion, or an error.</returns>
|
||||
public async Task<Result<Deleted>> DeleteAllForUserAsync(Guid userId, CancellationToken cancellationToken)
|
||||
{
|
||||
List<MediaResumePointEntity> resumePoints = await _luminaDbContext.MediaResumePoints
|
||||
.Where(resumePoint => resumePoint.UserId == userId)
|
||||
.ToListAsync(cancellationToken).ConfigureAwait(false);
|
||||
if (resumePoints.Count > 0)
|
||||
_luminaDbContext.MediaResumePoints.RemoveRange(resumePoints);
|
||||
return Result.Deleted;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes every resume point of the user identified by <paramref name="userId"/> in the media library identified by <paramref name="libraryId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose resume points are deleted.</param>
|
||||
/// <param name="libraryId">The Id of the media library whose resume points are deleted.</param>
|
||||
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful deletion, or an error.</returns>
|
||||
public async Task<Result<Deleted>> DeleteAllForUserInLibraryAsync(Guid userId, Guid libraryId, CancellationToken cancellationToken)
|
||||
{
|
||||
List<MediaResumePointEntity> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Determines whether <paramref name="incoming"/> carries values that differ from the stored <paramref name="stored"/> resume point.
|
||||
/// </summary>
|
||||
/// <param name="stored">The resume point currently stored in the persistence medium.</param>
|
||||
/// <param name="incoming">The resume point carrying the values to apply.</param>
|
||||
/// <returns><see langword="true"/> if an editable value changed, <see langword="false"/> otherwise.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<PlaylistEntity> Playlists { get; set; } = null!;
|
||||
public virtual DbSet<PlaylistEntryEntity> PlaylistEntries { get; set; } = null!;
|
||||
public virtual DbSet<FavoriteEntity> Favorites { get; set; } = null!;
|
||||
public virtual DbSet<MediaConsumptionRecordEntity> MediaConsumptionRecords { get; set; } = null!;
|
||||
public virtual DbSet<MediaResumePointEntity> MediaResumePoints { get; set; } = null!;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="LuminaDbContext"/> class.
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Gets the permission repository.
|
||||
@@ -417,6 +421,30 @@ public class UnitOfWork : IUnitOfWork, IDisposable
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media consumption record repository.
|
||||
/// </summary>
|
||||
public IMediaConsumptionRecordRepository MediaConsumptionRecordRepository
|
||||
{
|
||||
get
|
||||
{
|
||||
_mediaConsumptionRecordRepository ??= new MediaConsumptionRecordRepository(_luminaDbContext);
|
||||
return _mediaConsumptionRecordRepository;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets the media resume point repository.
|
||||
/// </summary>
|
||||
public IMediaResumePointRepository MediaResumePointRepository
|
||||
{
|
||||
get
|
||||
{
|
||||
_mediaResumePointRepository ??= new MediaResumePointRepository(_luminaDbContext);
|
||||
return _mediaResumePointRepository;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="UnitOfWork"/> class.
|
||||
/// </summary>
|
||||
|
||||
@@ -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));
|
||||
|
||||
+3
-1
@@ -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);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user