Adds the media consumption lifecycle commands and repository wiring

This commit is contained in:
BinaryAlley committed 2026-10-24 17:07:31 +03:00
1 parent 2ffacb5360
commit bde7ee4b1f
30 files changed
+1962 -28

No files matched your search

@@ -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.
@@ -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>
@@ -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
);
}
}
@@ -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
);
}
}
@@ -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
);
}
}
@@ -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>
@@ -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;
@@ -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!));
}
}
@@ -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
};
}
}
@@ -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;
@@ -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);
}
}
@@ -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
};
}
}
@@ -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;
@@ -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();
}
}
@@ -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);
}
}
@@ -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;
@@ -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);
}
}
@@ -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
};
}
}