Adds the media consumption history, statistics, resume, and deletion queries

This commit is contained in:
BinaryAlley committed 2026-10-24 18:48:48 +03:00
1 parent bde7ee4b1f
commit f777af07cf
61 files changed
+2833 -35

No files matched your search

@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DTO.MediaConsumption;
/// <summary>
/// Data transfer object for the consumption statistics of every user, together with their combined totals.
/// </summary>
/// <param name="Total">The combined consumption statistics of every user.</param>
/// <param name="Users">The consumption statistics of each user.</param>
[DebuggerDisplay("UserCount: {Users.Count}; CountedSessionCount: {Total.CountedSessionCount}")]
public sealed record AllUsersConsumptionStatisticsDto(
ConsumptionTotalsDto Total,
IReadOnlyList<ConsumptionStatisticsDto> Users
);
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DTO.MediaConsumption;
/// <summary>
/// Data transfer object for the combined consumption statistics of every user.
/// </summary>
/// <param name="TotalConsumedDurationMilliseconds">The total duration consumed over every recorded session of every user, in milliseconds.</param>
/// <param name="CountedSessionCount">The number of recorded sessions of every user that count towards statistics.</param>
/// <param name="CompletedSessionCount">The number of recorded sessions of every user that completed.</param>
/// <param name="StoppedSessionCount">The number of recorded sessions of every user that stopped before they completed and count towards statistics.</param>
/// <param name="CompletionRate">The fraction of the counted sessions of every user that completed, between 0 and 1, or 0 when there is no counted session.</param>
/// <param name="MediaKindSummaries">The combined consumption statistics broken down by media kind.</param>
[DebuggerDisplay("CountedSessionCount: {CountedSessionCount}; CompletedSessionCount: {CompletedSessionCount}")]
public sealed record ConsumptionTotalsDto(
long TotalConsumedDurationMilliseconds,
int CountedSessionCount,
int CompletedSessionCount,
int StoppedSessionCount,
double CompletionRate,
IReadOnlyList<MediaKindConsumptionStatisticsDto> MediaKindSummaries
);
@@ -124,6 +124,15 @@ public interface IBookRepository : IRepository<BookEntity>,
/// <returns>An <see cref="Result{TValue}"/> containing either the display names of the authors of the books, keyed by book Id, or an error.</returns>
Task<Result<IReadOnlyDictionary<Guid, string?>>> GetAuthorsDisplayNamesByBookIdsAsync(IReadOnlyCollection<Guid> bookIds, CancellationToken cancellationToken);
/// <summary>
/// Gets the books identified by <paramref name="bookIds"/>, optionally together with their navigation properties.
/// </summary>
/// <param name="bookIds">The Ids of the books to get.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the books should be loaded together with the books themselves.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the existing books, or an error.</returns>
Task<Result<IReadOnlyList<BookEntity>>> GetByIdsAsync(IReadOnlyCollection<Guid> bookIds, bool shouldIncludeNavigationProperties, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the books of the media library identified by <paramref name="libraryId"/>, together with their artwork and their related data.
/// </summary>
@@ -27,6 +27,15 @@ public interface IMusicArtworkRepository : IRepository<MusicArtworkEntity>,
/// <returns>An <see cref="Result{TValue}"/> containing either a collection of <see cref="MusicArtworkEntity"/>, or an error.</returns>
Task<Result<IReadOnlyList<MusicArtworkEntity>>> GetByOwnerAsync(MusicArtworkOwnerType ownerType, Guid ownerId, CancellationToken cancellationToken);
/// <summary>
/// Gets the pieces of artwork owned by the music library items of the provided <paramref name="ownerType"/> identified by any of <paramref name="ownerIds"/>.
/// </summary>
/// <param name="ownerType">The type of the music library items that own the artwork.</param>
/// <param name="ownerIds">The Ids of the music library items that own the artwork.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the artwork of the existing owners, or an error.</returns>
Task<Result<IReadOnlyList<MusicArtworkEntity>>> GetByOwnersAsync(MusicArtworkOwnerType ownerType, IReadOnlyCollection<Guid> ownerIds, CancellationToken cancellationToken);
/// <summary>
/// Deletes all the pieces of artwork owned by the music library item of the provided <paramref name="ownerType"/> identified by <paramref name="ownerId"/>.
/// </summary>
@@ -137,4 +137,13 @@ public interface ITrackRepository : IRepository<TrackEntity>,
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the access summary of the existing tracks, or an error.</returns>
Task<Result<TrackAccessSummaryDto>> GetAccessInfoByIdsAsync(IReadOnlyCollection<Guid> trackIds, CancellationToken cancellationToken);
/// <summary>
/// Gets the tracks identified by <paramref name="trackIds"/>, optionally together with their navigation properties.
/// </summary>
/// <param name="trackIds">The Ids of the tracks to get.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the tracks should be loaded together with the tracks themselves.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the existing tracks, or an error.</returns>
Task<Result<IReadOnlyList<TrackEntity>>> GetByIdsAsync(IReadOnlyCollection<Guid> trackIds, bool shouldIncludeNavigationProperties, CancellationToken cancellationToken);
}
@@ -178,6 +178,11 @@ public interface IUnitOfWork
/// </summary>
IMediaResumePointRepository MediaResumePointRepository { get; }
/// <summary>
/// Gets the repository for the consumption records used to build consumption statistics.
/// </summary>
IConsumptionStatisticsRepository ConsumptionStatisticsRepository { get; }
/// <summary>
/// Saves the changes made to the database.
/// </summary>
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Contracts.Responses.MediaConsumption;
using System.Linq;
#endregion
namespace Lumina.Application.Common.Mapping.MediaConsumption;
/// <summary>
/// Extension methods for converting <see cref="AllUsersConsumptionStatisticsDto"/>.
/// </summary>
public static class AllUsersConsumptionStatisticsDtoMapping
{
/// <summary>
/// Converts <paramref name="data"/> to <see cref="AllUsersConsumptionStatisticsResponse"/>.
/// </summary>
/// <param name="data">The data transfer object to be converted.</param>
/// <returns>The converted response.</returns>
public static AllUsersConsumptionStatisticsResponse ToResponse(this AllUsersConsumptionStatisticsDto data)
{
return new AllUsersConsumptionStatisticsResponse(
data.Total.ToResponse(),
[.. data.Users.Select(user => user.ToResponse())]
);
}
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaConsumption;
using System;
@@ -33,7 +34,7 @@ public static class ConsumedItemDtoMapping
DateTime.SpecifyKind(data.LastConsumedOnUtc, DateTimeKind.Utc),
data.CountedSessionCount,
data.CompletedSessionCount,
TimeSpan.FromMilliseconds(data.ConsumedDurationMilliseconds).TotalSeconds
data.ConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds
);
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.MediaConsumption;
using System;
#endregion
@@ -28,7 +29,7 @@ public static class ConsumptionRecordDtoMapping
DateTime.SpecifyKind(data.StartedOnUtc, DateTimeKind.Utc),
DateTime.SpecifyKind(data.LastActivityOnUtc, DateTimeKind.Utc),
data.EndedOnUtc.HasValue ? DateTime.SpecifyKind(data.EndedOnUtc.Value, DateTimeKind.Utc) : null,
TimeSpan.FromMilliseconds(data.ConsumedDurationMilliseconds).TotalSeconds,
data.ConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds,
data.LastPosition?.ToResponse(),
data.LastProgressFraction,
data.ConsecutivePagesRead
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.MediaConsumption;
using System;
using System.Linq;
#endregion
@@ -21,7 +21,7 @@ public static class ConsumptionStatisticsDtoMapping
{
return new ConsumptionSummaryResponse(
data.UserId,
TimeSpan.FromMilliseconds(data.TotalConsumedDurationMilliseconds).TotalSeconds,
data.TotalConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds,
data.CountedSessionCount,
data.CompletedSessionCount,
data.StoppedSessionCount,
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.MediaConsumption;
using System.Linq;
#endregion
namespace Lumina.Application.Common.Mapping.MediaConsumption;
/// <summary>
/// Extension methods for converting <see cref="ConsumptionTotalsDto"/>.
/// </summary>
public static class ConsumptionTotalsDtoMapping
{
/// <summary>
/// Converts <paramref name="data"/> to <see cref="ConsumptionTotalsResponse"/>.
/// </summary>
/// <param name="data">The data transfer object to be converted.</param>
/// <returns>The converted response.</returns>
public static ConsumptionTotalsResponse ToResponse(this ConsumptionTotalsDto data)
{
return new ConsumptionTotalsResponse(
data.TotalConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds,
data.CountedSessionCount,
data.CompletedSessionCount,
data.StoppedSessionCount,
data.CompletionRate,
[.. data.MediaKindSummaries.Select(mediaKindSummary => mediaKindSummary.ToResponse())]
);
}
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.ExternalIdentifiers.LibraryManagementBoundedContext.LibraryAggregate;
@@ -39,8 +40,11 @@ public static class MediaConsumptionRecordEntityMapping
MediaPositionKind positionKind = repositoryEntity.LastPositionKind.Value;
if (positionKind == MediaPositionKind.TimeOffset)
{
// A stored position outside the representable range is rejected like a negative one, instead of being silently clamped to a position that no client ever reported.
long maximumTimeOffsetMilliseconds = TimeSpan.MaxValue.Ticks / TimeSpan.TicksPerMillisecond;
if (!repositoryEntity.LastPositionTimeOffsetMilliseconds.HasValue ||
repositoryEntity.LastPositionTimeOffsetMilliseconds.Value < 0 ||
repositoryEntity.LastPositionTimeOffsetMilliseconds.Value > maximumTimeOffsetMilliseconds ||
repositoryEntity.LastPositionLocation is not null)
return DomainErrors.MediaConsumption.InvalidMediaPosition;
lastPosition = Optional<MediaPosition>.Some(
@@ -67,7 +71,7 @@ public static class MediaConsumptionRecordEntityMapping
DateTime.SpecifyKind(repositoryEntity.StartedOnUtc, DateTimeKind.Utc),
DateTime.SpecifyKind(repositoryEntity.LastActivityOnUtc, DateTimeKind.Utc),
endedOnUtc,
TimeSpan.FromMilliseconds(repositoryEntity.ConsumedDurationMilliseconds),
repositoryEntity.ConsumedDurationMilliseconds.ToClampedTimeSpan(),
lastPosition,
repositoryEntity.LastProgressFraction,
repositoryEntity.ConsecutivePagesRead
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.MediaConsumption;
using System;
#endregion
namespace Lumina.Application.Common.Mapping.MediaConsumption;
@@ -20,7 +20,7 @@ public static class MediaKindConsumptionStatisticsDtoMapping
{
return new MediaKindConsumptionSummaryResponse(
data.MediaKind,
TimeSpan.FromMilliseconds(data.TotalConsumedDurationMilliseconds).TotalSeconds,
data.TotalConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds,
data.CountedSessionCount,
data.CompletedSessionCount,
data.StoppedSessionCount,
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.MediaConsumption;
using System;
#endregion
namespace Lumina.Application.Common.Mapping.MediaConsumption;
@@ -20,7 +20,7 @@ public static class MediaPositionDtoMapping
{
return new MediaPositionResponse(
data.Kind,
data.TimeOffsetMilliseconds.HasValue ? TimeSpan.FromMilliseconds(data.TimeOffsetMilliseconds.Value).TotalSeconds : null,
data.TimeOffsetMilliseconds.HasValue ? data.TimeOffsetMilliseconds.Value.ToClampedTimeSpan().TotalSeconds : null,
data.Location
);
}
@@ -32,8 +32,11 @@ public static class MediaResumePointEntityMapping
MediaPosition lastPosition;
if (repositoryEntity.LastPositionKind == MediaPositionKind.TimeOffset)
{
// A stored position outside the representable range is rejected like a negative one, instead of being silently clamped to a position that no client ever reported.
long maximumTimeOffsetMilliseconds = TimeSpan.MaxValue.Ticks / TimeSpan.TicksPerMillisecond;
if (!repositoryEntity.LastPositionTimeOffsetMilliseconds.HasValue ||
repositoryEntity.LastPositionTimeOffsetMilliseconds.Value < 0 ||
repositoryEntity.LastPositionTimeOffsetMilliseconds.Value > maximumTimeOffsetMilliseconds ||
repositoryEntity.LastPositionLocation is not null)
return DomainErrors.MediaConsumption.InvalidMediaPosition;
lastPosition = MediaPosition.CreateTimeOffset(TimeSpan.FromMilliseconds(repositoryEntity.LastPositionTimeOffsetMilliseconds.Value));
@@ -1,7 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.MediaConsumption;
using System;
using System.Collections.Generic;
using System.Linq;
#endregion
@@ -24,7 +24,7 @@ public static class TagConsumptionDtoMapping
data.Name,
data.TagKind,
data.ConsumedItemCount,
TimeSpan.FromMilliseconds(data.ConsumedDurationMilliseconds).TotalSeconds
data.ConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds
);
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Contracts.DTO.Common;
@@ -13,6 +14,7 @@ using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibrary
using Lumina.Domain.Core.BoundedContexts.AudioLibraryBoundedContext.MusicLibraryAggregate.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -27,6 +29,33 @@ namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibra
/// </summary>
public static class TrackEntityMapping
{
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to the consumption history row of a music track.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <param name="lastConsumedOnUtc">The date and time when the track was last consumed.</param>
/// <param name="countedSessionCount">The number of sessions of the track that count towards statistics.</param>
/// <param name="completedSessionCount">The number of sessions of the track that completed.</param>
/// <param name="consumedDurationMilliseconds">The active duration consumed in the track, over all of its sessions, in milliseconds.</param>
/// <param name="coverPath">The path of the cover art of the album that contains the track, if available.</param>
/// <returns>The converted consumption history row.</returns>
public static ConsumedItemDto ToDto(this TrackEntity repositoryEntity, DateTime lastConsumedOnUtc, int countedSessionCount, int completedSessionCount, long consumedDurationMilliseconds, string? coverPath)
{
return new ConsumedItemDto(
MediaKind.MusicTrack,
repositoryEntity.Id,
repositoryEntity.LibraryId,
true,
repositoryEntity.Title,
repositoryEntity.Album?.Title ?? string.Empty,
repositoryEntity.Album?.Artist?.Name ?? string.Empty,
coverPath,
lastConsumedOnUtc,
countedSessionCount,
completedSessionCount,
consumedDurationMilliseconds);
}
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="Track"/>.
/// </summary>
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Mapping.Common.Metadata;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
@@ -31,6 +32,33 @@ namespace Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.B
/// </summary>
public static class BookEntityMapping
{
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to the consumption history row of a book.
/// </summary>
/// <param name="repositoryEntity">The repository entity to be converted.</param>
/// <param name="lastConsumedOnUtc">The date and time when the book was last consumed.</param>
/// <param name="countedSessionCount">The number of sessions of the book that count towards statistics.</param>
/// <param name="completedSessionCount">The number of sessions of the book that completed.</param>
/// <param name="consumedDurationMilliseconds">The active duration consumed in the book, over all of its sessions, in milliseconds.</param>
/// <param name="creatorName">The name of the author of the book, or an empty string when there is none.</param>
/// <returns>The converted consumption history row.</returns>
public static ConsumedItemDto ToDto(this BookEntity repositoryEntity, DateTime lastConsumedOnUtc, int countedSessionCount, int completedSessionCount, long consumedDurationMilliseconds, string creatorName)
{
return new ConsumedItemDto(
MediaKind.Book,
repositoryEntity.Id,
repositoryEntity.LibraryId,
true,
repositoryEntity.Title,
string.Empty,
creatorName,
repositoryEntity.Artwork.FirstOrDefault(artwork => artwork.ArtworkType == ArtworkType.Cover)?.FileName,
lastConsumedOnUtc,
countedSessionCount,
completedSessionCount,
consumedDurationMilliseconds);
}
/// <summary>
/// Converts <paramref name="repositoryEntity"/> to <see cref="Book"/>.
/// </summary>
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Application.Common.Utilities;
/// <summary>
/// Extension methods for converting stored duration values to <see cref="TimeSpan"/>.
/// </summary>
public static class DurationUtilities
{
/// <summary>
/// Converts a duration stored as whole milliseconds to a <see cref="TimeSpan"/>, clamped to the largest value a <see cref="TimeSpan"/> can
/// represent so that an accumulated total above that limit does not throw.
/// </summary>
/// <param name="milliseconds">The duration, in milliseconds.</param>
/// <returns>The duration, clamped to <see cref="TimeSpan.MaxValue"/> when it exceeds the representable range.</returns>
public static TimeSpan ToClampedTimeSpan(this long milliseconds)
{
long maximumMilliseconds = TimeSpan.MaxValue.Ticks / TimeSpan.TicksPerMillisecond;
return TimeSpan.FromMilliseconds(Math.Min(milliseconds, maximumMilliseconds));
}
}
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Commands.ClearConsumptionHistory;
/// <summary>
/// Command for deleting every consumption record of a user.
/// </summary>
/// <param name="TargetUserId">The Id of the user whose history is deleted, or <see langword="null"/> for the current user.</param>
[DebuggerDisplay("TargetUserId: {TargetUserId}")]
public record ClearConsumptionHistoryCommand(
string? TargetUserId
) : ICommand;
@@ -0,0 +1,83 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Commands.ClearConsumptionHistory;
/// <summary>
/// Handler for the command to delete every consumption record of a user.
/// </summary>
public class ClearConsumptionHistoryCommandHandler : ICommandHandler<ClearConsumptionHistoryCommand, Result<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<ClearConsumptionHistoryCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="ClearConsumptionHistoryCommandHandler"/> 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="validator">Injected validator for application validation rules.</param>
public ClearConsumptionHistoryCommandHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IValidator<ClearConsumptionHistoryCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the command to delete every consumption record of a 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}"/> representing either a successful deletion, or an error message.</returns>
public async Task<Result<Deleted>> HandleAsync(ClearConsumptionHistoryCommand 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 target defaults to the current user, and the access policy is the only place that decides whether the caller may act on it.
Guid targetUserId = command.TargetUserId is null ? userId : Guid.Parse(command.TargetUserId);
bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false);
if (!canAccessTarget)
return ApplicationErrors.Authorization.NotAuthorized;
// Clearing the history does not clear the resume points: the two are separate user actions, so the continue watching list survives.
Result<Deleted> deleteResult = await _unitOfWork.MediaConsumptionRecordRepository.DeleteAllForUserAsync(targetUserId, cancellationToken).ConfigureAwait(false);
if (deleteResult.IsFailure)
return deleteResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return Result.Deleted;
}
}
@@ -0,0 +1,26 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Commands.ClearConsumptionHistory;
/// <summary>
/// Validates the needed validation rules for <see cref="ClearConsumptionHistoryCommand"/>.
/// </summary>
public class ClearConsumptionHistoryCommandValidator : AbstractValidator<ClearConsumptionHistoryCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="ClearConsumptionHistoryCommandValidator"/> class.
/// </summary>
public ClearConsumptionHistoryCommandValidator()
{
// The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id.
RuleFor(command => command.TargetUserId)
.Must(targetUserId => targetUserId is null ||
(Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty))
.WithError(Errors.MediaConsumption.TargetUserIdIsInvalid);
}
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Commands.ClearResumePoints;
/// <summary>
/// Command for deleting the resume points of a user.
/// </summary>
/// <param name="TargetUserId">The Id of the user whose resume points are deleted, or <see langword="null"/> for the current user.</param>
/// <param name="LibraryId">The Id of the media library to restrict the deletion to, or <see langword="null"/> for every library.</param>
[DebuggerDisplay("TargetUserId: {TargetUserId}; LibraryId: {LibraryId}")]
public record ClearResumePointsCommand(
string? TargetUserId,
string? LibraryId
) : ICommand;
@@ -0,0 +1,87 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Commands.ClearResumePoints;
/// <summary>
/// Handler for the command to delete the resume points of a user.
/// </summary>
public class ClearResumePointsCommandHandler : ICommandHandler<ClearResumePointsCommand, Result<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<ClearResumePointsCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="ClearResumePointsCommandHandler"/> 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="validator">Injected validator for application validation rules.</param>
public ClearResumePointsCommandHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IValidator<ClearResumePointsCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the command to delete the resume points of a 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}"/> representing either a successful deletion, or an error message.</returns>
public async Task<Result<Deleted>> HandleAsync(ClearResumePointsCommand 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 target defaults to the current user, and the access policy is the only place that decides whether the caller may act on it.
Guid targetUserId = command.TargetUserId is null ? userId : Guid.Parse(command.TargetUserId);
bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false);
if (!canAccessTarget)
return ApplicationErrors.Authorization.NotAuthorized;
// Removing the resume points does not touch the history: the user asked only to clear the continue watching list.
Result<Deleted> deleteResult;
if (command.LibraryId is null)
deleteResult = await _unitOfWork.MediaResumePointRepository.DeleteAllForUserAsync(targetUserId, cancellationToken).ConfigureAwait(false);
else
deleteResult = await _unitOfWork.MediaResumePointRepository.DeleteAllForUserInLibraryAsync(targetUserId, Guid.Parse(command.LibraryId), cancellationToken).ConfigureAwait(false);
if (deleteResult.IsFailure)
return deleteResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return Result.Deleted;
}
}
@@ -0,0 +1,31 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Commands.ClearResumePoints;
/// <summary>
/// Validates the needed validation rules for <see cref="ClearResumePointsCommand"/>.
/// </summary>
public class ClearResumePointsCommandValidator : AbstractValidator<ClearResumePointsCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="ClearResumePointsCommandValidator"/> class.
/// </summary>
public ClearResumePointsCommandValidator()
{
// The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id.
RuleFor(command => command.TargetUserId)
.Must(targetUserId => targetUserId is null ||
(Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty))
.WithError(Errors.MediaConsumption.TargetUserIdIsInvalid);
RuleFor(command => command.LibraryId)
.Must(libraryId => libraryId is null ||
(Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty))
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
}
}
@@ -13,6 +13,12 @@ namespace Lumina.Application.Core.MediaConsumption.Commands.CompleteConsumption;
/// </summary>
public class CompleteConsumptionCommandValidator : AbstractValidator<CompleteConsumptionCommand>
{
/// <summary>
/// The maximum active duration, in seconds, that a client can report for one session or as a position within a media item. The limit keeps
/// accumulated totals representable as a <see cref="TimeSpan"/> and rejects durations that cannot describe real media.
/// </summary>
private const double MAXIMUM_REPORTED_DURATION_IN_SECONDS = 31 * 24 * 60 * 60;
/// <summary>
/// Initializes a new instance of the <see cref="CompleteConsumptionCommandValidator"/> class.
/// </summary>
@@ -54,7 +60,7 @@ public class CompleteConsumptionCommandValidator : AbstractValidator<CompleteCon
RuleFor(command => command.ConsumedDurationInSeconds)
.Must(consumedDuration => consumedDuration is null ||
consumedDuration.Value <= TimeSpan.MaxValue.TotalSeconds)
consumedDuration.Value <= MAXIMUM_REPORTED_DURATION_IN_SECONDS)
.WithError(Errors.MediaConsumption.ConsumedDurationIsOutOfRange);
}
@@ -74,14 +80,13 @@ public class CompleteConsumptionCommandValidator : AbstractValidator<CompleteCon
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.
// 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 &&
timeOffsetInSeconds.Value <= MAXIMUM_REPORTED_DURATION_IN_SECONDS &&
string.IsNullOrWhiteSpace(location),
MediaPositionKind.Location => !timeOffsetInSeconds.HasValue &&
!string.IsNullOrWhiteSpace(location) &&
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionRecord;
/// <summary>
/// Command for deleting one consumption record of a user.
/// </summary>
/// <param name="ConsumptionRecordId">The Id of the consumption record, taken from the route.</param>
/// <param name="TargetUserId">The Id of the user the record must belong to, or <see langword="null"/> for the current user.</param>
[DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}; TargetUserId: {TargetUserId}")]
public record DeleteConsumptionRecordCommand(
string? ConsumptionRecordId,
string? TargetUserId
) : ICommand;
@@ -0,0 +1,86 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Domain.Common.Primitives;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionRecord;
/// <summary>
/// Handler for the command to delete one consumption record of a user.
/// </summary>
public class DeleteConsumptionRecordCommandHandler : ICommandHandler<DeleteConsumptionRecordCommand, Result<Deleted>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<DeleteConsumptionRecordCommand> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="DeleteConsumptionRecordCommandHandler"/> 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="validator">Injected validator for application validation rules.</param>
public DeleteConsumptionRecordCommandHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IValidator<DeleteConsumptionRecordCommand> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the command to delete one consumption record of a 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}"/> representing either a successful deletion, or an error message.</returns>
public async Task<Result<Deleted>> HandleAsync(DeleteConsumptionRecordCommand 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 target defaults to the current user, and the access policy is the only place that decides whether the caller may act on it.
Guid targetUserId = command.TargetUserId is null ? userId : Guid.Parse(command.TargetUserId);
bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false);
if (!canAccessTarget)
return ApplicationErrors.Authorization.NotAuthorized;
// The validator guarantees that the route identifier is a non-empty Guid before this point.
Guid consumptionRecordId = Guid.Parse(command.ConsumptionRecordId!);
// Deleting an absent record succeeds, so a retried deletion or a record deleted in another tab is not an error.
Result<Deleted> deleteResult = await _unitOfWork.MediaConsumptionRecordRepository.DeleteForUserAsync(consumptionRecordId, targetUserId, cancellationToken).ConfigureAwait(false);
if (deleteResult.IsFailure)
return deleteResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
if (saveChangesResult.IsFailure)
return saveChangesResult.Errors;
return Result.Deleted;
}
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionRecord;
/// <summary>
/// Validates the needed validation rules for <see cref="DeleteConsumptionRecordCommand"/>.
/// </summary>
public class DeleteConsumptionRecordCommandValidator : AbstractValidator<DeleteConsumptionRecordCommand>
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteConsumptionRecordCommandValidator"/> class.
/// </summary>
public DeleteConsumptionRecordCommandValidator()
{
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);
// The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id.
RuleFor(command => command.TargetUserId)
.Must(targetUserId => targetUserId is null ||
(Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty))
.WithError(Errors.MediaConsumption.TargetUserIdIsInvalid);
}
}
@@ -13,6 +13,12 @@ namespace Lumina.Application.Core.MediaConsumption.Commands.ReportConsumptionPro
/// </summary>
public class ReportConsumptionProgressCommandValidator : AbstractValidator<ReportConsumptionProgressCommand>
{
/// <summary>
/// The maximum active duration, in seconds, that a client can report for one session or as a position within a media item. The limit keeps
/// accumulated totals representable as a <see cref="TimeSpan"/> and rejects durations that cannot describe real media.
/// </summary>
private const double MAXIMUM_REPORTED_DURATION_IN_SECONDS = 31 * 24 * 60 * 60;
/// <summary>
/// Initializes a new instance of the <see cref="ReportConsumptionProgressCommandValidator"/> class.
/// </summary>
@@ -54,7 +60,7 @@ public class ReportConsumptionProgressCommandValidator : AbstractValidator<Repor
RuleFor(command => command.ConsumedDurationInSeconds)
.Must(consumedDuration => consumedDuration is null ||
consumedDuration.Value <= TimeSpan.MaxValue.TotalSeconds)
consumedDuration.Value <= MAXIMUM_REPORTED_DURATION_IN_SECONDS)
.WithError(Errors.MediaConsumption.ConsumedDurationIsOutOfRange);
RuleFor(command => command.ConsecutivePagesRead)
@@ -78,14 +84,13 @@ public class ReportConsumptionProgressCommandValidator : AbstractValidator<Repor
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.
// 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 &&
timeOffsetInSeconds.Value <= MAXIMUM_REPORTED_DURATION_IN_SECONDS &&
string.IsNullOrWhiteSpace(location),
MediaPositionKind.Location => !timeOffsetInSeconds.HasValue &&
!string.IsNullOrWhiteSpace(location) &&
@@ -13,6 +13,12 @@ namespace Lumina.Application.Core.MediaConsumption.Commands.StopConsumption;
/// </summary>
public class StopConsumptionCommandValidator : AbstractValidator<StopConsumptionCommand>
{
/// <summary>
/// The maximum active duration, in seconds, that a client can report for one session or as a position within a media item. The limit keeps
/// accumulated totals representable as a <see cref="TimeSpan"/> and rejects durations that cannot describe real media.
/// </summary>
private const double MAXIMUM_REPORTED_DURATION_IN_SECONDS = 31 * 24 * 60 * 60;
/// <summary>
/// Initializes a new instance of the <see cref="StopConsumptionCommandValidator"/> class.
/// </summary>
@@ -54,7 +60,7 @@ public class StopConsumptionCommandValidator : AbstractValidator<StopConsumption
RuleFor(command => command.ConsumedDurationInSeconds)
.Must(consumedDuration => consumedDuration is null ||
consumedDuration.Value <= TimeSpan.MaxValue.TotalSeconds)
consumedDuration.Value <= MAXIMUM_REPORTED_DURATION_IN_SECONDS)
.WithError(Errors.MediaConsumption.ConsumedDurationIsOutOfRange);
}
@@ -74,14 +80,13 @@ public class StopConsumptionCommandValidator : AbstractValidator<StopConsumption
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.
// 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 &&
timeOffsetInSeconds.Value <= MAXIMUM_REPORTED_DURATION_IN_SECONDS &&
string.IsNullOrWhiteSpace(location),
MediaPositionKind.Location => !timeOffsetInSeconds.HasValue &&
!string.IsNullOrWhiteSpace(location) &&
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Queries.GetAllUsersConsumptionStatistics;
/// <summary>
/// Query for getting the consumption statistics of every user.
/// </summary>
/// <param name="LibraryId">The Id of the media library to restrict the statistics to, or <see langword="null"/> for every library.</param>
/// <param name="MediaKind">The kind of media to restrict the statistics to, or <see langword="null"/> for every kind.</param>
/// <param name="FromUtc">The inclusive start of the date range, or <see langword="null"/> when the range has no start.</param>
/// <param name="ToUtc">The inclusive end of the date range, or <see langword="null"/> when the range has no end.</param>
[DebuggerDisplay("MediaKind: {MediaKind}")]
public record GetAllUsersConsumptionStatisticsQuery(
string? LibraryId,
MediaKind? MediaKind,
DateTime? FromUtc,
DateTime? ToUtc
) : IQuery;
@@ -0,0 +1,182 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaConsumption;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.MediaConsumption;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Queries.GetAllUsersConsumptionStatistics;
/// <summary>
/// Handler for the query to get the consumption statistics of every user.
/// </summary>
public class GetAllUsersConsumptionStatisticsQueryHandler : IQueryHandler<GetAllUsersConsumptionStatisticsQuery, Result<AllUsersConsumptionStatisticsResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<GetAllUsersConsumptionStatisticsQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetAllUsersConsumptionStatisticsQueryHandler"/> 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="validator">Injected validator for application validation rules.</param>
public GetAllUsersConsumptionStatisticsQueryHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IValidator<GetAllUsersConsumptionStatisticsQuery> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the consumption statistics of every user.
/// </summary>
/// <param name="query">The query 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 requested <see cref="AllUsersConsumptionStatisticsResponse"/>, or an error message.
/// </returns>
public async Task<Result<AllUsersConsumptionStatisticsResponse>> HandleAsync(GetAllUsersConsumptionStatisticsQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
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;
// Only admins can read the statistics of every user; the all-users summary is not derived from the per-user routes.
bool isAdmin = await _authorizationService.IsInRoleAsync(userId, AuthorizationRoles.ADMIN, cancellationToken).ConfigureAwait(false);
if (!isAdmin)
return ApplicationErrors.Authorization.NotAuthorized;
Guid? libraryId = query.LibraryId is null ? null : Guid.Parse(query.LibraryId);
// This is the only statistics query that loads the records of every user, and it is reachable only through the admin check above.
Result<IReadOnlyList<MediaConsumptionRecordEntity>> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository
.GetForAllUsersAsync(libraryId, query.MediaKind, query.FromUtc, query.ToUtc, cancellationToken).ConfigureAwait(false);
if (getRecordsResult.IsFailure)
return getRecordsResult.Errors;
// The user summaries are built in one pass over the grouped records. The server total is then derived from those summaries, so it can
// never disagree with the sum of the users and the records are not walked again for it.
List<ConsumptionStatisticsDto> userSummaries = [.. getRecordsResult.Value
.GroupBy(record => record.UserId)
.OrderBy(group => group.Key)
.Select(group => BuildStatistics(group.Key, group))];
List<MediaKindConsumptionStatisticsDto> totalMediaKindSummaries = [.. userSummaries
.SelectMany(summary => summary.MediaKindSummaries)
.GroupBy(summary => summary.MediaKind)
.OrderBy(group => group.Key)
.Select(group =>
{
int countedSessionCount = group.Sum(summary => summary.CountedSessionCount);
int completedSessionCount = group.Sum(summary => summary.CompletedSessionCount);
return new MediaKindConsumptionStatisticsDto(
group.Key,
group.Sum(summary => summary.TotalConsumedDurationMilliseconds),
countedSessionCount,
completedSessionCount,
group.Sum(summary => summary.StoppedSessionCount),
countedSessionCount == 0 ? 0 : (double)completedSessionCount / countedSessionCount);
})];
int totalCountedSessionCount = userSummaries.Sum(summary => summary.CountedSessionCount);
int totalCompletedSessionCount = userSummaries.Sum(summary => summary.CompletedSessionCount);
ConsumptionTotalsDto totals = new(
userSummaries.Sum(summary => summary.TotalConsumedDurationMilliseconds),
totalCountedSessionCount,
totalCompletedSessionCount,
userSummaries.Sum(summary => summary.StoppedSessionCount),
totalCountedSessionCount == 0 ? 0 : (double)totalCompletedSessionCount / totalCountedSessionCount,
totalMediaKindSummaries);
return new AllUsersConsumptionStatisticsDto(totals, userSummaries).ToResponse();
}
/// <summary>
/// Builds the consumption statistics of a user from the records of that user.
/// </summary>
/// <param name="userId">The Id of the user the records belong to.</param>
/// <param name="records">The records of the user, already filtered by the query.</param>
/// <returns>The consumption statistics of the user.</returns>
private static ConsumptionStatisticsDto BuildStatistics(Guid userId, IEnumerable<MediaConsumptionRecordEntity> records)
{
// The rule is created once per media kind instead of once per record. A completed session always counts, while a stopped session counts
// only when it reaches the counting threshold of its media kind. Duration totals every session because it measures consumed time, not the
// subset of sessions that count towards the statistics.
List<MediaKindConsumptionStatisticsDto> mediaKindSummaries = [];
foreach (IGrouping<MediaKind, MediaConsumptionRecordEntity> mediaKindGroup in records
.GroupBy(record => record.MediaKind)
.OrderBy(group => group.Key))
{
Optional<MediaConsumptionRule> ruleResult = MediaConsumptionRule.For(mediaKindGroup.Key);
int countedSessionCount = 0;
int completedSessionCount = 0;
int stoppedSessionCount = 0;
long consumedDurationMilliseconds = 0;
foreach (MediaConsumptionRecordEntity record in mediaKindGroup)
{
consumedDurationMilliseconds += record.ConsumedDurationMilliseconds;
if (!ruleResult.HasValue)
continue;
if (record.Status == ConsumptionStatus.Completed)
completedSessionCount++;
if (!ruleResult.Value.Counts(record.Status, record.ConsumedDurationMilliseconds.ToClampedTimeSpan(), record.ConsecutivePagesRead))
continue;
countedSessionCount++;
if (record.Status == ConsumptionStatus.Stopped)
stoppedSessionCount++;
}
mediaKindSummaries.Add(new MediaKindConsumptionStatisticsDto(
mediaKindGroup.Key,
consumedDurationMilliseconds,
countedSessionCount,
completedSessionCount,
stoppedSessionCount,
countedSessionCount == 0 ? 0 : (double)completedSessionCount / countedSessionCount));
}
// The overall totals are the sums of the per-kind summaries, so the completion rate can never disagree with the breakdown.
long totalConsumedDurationMilliseconds = mediaKindSummaries.Sum(summary => summary.TotalConsumedDurationMilliseconds);
int totalCountedSessionCount = mediaKindSummaries.Sum(summary => summary.CountedSessionCount);
int totalCompletedSessionCount = mediaKindSummaries.Sum(summary => summary.CompletedSessionCount);
int totalStoppedSessionCount = mediaKindSummaries.Sum(summary => summary.StoppedSessionCount);
return new ConsumptionStatisticsDto(
userId,
totalConsumedDurationMilliseconds,
totalCountedSessionCount,
totalCompletedSessionCount,
totalStoppedSessionCount,
totalCountedSessionCount == 0 ? 0 : (double)totalCompletedSessionCount / totalCountedSessionCount,
mediaKindSummaries);
}
}
@@ -0,0 +1,40 @@
#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.Queries.GetAllUsersConsumptionStatistics;
/// <summary>
/// Validates the needed validation rules for <see cref="GetAllUsersConsumptionStatisticsQuery"/>.
/// </summary>
public class GetAllUsersConsumptionStatisticsQueryValidator : AbstractValidator<GetAllUsersConsumptionStatisticsQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetAllUsersConsumptionStatisticsQueryValidator"/> class.
/// </summary>
public GetAllUsersConsumptionStatisticsQueryValidator()
{
RuleFor(query => query.LibraryId)
.Must(libraryId => libraryId is null ||
(Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty))
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(query => query.MediaKind)
.IsInEnum()
.WithError(Errors.MediaConsumption.UnsupportedMediaKind)
.When(query => query.MediaKind is not null);
RuleFor(query => query.MediaKind)
.Must(mediaKind => mediaKind is null || mediaKind != MediaKind.None)
.WithError(Errors.MediaConsumption.UnsupportedMediaKind);
// An inverted range would silently return no records, so it is rejected as an invalid request instead.
RuleFor(query => query.FromUtc)
.Must((query, fromUtc) => !fromUtc.HasValue || !query.ToUtc.HasValue || fromUtc.Value <= query.ToUtc.Value)
.WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
}
}
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionRecord;
/// <summary>
/// Query for getting a consumption record of the current user.
/// </summary>
/// <param name="ConsumptionRecordId">The Id of the consumption record, taken from the route.</param>
[DebuggerDisplay("ConsumptionRecordId: {ConsumptionRecordId}")]
public record GetConsumptionRecordQuery(
string? ConsumptionRecordId
) : IQuery;
@@ -0,0 +1,78 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.UoW;
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.Primitives;
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.Queries.GetConsumptionRecord;
/// <summary>
/// Handler for the query to get a consumption record of the current user.
/// </summary>
public class GetConsumptionRecordQueryHandler : IQueryHandler<GetConsumptionRecordQuery, Result<ConsumptionRecordResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetConsumptionRecordQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetConsumptionRecordQueryHandler"/> 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="validator">Injected validator for application validation rules.</param>
public GetConsumptionRecordQueryHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IValidator<GetConsumptionRecordQuery> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get a consumption record of the current user.
/// </summary>
/// <param name="query">The query 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 requested <see cref="ConsumptionRecordResponse"/>, or an error message.
/// </returns>
public async Task<Result<ConsumptionRecordResponse>> HandleAsync(GetConsumptionRecordQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
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 is a non-empty Guid before this point.
Guid consumptionRecordId = Guid.Parse(query.ConsumptionRecordId!);
// The record is read without tracking and 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, shouldTrackEntities: false, cancellationToken: cancellationToken).ConfigureAwait(false);
if (getRecordResult.IsFailure)
return getRecordResult.Errors;
if (getRecordResult.Value is null)
return DomainErrors.MediaConsumption.ConsumptionRecordNotFound;
return getRecordResult.Value.ToDto().ToResponse();
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Utilities;
using Lumina.Domain.Common.Errors;
using System;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionRecord;
/// <summary>
/// Validates the needed validation rules for <see cref="GetConsumptionRecordQuery"/>.
/// </summary>
public class GetConsumptionRecordQueryValidator : AbstractValidator<GetConsumptionRecordQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetConsumptionRecordQueryValidator"/> class.
/// </summary>
public GetConsumptionRecordQueryValidator()
{
RuleFor(query => query.ConsumptionRecordId)
.NotEmpty()
.WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty);
RuleFor(query => query.ConsumptionRecordId)
.Must(consumptionRecordId => Guid.TryParse(consumptionRecordId, out Guid parsedConsumptionRecordId) && parsedConsumptionRecordId != Guid.Empty)
.When(query => query.ConsumptionRecordId is not null && query.ConsumptionRecordId.Length > 0)
.WithError(Errors.MediaConsumption.ConsumptionRecordIdCannotBeEmpty);
}
}
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatistics;
/// <summary>
/// Query for getting the consumption statistics of a user.
/// </summary>
/// <param name="TargetUserId">The Id of the user whose statistics are retrieved, or <see langword="null"/> for the current user.</param>
/// <param name="LibraryId">The Id of the media library to restrict the statistics to, or <see langword="null"/> for every library.</param>
/// <param name="MediaKind">The kind of media to restrict the statistics to, or <see langword="null"/> for every kind.</param>
/// <param name="FromUtc">The inclusive start of the date range, or <see langword="null"/> when the range has no start.</param>
/// <param name="ToUtc">The inclusive end of the date range, or <see langword="null"/> when the range has no end.</param>
[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")]
public record GetConsumptionStatisticsQuery(
string? TargetUserId,
string? LibraryId,
MediaKind? MediaKind,
DateTime? FromUtc,
DateTime? ToUtc
) : IQuery;
@@ -0,0 +1,151 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaConsumption;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.MediaConsumption;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Queries.GetConsumptionStatistics;
/// <summary>
/// Handler for the query to get the consumption statistics of a user.
/// </summary>
public class GetConsumptionStatisticsQueryHandler : IQueryHandler<GetConsumptionStatisticsQuery, Result<ConsumptionSummaryResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<GetConsumptionStatisticsQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetConsumptionStatisticsQueryHandler"/> 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="validator">Injected validator for application validation rules.</param>
public GetConsumptionStatisticsQueryHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IValidator<GetConsumptionStatisticsQuery> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the consumption statistics of a user.
/// </summary>
/// <param name="query">The query 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 requested <see cref="ConsumptionSummaryResponse"/>, or an error message.
/// </returns>
public async Task<Result<ConsumptionSummaryResponse>> HandleAsync(GetConsumptionStatisticsQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
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 target defaults to the current user, and the access policy is the only place that decides whether the caller may read it.
Guid targetUserId = query.TargetUserId is null ? userId : Guid.Parse(query.TargetUserId);
bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false);
if (!canAccessTarget)
return ApplicationErrors.Authorization.NotAuthorized;
Guid? libraryId = query.LibraryId is null ? null : Guid.Parse(query.LibraryId);
// The handlers aggregate the records themselves; the repository only binds the filters and returns the records without tracking.
Result<IReadOnlyList<MediaConsumptionRecordEntity>> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository
.GetForUserAsync(targetUserId, libraryId, query.MediaKind, query.FromUtc, query.ToUtc, cancellationToken).ConfigureAwait(false);
if (getRecordsResult.IsFailure)
return getRecordsResult.Errors;
return BuildStatistics(targetUserId, getRecordsResult.Value).ToResponse();
}
/// <summary>
/// Builds the consumption statistics of a user from the records of that user.
/// </summary>
/// <param name="userId">The Id of the user the records belong to.</param>
/// <param name="records">The records of the user, already filtered by the query.</param>
/// <returns>The consumption statistics of the user.</returns>
private static ConsumptionStatisticsDto BuildStatistics(Guid userId, IEnumerable<MediaConsumptionRecordEntity> records)
{
// The rule is created once per media kind instead of once per record. A completed session always counts, while a stopped session counts
// only when it reaches the counting threshold of its media kind. Duration totals every session because it measures consumed time, not the
// subset of sessions that count towards the statistics.
List<MediaKindConsumptionStatisticsDto> mediaKindSummaries = [];
foreach (IGrouping<MediaKind, MediaConsumptionRecordEntity> mediaKindGroup in records
.GroupBy(record => record.MediaKind)
.OrderBy(group => group.Key))
{
Optional<MediaConsumptionRule> ruleResult = MediaConsumptionRule.For(mediaKindGroup.Key);
int countedSessionCount = 0;
int completedSessionCount = 0;
int stoppedSessionCount = 0;
long consumedDurationMilliseconds = 0;
foreach (MediaConsumptionRecordEntity record in mediaKindGroup)
{
consumedDurationMilliseconds += record.ConsumedDurationMilliseconds;
if (!ruleResult.HasValue)
continue;
if (record.Status == ConsumptionStatus.Completed)
completedSessionCount++;
if (!ruleResult.Value.Counts(record.Status, record.ConsumedDurationMilliseconds.ToClampedTimeSpan(), record.ConsecutivePagesRead))
continue;
countedSessionCount++;
if (record.Status == ConsumptionStatus.Stopped)
stoppedSessionCount++;
}
mediaKindSummaries.Add(new MediaKindConsumptionStatisticsDto(
mediaKindGroup.Key,
consumedDurationMilliseconds,
countedSessionCount,
completedSessionCount,
stoppedSessionCount,
countedSessionCount == 0 ? 0 : (double)completedSessionCount / countedSessionCount));
}
// The overall totals are the sums of the per-kind summaries, so the completion rate can never disagree with the breakdown.
long totalConsumedDurationMilliseconds = mediaKindSummaries.Sum(summary => summary.TotalConsumedDurationMilliseconds);
int totalCountedSessionCount = mediaKindSummaries.Sum(summary => summary.CountedSessionCount);
int totalCompletedSessionCount = mediaKindSummaries.Sum(summary => summary.CompletedSessionCount);
int totalStoppedSessionCount = mediaKindSummaries.Sum(summary => summary.StoppedSessionCount);
return new ConsumptionStatisticsDto(
userId,
totalConsumedDurationMilliseconds,
totalCountedSessionCount,
totalCompletedSessionCount,
totalStoppedSessionCount,
totalCountedSessionCount == 0 ? 0 : (double)totalCompletedSessionCount / totalCountedSessionCount,
mediaKindSummaries);
}
}
@@ -0,0 +1,46 @@
#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.Queries.GetConsumptionStatistics;
/// <summary>
/// Validates the needed validation rules for <see cref="GetConsumptionStatisticsQuery"/>.
/// </summary>
public class GetConsumptionStatisticsQueryValidator : AbstractValidator<GetConsumptionStatisticsQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetConsumptionStatisticsQueryValidator"/> class.
/// </summary>
public GetConsumptionStatisticsQueryValidator()
{
// The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id.
RuleFor(query => query.TargetUserId)
.Must(targetUserId => targetUserId is null ||
(Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty))
.WithError(Errors.MediaConsumption.TargetUserIdIsInvalid);
RuleFor(query => query.LibraryId)
.Must(libraryId => libraryId is null ||
(Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty))
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(query => query.MediaKind)
.IsInEnum()
.WithError(Errors.MediaConsumption.UnsupportedMediaKind)
.When(query => query.MediaKind is not null);
RuleFor(query => query.MediaKind)
.Must(mediaKind => mediaKind is null || mediaKind != MediaKind.None)
.WithError(Errors.MediaConsumption.UnsupportedMediaKind);
// An inverted range would silently return no records, so it is rejected as an invalid request instead.
RuleFor(query => query.FromUtc)
.Must((query, fromUtc) => !fromUtc.HasValue || !query.ToUtc.HasValue || fromUtc.Value <= query.ToUtc.Value)
.WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed;
/// <summary>
/// Query for getting the most consumed media items of a user.
/// </summary>
/// <param name="TargetUserId">The Id of the user whose history is retrieved, or <see langword="null"/> for the current user.</param>
/// <param name="LibraryId">The Id of the media library to restrict the history to, or <see langword="null"/> for every library.</param>
/// <param name="MediaKind">The kind of media to restrict the history to, or <see langword="null"/> for every kind.</param>
/// <param name="PaginationData">The object containing the requested pagination data. When <see langword="null"/>, every matching item is returned; when present, its requested page is returned.</param>
[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")]
public record GetMostConsumedQuery(
string? TargetUserId,
string? LibraryId,
MediaKind? MediaKind,
PaginationDataDto? PaginationData
) : IQuery;
@@ -0,0 +1,345 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity;
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.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaConsumption;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed;
/// <summary>
/// Handler for the query to get the most consumed media items of a user.
/// </summary>
public class GetMostConsumedQueryHandler : IQueryHandler<GetMostConsumedQuery, Result<PaginatedResponse<ConsumedItemResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<GetMostConsumedQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetMostConsumedQueryHandler"/> 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="validator">Injected validator for application validation rules.</param>
public GetMostConsumedQueryHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IValidator<GetMostConsumedQuery> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the most consumed media items of a user.
/// </summary>
/// <param name="query">The query 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 requested page of most consumed media items, or an error message.
/// </returns>
public async Task<Result<PaginatedResponse<ConsumedItemResponse>>> HandleAsync(GetMostConsumedQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
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 target defaults to the current user, and the access policy is the only place that decides whether the caller may read it.
Guid targetUserId = query.TargetUserId is null ? userId : Guid.Parse(query.TargetUserId);
bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false);
if (!canAccessTarget)
return ApplicationErrors.Authorization.NotAuthorized;
Guid? libraryId = query.LibraryId is null ? null : Guid.Parse(query.LibraryId);
Result<IReadOnlyList<MediaConsumptionRecordEntity>> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository
.GetForUserAsync(targetUserId, libraryId, query.MediaKind, fromUtc: null, toUtc: null, cancellationToken).ConfigureAwait(false);
if (getRecordsResult.IsFailure)
return getRecordsResult.Errors;
// The sessions are reduced to one row per media item before ordering and pagination, so an item consumed many times appears once.
List<ConsumedItemAggregate> orderedAggregates = [.. BuildAggregates(getRecordsResult.Value)
.OrderByDescending(aggregate => aggregate.CountedSessionCount)
.ThenByDescending(aggregate => aggregate.ConsumedDurationMilliseconds)
.ThenByDescending(aggregate => aggregate.LastConsumedOnUtc)
.ThenBy(aggregate => aggregate.MediaItemId)
.ThenBy(aggregate => aggregate.MediaKind)
.ThenBy(aggregate => aggregate.LibraryId)];
PaginatedResultDto<ConsumedItemDto> page;
if (query.PaginationData is null)
{
// Without pagination the caller asked for every matching item, which is bounded by the number of distinct items in the history.
Result<List<ConsumedItemDto>> getItemsResult = await ToConsumedItemDtosAsync(orderedAggregates, userId, cancellationToken).ConfigureAwait(false);
if (getItemsResult.IsFailure)
return getItemsResult.Errors;
page = new PaginatedResultDto<ConsumedItemDto>
{
Data = getItemsResult.Value,
CurrentPage = 1,
PerPage = orderedAggregates.Count,
Count = orderedAggregates.Count,
NumberOfPages = 1
};
}
else
{
int currentPage = query.PaginationData.CurrentPage;
int perPage = query.PaginationData.PerPage;
int count = orderedAggregates.Count;
int numberOfPages = (int)Math.Ceiling((double)count / perPage);
int pageNumber = Math.Min(currentPage, Math.Max(1, numberOfPages));
List<ConsumedItemAggregate> pageAggregates = [.. orderedAggregates
.Skip((pageNumber - 1) * perPage)
.Take(perPage)];
Result<List<ConsumedItemDto>> getItemsResult = await ToConsumedItemDtosAsync(pageAggregates, userId, cancellationToken).ConfigureAwait(false);
if (getItemsResult.IsFailure)
return getItemsResult.Errors;
page = new PaginatedResultDto<ConsumedItemDto>
{
Data = getItemsResult.Value,
CurrentPage = pageNumber,
PerPage = perPage,
Count = count,
NumberOfPages = numberOfPages
};
}
return Result.From(page.ToResponses());
}
/// <summary>
/// Aggregates the consumption records of each media item into the counts and duration that the history lists show.
/// </summary>
/// <param name="records">The consumption records of the user, already filtered by the query.</param>
/// <returns>One aggregate per media item, library, and media kind.</returns>
private static List<ConsumedItemAggregate> BuildAggregates(IReadOnlyList<MediaConsumptionRecordEntity> records)
{
List<ConsumedItemAggregate> aggregates = [];
foreach (IGrouping<(MediaKind MediaKind, Guid MediaItemId, Guid LibraryId), MediaConsumptionRecordEntity> itemGroup in records
.GroupBy(record => (record.MediaKind, record.MediaItemId, record.LibraryId)))
{
// Counted sessions follow the rule of the media kind, while the completed count is the subset that completed. Duration totals every
// session of the item, because it measures consumed time, not only the sessions that count.
Optional<MediaConsumptionRule> ruleResult = MediaConsumptionRule.For(itemGroup.Key.MediaKind);
int countedSessionCount = 0;
int completedSessionCount = 0;
long consumedDurationMilliseconds = 0;
DateTime lastConsumedOnUtc = DateTime.MinValue;
foreach (MediaConsumptionRecordEntity record in itemGroup)
{
consumedDurationMilliseconds += record.ConsumedDurationMilliseconds;
if (record.LastActivityOnUtc > lastConsumedOnUtc)
lastConsumedOnUtc = record.LastActivityOnUtc;
if (record.Status == ConsumptionStatus.Completed)
completedSessionCount++;
if (ruleResult.HasValue &&
ruleResult.Value.Counts(record.Status, record.ConsumedDurationMilliseconds.ToClampedTimeSpan(), record.ConsecutivePagesRead))
countedSessionCount++;
}
aggregates.Add(new ConsumedItemAggregate(
itemGroup.Key.MediaKind,
itemGroup.Key.MediaItemId,
itemGroup.Key.LibraryId,
lastConsumedOnUtc,
countedSessionCount,
completedSessionCount,
consumedDurationMilliseconds));
}
return aggregates;
}
/// <summary>
/// Resolves the display data of the media items of <paramref name="aggregates"/> and builds their DTOs.
/// </summary>
/// <param name="aggregates">The aggregated history rows of the requested page.</param>
/// <param name="currentUserId">The Id of the current user, used to decide which library display data may be shown.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The history rows, with blank display data for missing or inaccessible items.</returns>
private async Task<Result<List<ConsumedItemDto>>> ToConsumedItemDtosAsync(
List<ConsumedItemAggregate> aggregates, Guid currentUserId, CancellationToken cancellationToken)
{
if (aggregates.Count == 0)
return new List<ConsumedItemDto>();
// The access decision only needs the library Id that the record already carries, so it is made once per distinct library before any item
// or artwork is loaded. Inaccessible items keep their counts and duration, but their display data is never read.
Dictionary<Guid, bool> libraryAccess = [];
foreach (Guid libraryId in aggregates.Select(aggregate => aggregate.LibraryId).Distinct())
libraryAccess[libraryId] = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
currentUserId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
List<Guid> trackIds = [.. aggregates
.Where(aggregate => aggregate.MediaKind == MediaKind.MusicTrack && libraryAccess[aggregate.LibraryId])
.Select(aggregate => aggregate.MediaItemId)
.Distinct()];
Dictionary<Guid, TrackEntity> tracks = [];
if (trackIds.Count > 0)
{
Result<IReadOnlyList<TrackEntity>> getTracksResult = await _unitOfWork.TrackRepository
.GetByIdsAsync(trackIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false);
if (getTracksResult.IsFailure)
return getTracksResult.Errors;
tracks = getTracksResult.Value.ToDictionary(track => track.Id);
}
List<Guid> albumIds = [.. tracks.Values.Select(track => track.AlbumId).Distinct()];
Dictionary<Guid, string?> albumCovers = [];
if (albumIds.Count > 0)
{
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository
.GetByOwnersAsync(MusicArtworkOwnerType.Album, albumIds, cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
albumCovers = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.GroupBy(artwork => artwork.OwnerId)
.ToDictionary(
group => group.Key,
group => group.OrderBy(artwork => artwork.Ordinal).Select(artwork => artwork.FileName).FirstOrDefault());
}
List<Guid> bookIds = [.. aggregates
.Where(aggregate => aggregate.MediaKind == MediaKind.Book && libraryAccess[aggregate.LibraryId])
.Select(aggregate => aggregate.MediaItemId)
.Distinct()];
Dictionary<Guid, BookEntity> books = [];
if (bookIds.Count > 0)
{
Result<IReadOnlyList<BookEntity>> getBooksResult = await _unitOfWork.BookRepository
.GetByIdsAsync(bookIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false);
if (getBooksResult.IsFailure)
return getBooksResult.Errors;
books = getBooksResult.Value.ToDictionary(book => book.Id);
}
List<Guid> authorIds = [.. books.Values
.SelectMany(book => book.Contributors
.Where(contributor => contributor.Role == MediaContributorRole.Author)
.Select(contributor => contributor.MediaContributorId))
.Distinct()];
Dictionary<Guid, string> authorNames = [];
if (authorIds.Count > 0)
{
Result<IReadOnlyList<MediaContributorEntity>> getAuthorsResult = await _unitOfWork.MediaContributorRepository
.GetByIdsAsync(authorIds, cancellationToken).ConfigureAwait(false);
if (getAuthorsResult.IsFailure)
return getAuthorsResult.Errors;
authorNames = getAuthorsResult.Value.ToDictionary(contributor => contributor.Id, contributor => contributor.DisplayName);
}
List<ConsumedItemDto> items = [];
foreach (ConsumedItemAggregate aggregate in aggregates)
{
if (aggregate.MediaKind == MediaKind.MusicTrack &&
libraryAccess[aggregate.LibraryId] &&
tracks.TryGetValue(aggregate.MediaItemId, out TrackEntity? track) &&
track.LibraryId == aggregate.LibraryId)
{
string? coverPath = albumCovers.TryGetValue(track.AlbumId, out string? coverFileName) ? coverFileName : null;
items.Add(track.ToDto(
aggregate.LastConsumedOnUtc,
aggregate.CountedSessionCount,
aggregate.CompletedSessionCount,
aggregate.ConsumedDurationMilliseconds,
coverPath));
continue;
}
if (aggregate.MediaKind == MediaKind.Book &&
libraryAccess[aggregate.LibraryId] &&
books.TryGetValue(aggregate.MediaItemId, out BookEntity? book) &&
book.LibraryId == aggregate.LibraryId)
{
string creatorName = book.Contributors
.Where(contributor => contributor.Role == MediaContributorRole.Author && authorNames.ContainsKey(contributor.MediaContributorId))
.Select(contributor => authorNames[contributor.MediaContributorId])
.OrderBy(name => name)
.FirstOrDefault() ?? string.Empty;
items.Add(book.ToDto(
aggregate.LastConsumedOnUtc,
aggregate.CountedSessionCount,
aggregate.CompletedSessionCount,
aggregate.ConsumedDurationMilliseconds,
creatorName));
continue;
}
// A deleted or inaccessible item keeps its counts and duration, because the sessions were really consumed, but its display data is blank.
items.Add(new ConsumedItemDto(
aggregate.MediaKind,
aggregate.MediaItemId,
aggregate.LibraryId,
false,
string.Empty,
string.Empty,
string.Empty,
null,
aggregate.LastConsumedOnUtc,
aggregate.CountedSessionCount,
aggregate.CompletedSessionCount,
aggregate.ConsumedDurationMilliseconds));
}
return items;
}
/// <summary>
/// The aggregated consumption of one media item in one library.
/// </summary>
/// <param name="MediaKind">The kind of the consumed media item.</param>
/// <param name="MediaItemId">The Id of the consumed media item.</param>
/// <param name="LibraryId">The Id of the media library that contains the media item.</param>
/// <param name="LastConsumedOnUtc">The date and time when the media item was last consumed.</param>
/// <param name="CountedSessionCount">The number of sessions that count towards statistics.</param>
/// <param name="CompletedSessionCount">The number of sessions that completed.</param>
/// <param name="ConsumedDurationMilliseconds">The active duration consumed in the media item, over all of its sessions, in milliseconds.</param>
private sealed record ConsumedItemAggregate(
MediaKind MediaKind,
Guid MediaItemId,
Guid LibraryId,
DateTime LastConsumedOnUtc,
int CountedSessionCount,
int CompletedSessionCount,
long ConsumedDurationMilliseconds
);
}
@@ -0,0 +1,41 @@
#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.Queries.GetMostConsumed;
/// <summary>
/// Validates the needed validation rules for <see cref="GetMostConsumedQuery"/>.
/// </summary>
public class GetMostConsumedQueryValidator : AbstractValidator<GetMostConsumedQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetMostConsumedQueryValidator"/> class.
/// </summary>
public GetMostConsumedQueryValidator()
{
// The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id.
RuleFor(query => query.TargetUserId)
.Must(targetUserId => targetUserId is null ||
(Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty))
.WithError(Errors.MediaConsumption.TargetUserIdIsInvalid);
RuleFor(query => query.LibraryId)
.Must(libraryId => libraryId is null ||
(Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty))
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(query => query.MediaKind)
.IsInEnum()
.WithError(Errors.MediaConsumption.UnsupportedMediaKind)
.When(query => query.MediaKind is not null);
RuleFor(query => query.MediaKind)
.Must(mediaKind => mediaKind is null || mediaKind != MediaKind.None)
.WithError(Errors.MediaConsumption.UnsupportedMediaKind);
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed;
/// <summary>
/// Query for getting the recently consumed media items of a user, from the most recently consumed.
/// </summary>
/// <param name="TargetUserId">The Id of the user whose history is retrieved, or <see langword="null"/> for the current user.</param>
/// <param name="LibraryId">The Id of the media library to restrict the history to, or <see langword="null"/> for every library.</param>
/// <param name="MediaKind">The kind of media to restrict the history to, or <see langword="null"/> for every kind.</param>
/// <param name="PaginationData">The object containing the requested pagination data. When <see langword="null"/>, every matching item is returned; when present, its requested page is returned.</param>
[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")]
public record GetRecentlyConsumedQuery(
string? TargetUserId,
string? LibraryId,
MediaKind? MediaKind,
PaginationDataDto? PaginationData
) : IQuery;
@@ -0,0 +1,342 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Entities.MediaContributors;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Application.Common.DTO.Pagination;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity;
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.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Application.Common.Mapping.MediaLibrary.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.Common;
using Lumina.Contracts.Responses.MediaConsumption;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed;
/// <summary>
/// Handler for the query to get the recently consumed media items of a user.
/// </summary>
public class GetRecentlyConsumedQueryHandler : IQueryHandler<GetRecentlyConsumedQuery, Result<PaginatedResponse<ConsumedItemResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<GetRecentlyConsumedQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetRecentlyConsumedQueryHandler"/> 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="validator">Injected validator for application validation rules.</param>
public GetRecentlyConsumedQueryHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IValidator<GetRecentlyConsumedQuery> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the recently consumed media items of a user.
/// </summary>
/// <param name="query">The query 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 requested page of recently consumed media items, or an error message.
/// </returns>
public async Task<Result<PaginatedResponse<ConsumedItemResponse>>> HandleAsync(GetRecentlyConsumedQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
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 target defaults to the current user, and the access policy is the only place that decides whether the caller may read it.
Guid targetUserId = query.TargetUserId is null ? userId : Guid.Parse(query.TargetUserId);
bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false);
if (!canAccessTarget)
return ApplicationErrors.Authorization.NotAuthorized;
Guid? libraryId = query.LibraryId is null ? null : Guid.Parse(query.LibraryId);
Result<IReadOnlyList<MediaConsumptionRecordEntity>> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository
.GetForUserAsync(targetUserId, libraryId, query.MediaKind, fromUtc: null, toUtc: null, cancellationToken).ConfigureAwait(false);
if (getRecordsResult.IsFailure)
return getRecordsResult.Errors;
// The sessions are reduced to one row per media item before ordering and pagination, so an item consumed many times appears once.
List<ConsumedItemAggregate> orderedAggregates = [.. BuildAggregates(getRecordsResult.Value)
.OrderByDescending(aggregate => aggregate.LastConsumedOnUtc)
.ThenBy(aggregate => aggregate.MediaKind)
.ThenBy(aggregate => aggregate.MediaItemId)
.ThenBy(aggregate => aggregate.LibraryId)];
PaginatedResultDto<ConsumedItemDto> page;
if (query.PaginationData is null)
{
// Without pagination the caller asked for every matching item, which is bounded by the number of distinct items in the history.
Result<List<ConsumedItemDto>> getItemsResult = await ToConsumedItemDtosAsync(orderedAggregates, userId, cancellationToken).ConfigureAwait(false);
if (getItemsResult.IsFailure)
return getItemsResult.Errors;
page = new PaginatedResultDto<ConsumedItemDto>
{
Data = getItemsResult.Value,
CurrentPage = 1,
PerPage = orderedAggregates.Count,
Count = orderedAggregates.Count,
NumberOfPages = 1
};
}
else
{
int currentPage = query.PaginationData.CurrentPage;
int perPage = query.PaginationData.PerPage;
int count = orderedAggregates.Count;
int numberOfPages = (int)Math.Ceiling((double)count / perPage);
int pageNumber = Math.Min(currentPage, Math.Max(1, numberOfPages));
List<ConsumedItemAggregate> pageAggregates = [.. orderedAggregates
.Skip((pageNumber - 1) * perPage)
.Take(perPage)];
Result<List<ConsumedItemDto>> getItemsResult = await ToConsumedItemDtosAsync(pageAggregates, userId, cancellationToken).ConfigureAwait(false);
if (getItemsResult.IsFailure)
return getItemsResult.Errors;
page = new PaginatedResultDto<ConsumedItemDto>
{
Data = getItemsResult.Value,
CurrentPage = pageNumber,
PerPage = perPage,
Count = count,
NumberOfPages = numberOfPages
};
}
return Result.From(page.ToResponses());
}
/// <summary>
/// Aggregates the consumption records of each media item into the counts and duration that the history lists show.
/// </summary>
/// <param name="records">The consumption records of the user, already filtered by the query.</param>
/// <returns>One aggregate per media item, library, and media kind.</returns>
private static List<ConsumedItemAggregate> BuildAggregates(IReadOnlyList<MediaConsumptionRecordEntity> records)
{
List<ConsumedItemAggregate> aggregates = [];
foreach (IGrouping<(MediaKind MediaKind, Guid MediaItemId, Guid LibraryId), MediaConsumptionRecordEntity> itemGroup in records
.GroupBy(record => (record.MediaKind, record.MediaItemId, record.LibraryId)))
{
// Counted sessions follow the rule of the media kind, while the completed count is the subset that completed. Duration totals every
// session of the item, because it measures consumed time, not only the sessions that count.
Optional<MediaConsumptionRule> ruleResult = MediaConsumptionRule.For(itemGroup.Key.MediaKind);
int countedSessionCount = 0;
int completedSessionCount = 0;
long consumedDurationMilliseconds = 0;
DateTime lastConsumedOnUtc = DateTime.MinValue;
foreach (MediaConsumptionRecordEntity record in itemGroup)
{
consumedDurationMilliseconds += record.ConsumedDurationMilliseconds;
if (record.LastActivityOnUtc > lastConsumedOnUtc)
lastConsumedOnUtc = record.LastActivityOnUtc;
if (record.Status == ConsumptionStatus.Completed)
completedSessionCount++;
if (ruleResult.HasValue &&
ruleResult.Value.Counts(record.Status, record.ConsumedDurationMilliseconds.ToClampedTimeSpan(), record.ConsecutivePagesRead))
countedSessionCount++;
}
aggregates.Add(new ConsumedItemAggregate(
itemGroup.Key.MediaKind,
itemGroup.Key.MediaItemId,
itemGroup.Key.LibraryId,
lastConsumedOnUtc,
countedSessionCount,
completedSessionCount,
consumedDurationMilliseconds));
}
return aggregates;
}
/// <summary>
/// Resolves the display data of the media items of <paramref name="aggregates"/> and builds their DTOs.
/// </summary>
/// <param name="aggregates">The aggregated history rows of the requested page.</param>
/// <param name="currentUserId">The Id of the current user, used to decide which library display data may be shown.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The history rows, with blank display data for missing or inaccessible items.</returns>
private async Task<Result<List<ConsumedItemDto>>> ToConsumedItemDtosAsync(List<ConsumedItemAggregate> aggregates, Guid currentUserId, CancellationToken cancellationToken)
{
if (aggregates.Count == 0)
return new List<ConsumedItemDto>();
// The access decision only needs the library Id that the record already carries, so it is made once per distinct library before any item
// or artwork is loaded. Inaccessible items keep their counts and duration, but their display data is never read.
Dictionary<Guid, bool> libraryAccess = [];
foreach (Guid libraryId in aggregates.Select(aggregate => aggregate.LibraryId).Distinct())
libraryAccess[libraryId] = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
currentUserId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
List<Guid> trackIds = [.. aggregates
.Where(aggregate => aggregate.MediaKind == MediaKind.MusicTrack && libraryAccess[aggregate.LibraryId])
.Select(aggregate => aggregate.MediaItemId)
.Distinct()];
Dictionary<Guid, TrackEntity> tracks = [];
if (trackIds.Count > 0)
{
Result<IReadOnlyList<TrackEntity>> getTracksResult = await _unitOfWork.TrackRepository
.GetByIdsAsync(trackIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false);
if (getTracksResult.IsFailure)
return getTracksResult.Errors;
tracks = getTracksResult.Value.ToDictionary(track => track.Id);
}
List<Guid> albumIds = [.. tracks.Values.Select(track => track.AlbumId).Distinct()];
Dictionary<Guid, string?> albumCovers = [];
if (albumIds.Count > 0)
{
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository
.GetByOwnersAsync(MusicArtworkOwnerType.Album, albumIds, cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
albumCovers = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.GroupBy(artwork => artwork.OwnerId)
.ToDictionary(
group => group.Key,
group => group.OrderBy(artwork => artwork.Ordinal).Select(artwork => artwork.FileName).FirstOrDefault());
}
List<Guid> bookIds = [.. aggregates
.Where(aggregate => aggregate.MediaKind == MediaKind.Book && libraryAccess[aggregate.LibraryId])
.Select(aggregate => aggregate.MediaItemId)
.Distinct()];
Dictionary<Guid, BookEntity> books = [];
if (bookIds.Count > 0)
{
Result<IReadOnlyList<BookEntity>> getBooksResult = await _unitOfWork.BookRepository
.GetByIdsAsync(bookIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false);
if (getBooksResult.IsFailure)
return getBooksResult.Errors;
books = getBooksResult.Value.ToDictionary(book => book.Id);
}
List<Guid> authorIds = [.. books.Values
.SelectMany(book => book.Contributors
.Where(contributor => contributor.Role == MediaContributorRole.Author)
.Select(contributor => contributor.MediaContributorId))
.Distinct()];
Dictionary<Guid, string> authorNames = [];
if (authorIds.Count > 0)
{
Result<IReadOnlyList<MediaContributorEntity>> getAuthorsResult = await _unitOfWork.MediaContributorRepository
.GetByIdsAsync(authorIds, cancellationToken).ConfigureAwait(false);
if (getAuthorsResult.IsFailure)
return getAuthorsResult.Errors;
authorNames = getAuthorsResult.Value.ToDictionary(contributor => contributor.Id, contributor => contributor.DisplayName);
}
List<ConsumedItemDto> items = [];
foreach (ConsumedItemAggregate aggregate in aggregates)
{
if (aggregate.MediaKind == MediaKind.MusicTrack &&
libraryAccess[aggregate.LibraryId] &&
tracks.TryGetValue(aggregate.MediaItemId, out TrackEntity? track) &&
track.LibraryId == aggregate.LibraryId)
{
string? coverPath = albumCovers.TryGetValue(track.AlbumId, out string? coverFileName) ? coverFileName : null;
items.Add(track.ToDto(
aggregate.LastConsumedOnUtc,
aggregate.CountedSessionCount,
aggregate.CompletedSessionCount,
aggregate.ConsumedDurationMilliseconds,
coverPath));
continue;
}
if (aggregate.MediaKind == MediaKind.Book &&
libraryAccess[aggregate.LibraryId] &&
books.TryGetValue(aggregate.MediaItemId, out BookEntity? book) &&
book.LibraryId == aggregate.LibraryId)
{
string creatorName = book.Contributors
.Where(contributor => contributor.Role == MediaContributorRole.Author && authorNames.ContainsKey(contributor.MediaContributorId))
.Select(contributor => authorNames[contributor.MediaContributorId])
.OrderBy(name => name)
.FirstOrDefault() ?? string.Empty;
items.Add(book.ToDto(
aggregate.LastConsumedOnUtc,
aggregate.CountedSessionCount,
aggregate.CompletedSessionCount,
aggregate.ConsumedDurationMilliseconds,
creatorName));
continue;
}
// A deleted or inaccessible item keeps its counts and duration, because the sessions were really consumed, but its display data is blank.
items.Add(new ConsumedItemDto(
aggregate.MediaKind,
aggregate.MediaItemId,
aggregate.LibraryId,
false,
string.Empty,
string.Empty,
string.Empty,
null,
aggregate.LastConsumedOnUtc,
aggregate.CountedSessionCount,
aggregate.CompletedSessionCount,
aggregate.ConsumedDurationMilliseconds));
}
return items;
}
/// <summary>
/// The aggregated consumption of one media item in one library.
/// </summary>
/// <param name="MediaKind">The kind of the consumed media item.</param>
/// <param name="MediaItemId">The Id of the consumed media item.</param>
/// <param name="LibraryId">The Id of the media library that contains the media item.</param>
/// <param name="LastConsumedOnUtc">The date and time when the media item was last consumed.</param>
/// <param name="CountedSessionCount">The number of sessions that count towards statistics.</param>
/// <param name="CompletedSessionCount">The number of sessions that completed.</param>
/// <param name="ConsumedDurationMilliseconds">The active duration consumed in the media item, over all of its sessions, in milliseconds.</param>
private sealed record ConsumedItemAggregate(
MediaKind MediaKind,
Guid MediaItemId,
Guid LibraryId,
DateTime LastConsumedOnUtc,
int CountedSessionCount,
int CompletedSessionCount,
long ConsumedDurationMilliseconds
);
}
@@ -0,0 +1,41 @@
#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.Queries.GetRecentlyConsumed;
/// <summary>
/// Validates the needed validation rules for <see cref="GetRecentlyConsumedQuery"/>.
/// </summary>
public class GetRecentlyConsumedQueryValidator : AbstractValidator<GetRecentlyConsumedQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetRecentlyConsumedQueryValidator"/> class.
/// </summary>
public GetRecentlyConsumedQueryValidator()
{
// The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id.
RuleFor(query => query.TargetUserId)
.Must(targetUserId => targetUserId is null ||
(Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty))
.WithError(Errors.MediaConsumption.TargetUserIdIsInvalid);
RuleFor(query => query.LibraryId)
.Must(libraryId => libraryId is null ||
(Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty))
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(query => query.MediaKind)
.IsInEnum()
.WithError(Errors.MediaConsumption.UnsupportedMediaKind)
.When(query => query.MediaKind is not null);
RuleFor(query => query.MediaKind)
.Must(mediaKind => mediaKind is null || mediaKind != MediaKind.None)
.WithError(Errors.MediaConsumption.UnsupportedMediaKind);
}
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Queries.GetResumePoint;
/// <summary>
/// Query for getting the resume point of the current user for a media item.
/// </summary>
/// <param name="MediaKind">The kind of media to resume, taken from the route.</param>
/// <param name="MediaItemId">The Id of the media item to resume, taken from the route.</param>
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
public record GetResumePointQuery(
string? MediaKind,
string? MediaItemId
) : IQuery;
@@ -0,0 +1,133 @@
#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.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
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.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
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.Queries.GetResumePoint;
/// <summary>
/// Handler for the query to get the resume point of the current user for a media item.
/// </summary>
public class GetResumePointQueryHandler : IQueryHandler<GetResumePointQuery, Result<ResumePointResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IValidator<GetResumePointQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetResumePointQueryHandler"/> 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="validator">Injected validator for application validation rules.</param>
public GetResumePointQueryHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IValidator<GetResumePointQuery> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the resume point of the current user for a media item.
/// </summary>
/// <param name="query">The query 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 requested <see cref="ResumePointResponse"/>, or an error message.
/// </returns>
public async Task<Result<ResumePointResponse>> HandleAsync(GetResumePointQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
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 media kind is a defined value and the media item identifier is a non-empty Guid before this point.
MediaKind mediaKind = Enum.Parse<MediaKind>(query.MediaKind!, ignoreCase: true);
Guid mediaItemId = Guid.Parse(query.MediaItemId!);
Optional<MediaConsumptionRule> ruleResult = MediaConsumptionRule.For(mediaKind);
if (!ruleResult.HasValue)
return DomainErrors.MediaConsumption.UnsupportedMediaKind;
if (!ruleResult.Value.CanResume)
return DomainErrors.MediaConsumption.MediaKindCannotResume;
// The resume point is read without tracking and scoped to the current user, so a resume point of another user is indistinguishable from a missing one.
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 null)
return DomainErrors.MediaConsumption.MediaResumePointNotFound;
// The media item must still exist in the library the resume point was recorded in. A resume point whose item was deleted, or whose item no
// longer belongs to that library, is an orphan, so it is removed before the same not-found result as a missing item is returned.
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 != getResumePointResult.Value.LibraryId)
{
Result<Deleted> deleteResult = await _unitOfWork.MediaResumePointRepository.DeleteForUserAndMediaItemAsync(userId, mediaKind, mediaItemId, cancellationToken).ConfigureAwait(false);
if (deleteResult.IsFailure)
return deleteResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// Another request may have deleted the same orphan between the delete and this save. That race is the desired outcome, so a
// concurrency conflict is treated as success; any other persistence failure is still returned.
if (saveChangesResult.IsFailure && !saveChangesResult.Errors.Any(error => error == ApplicationErrors.Persistence.ConcurrencyConflict))
return saveChangesResult.Errors;
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 != getResumePointResult.Value.LibraryId)
{
Result<Deleted> deleteResult = await _unitOfWork.MediaResumePointRepository.DeleteForUserAndMediaItemAsync(userId, mediaKind, mediaItemId, cancellationToken).ConfigureAwait(false);
if (deleteResult.IsFailure)
return deleteResult.Errors;
Result<Success> saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
// Another request may have deleted the same orphan between the delete and this save. That race is the desired outcome, so a
// concurrency conflict is treated as success; any other persistence failure is still returned.
if (saveChangesResult.IsFailure && !saveChangesResult.Errors.Any(error => error == ApplicationErrors.Persistence.ConcurrencyConflict))
return saveChangesResult.Errors;
return DomainErrors.WrittenContent.BookNotFound;
}
}
else
return DomainErrors.MediaConsumption.UnsupportedMediaKind;
return getResumePointResult.Value.ToDto().ToResponse();
}
}
@@ -0,0 +1,41 @@
#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.Queries.GetResumePoint;
/// <summary>
/// Validates the needed validation rules for <see cref="GetResumePointQuery"/>.
/// </summary>
public class GetResumePointQueryValidator : AbstractValidator<GetResumePointQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetResumePointQueryValidator"/> class.
/// </summary>
public GetResumePointQueryValidator()
{
// Validates the kind of media to resume, taken from the route.
RuleFor(query => query.MediaKind)
.NotEmpty()
.WithError(Errors.MediaConsumption.UnsupportedMediaKind);
RuleFor(query => query.MediaKind)
.Must(mediaKind => Enum.TryParse(mediaKind, ignoreCase: true, out MediaKind parsedMediaKind) && Enum.IsDefined(parsedMediaKind))
.When(query => query.MediaKind is not null && query.MediaKind.Length > 0)
.WithError(Errors.MediaConsumption.UnsupportedMediaKind);
// Validates the identifier of the media item to resume, taken from the route.
RuleFor(query => query.MediaItemId)
.NotEmpty()
.WithError(Errors.MediaConsumption.MediaItemIdCannotBeEmpty);
RuleFor(query => query.MediaItemId)
.Must(mediaItemId => Guid.TryParse(mediaItemId, out Guid parsedMediaItemId) && parsedMediaItemId != Guid.Empty)
.When(query => query.MediaItemId is not null && query.MediaItemId.Length > 0)
.WithError(Errors.MediaConsumption.MediaItemIdCannotBeEmpty);
}
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.CQRS;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption;
/// <summary>
/// Query for getting the consumption statistics of the tags and genres of a user.
/// </summary>
/// <param name="TargetUserId">The Id of the user whose statistics are retrieved, or <see langword="null"/> for the current user.</param>
/// <param name="LibraryId">The Id of the media library to restrict the statistics to, or <see langword="null"/> for every library.</param>
/// <param name="MediaKind">The kind of media to restrict the statistics to, or <see langword="null"/> for every kind.</param>
/// <param name="TagKind">Whether to return genres or tags, or <see langword="null"/> for both.</param>
/// <param name="FromUtc">The inclusive start of the date range, or <see langword="null"/> when the range has no start.</param>
/// <param name="ToUtc">The inclusive end of the date range, or <see langword="null"/> when the range has no end.</param>
[DebuggerDisplay("TargetUserId: {TargetUserId}; TagKind: {TagKind}")]
public record GetTagConsumptionQuery(
string? TargetUserId,
string? LibraryId,
MediaKind? MediaKind,
TagKind? TagKind,
DateTime? FromUtc,
DateTime? ToUtc
) : IQuery;
@@ -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.AudioLibrary.MusicLibrary;
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.WrittenContentLibrary.BookLibrary;
using Lumina.Application.Common.DataAccess.UoW;
using Lumina.Application.Common.DTO.MediaConsumption;
using Lumina.Application.Common.Infrastructure.Authentication;
using Lumina.Application.Common.Infrastructure.Authorization;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.ConsumptionActivity;
using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
using Lumina.Application.Common.Infrastructure.Validation;
using Lumina.Application.Common.Mapping.MediaConsumption;
using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.MediaConsumption;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MediaConsumptionBoundedContext.Common.ValueObjects;
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption;
/// <summary>
/// Handler for the query to get the consumption statistics of the tags and genres of a user.
/// </summary>
public class GetTagConsumptionQueryHandler : IQueryHandler<GetTagConsumptionQuery, Result<IReadOnlyList<TagConsumptionResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
private readonly IValidator<GetTagConsumptionQuery> _validator;
/// <summary>
/// Initializes a new instance of the <see cref="GetTagConsumptionQueryHandler"/> 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="validator">Injected validator for application validation rules.</param>
public GetTagConsumptionQueryHandler(
IUnitOfWork unitOfWork,
ICurrentUserService currentUserService,
IAuthorizationService authorizationService,
IValidator<GetTagConsumptionQuery> validator)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
_validator = validator;
}
/// <summary>
/// Handles the query to get the consumption statistics of the tags and genres of a user.
/// </summary>
/// <param name="query">The query 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 requested tag and genre statistics, or an error message.
/// </returns>
public async Task<Result<IReadOnlyList<TagConsumptionResponse>>> HandleAsync(GetTagConsumptionQuery query, CancellationToken cancellationToken)
{
List<Error> validationResult = _validator.Validate(query);
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 target defaults to the current user, and the access policy is the only place that decides whether the caller may read it.
Guid targetUserId = query.TargetUserId is null ? userId : Guid.Parse(query.TargetUserId);
bool canAccessTarget = await _authorizationService.EvaluatePolicyAsync<IConsumptionActivityAccessPolicy>(
userId, new ConsumptionActivityAccessPolicyContext(targetUserId), cancellationToken).ConfigureAwait(false);
if (!canAccessTarget)
return ApplicationErrors.Authorization.NotAuthorized;
Guid? libraryId = query.LibraryId is null ? null : Guid.Parse(query.LibraryId);
Result<IReadOnlyList<MediaConsumptionRecordEntity>> getRecordsResult = await _unitOfWork.ConsumptionStatisticsRepository
.GetForUserAsync(targetUserId, libraryId, query.MediaKind, query.FromUtc, query.ToUtc, cancellationToken).ConfigureAwait(false);
if (getRecordsResult.IsFailure)
return getRecordsResult.Errors;
// The access decision only needs the library Id that the records already carry, so it is made once per distinct library before any term is
// loaded. Terms of a library the caller cannot access are never read.
Dictionary<Guid, bool> libraryAccess = [];
foreach (Guid recordLibraryId in getRecordsResult.Value.Select(record => record.LibraryId).Distinct())
libraryAccess[recordLibraryId] = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(recordLibraryId), cancellationToken).ConfigureAwait(false);
// Only the distinct item Ids of each kind in accessible libraries are read, through the catalogue repositories, in bounded chunks.
List<Guid> trackIds = [.. getRecordsResult.Value
.Where(record => record.MediaKind == MediaKind.MusicTrack && libraryAccess[record.LibraryId])
.Select(record => record.MediaItemId)
.Distinct()];
List<TrackEntity> tracks = [];
if (trackIds.Count > 0)
{
Result<IReadOnlyList<TrackEntity>> getTracksResult = await _unitOfWork.TrackRepository
.GetByIdsAsync(trackIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false);
if (getTracksResult.IsFailure)
return getTracksResult.Errors;
tracks = [.. getTracksResult.Value];
}
List<Guid> bookIds = [.. getRecordsResult.Value
.Where(record => record.MediaKind == MediaKind.Book && libraryAccess[record.LibraryId])
.Select(record => record.MediaItemId)
.Distinct()];
List<BookEntity> books = [];
if (bookIds.Count > 0)
{
Result<IReadOnlyList<BookEntity>> getBooksResult = await _unitOfWork.BookRepository
.GetByIdsAsync(bookIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false);
if (getBooksResult.IsFailure)
return getBooksResult.Errors;
books = [.. getBooksResult.Value];
}
Dictionary<(MediaKind MediaKind, Guid MediaItemId, Guid LibraryId), List<(TagKind TagKind, string Name)>> termsByItem = [];
foreach (TrackEntity track in tracks)
{
List<(TagKind TagKind, string Name)> itemTerms = [];
itemTerms.AddRange(track.Tags.Select(tag => tag.Name).OfType<string>().Select(name => (TagKind.Tag, name)));
itemTerms.AddRange(track.Genres.Select(genre => genre.Name).OfType<string>().Select(name => (TagKind.Genre, name)));
if (itemTerms.Count > 0)
termsByItem[(MediaKind.MusicTrack, track.Id, track.LibraryId)] = itemTerms;
}
foreach (BookEntity book in books)
{
List<(TagKind TagKind, string Name)> itemTerms = [];
itemTerms.AddRange(book.Tags.Select(tag => tag.Name).OfType<string>().Select(name => (TagKind.Tag, name)));
itemTerms.AddRange(book.Genres.Select(genre => genre.Name).OfType<string>().Select(name => (TagKind.Genre, name)));
if (itemTerms.Count > 0)
termsByItem[(MediaKind.Book, book.Id, book.LibraryId)] = itemTerms;
}
// The records are aggregated to one row per item and library first, so an item with several sessions contributes its terms once, not once per
// session. The library is part of the key because the item is resolved in its current library, and a record from another library must not
// borrow the terms or the access decision of the current one. An item that moved libraries after consumption is therefore excluded from the
// breakdown, matching the history lists that blank display data when the record and item libraries disagree.
Dictionary<(TagKind TagKind, string Name), (int ConsumedItemCount, long ConsumedDurationMilliseconds)> terms = [];
foreach (IGrouping<(MediaKind MediaKind, Guid MediaItemId, Guid LibraryId), MediaConsumptionRecordEntity> itemGroup in getRecordsResult.Value
.GroupBy(record => (record.MediaKind, record.MediaItemId, record.LibraryId)))
{
if (!libraryAccess[itemGroup.Key.LibraryId])
continue;
if (!termsByItem.TryGetValue((itemGroup.Key.MediaKind, itemGroup.Key.MediaItemId, itemGroup.Key.LibraryId), out List<(TagKind TagKind, string Name)>? itemTerms) ||
itemTerms.Count == 0)
continue;
// The breakdown mirrors the statistics, so an item whose sessions all fall below the counting threshold of their media kind does not
// contribute its terms or its duration to the breakdown.
Optional<MediaConsumptionRule> ruleResult = MediaConsumptionRule.For(itemGroup.Key.MediaKind);
if (!ruleResult.HasValue)
continue;
bool hasCountedSession = itemGroup.Any(record => ruleResult.Value.Counts(
record.Status,
record.ConsumedDurationMilliseconds.ToClampedTimeSpan(),
record.ConsecutivePagesRead));
if (!hasCountedSession)
continue;
long consumedDurationMilliseconds = itemGroup.Sum(record => record.ConsumedDurationMilliseconds);
if (query.TagKind is null || query.TagKind == TagKind.Tag)
{
List<string> tagNames = [.. itemTerms
.Where(termRow => termRow.TagKind == TagKind.Tag)
.Select(termRow => termRow.Name)];
AddTerms(terms, TagKind.Tag, tagNames, consumedDurationMilliseconds);
}
if (query.TagKind is null || query.TagKind == TagKind.Genre)
{
List<string> genreNames = [.. itemTerms
.Where(termRow => termRow.TagKind == TagKind.Genre)
.Select(termRow => termRow.Name)];
AddTerms(terms, TagKind.Genre, genreNames, consumedDurationMilliseconds);
}
}
List<TagConsumptionDto> tagConsumptions = [.. terms
.Select(term => new TagConsumptionDto(
term.Key.Name,
term.Key.TagKind,
term.Value.ConsumedItemCount,
term.Value.ConsumedDurationMilliseconds))
.OrderByDescending(tagConsumption => tagConsumption.ConsumedItemCount)
.ThenByDescending(tagConsumption => tagConsumption.ConsumedDurationMilliseconds)
.ThenBy(tagConsumption => tagConsumption.TagKind)
.ThenBy(tagConsumption => tagConsumption.Name)];
return Result.From(tagConsumptions.ToResponses());
}
/// <summary>
/// Adds the lowercase <paramref name="names"/> of one item to the accumulated <paramref name="terms"/>.
/// </summary>
/// <param name="terms">The accumulated terms, keyed by tag kind and lowercase name.</param>
/// <param name="tagKind">Whether the names are tags or genres.</param>
/// <param name="names">The names carried by the item.</param>
/// <param name="consumedDurationMilliseconds">The duration consumed in the item, over all of its sessions, in milliseconds.</param>
private static void AddTerms(
Dictionary<(TagKind TagKind, string Name), (int ConsumedItemCount, long ConsumedDurationMilliseconds)> terms,
TagKind tagKind,
List<string> names,
long consumedDurationMilliseconds)
{
// The item is aggregated to one row, so each distinct lowercase name of the item is counted once, regardless of how many sessions it had.
foreach (string name in names.Select(name => name.Trim().ToLowerInvariant()).Distinct())
{
if (name.Length == 0)
continue;
(TagKind TagKind, string Name) key = (tagKind, name);
if (terms.TryGetValue(key, out (int ConsumedItemCount, long ConsumedDurationMilliseconds) current))
terms[key] = (current.ConsumedItemCount + 1, current.ConsumedDurationMilliseconds + consumedDurationMilliseconds);
else
terms[key] = (1, consumedDurationMilliseconds);
}
}
}
@@ -0,0 +1,52 @@
#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 Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
#endregion
namespace Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption;
/// <summary>
/// Validates the needed validation rules for <see cref="GetTagConsumptionQuery"/>.
/// </summary>
public class GetTagConsumptionQueryValidator : AbstractValidator<GetTagConsumptionQuery>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetTagConsumptionQueryValidator"/> class.
/// </summary>
public GetTagConsumptionQueryValidator()
{
// The target defaults to the current user, so an absent target is valid, but a supplied one must be a real user Id.
RuleFor(query => query.TargetUserId)
.Must(targetUserId => targetUserId is null ||
(Guid.TryParse(targetUserId, out Guid parsedTargetUserId) && parsedTargetUserId != Guid.Empty))
.WithError(Errors.MediaConsumption.TargetUserIdIsInvalid);
RuleFor(query => query.LibraryId)
.Must(libraryId => libraryId is null ||
(Guid.TryParse(libraryId, out Guid parsedLibraryId) && parsedLibraryId != Guid.Empty))
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
RuleFor(query => query.MediaKind)
.IsInEnum()
.WithError(Errors.MediaConsumption.UnsupportedMediaKind)
.When(query => query.MediaKind is not null);
RuleFor(query => query.MediaKind)
.Must(mediaKind => mediaKind is null || mediaKind != MediaKind.None)
.WithError(Errors.MediaConsumption.UnsupportedMediaKind);
RuleFor(query => query.TagKind)
.IsInEnum()
.WithError(Errors.MediaConsumption.TagKindIsInvalid)
.When(query => query.TagKind is not null);
// An inverted range would silently return no records, so it is rejected as an invalid request instead.
RuleFor(query => query.FromUtc)
.Must((query, fromUtc) => !fromUtc.HasValue || !query.ToUtc.HasValue || fromUtc.Value <= query.ToUtc.Value)
.WithError(Errors.MediaConsumption.ConsumptionDateRangeIsInvalid);
}
}
@@ -0,0 +1,17 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.MediaConsumption;
/// <summary>
/// Represents the consumption statistics of every user, together with their combined totals.
/// </summary>
/// <param name="Total">The combined consumption statistics of every user.</param>
/// <param name="Users">The consumption statistics of each user.</param>
[DebuggerDisplay("UserCount: {Users.Count}; CountedSessionCount: {Total.CountedSessionCount}")]
public sealed record AllUsersConsumptionStatisticsResponse(
ConsumptionTotalsResponse Total,
IReadOnlyList<ConsumptionSummaryResponse> Users
);
@@ -0,0 +1,25 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.MediaConsumption;
/// <summary>
/// Represents the combined consumption statistics of every user.
/// </summary>
/// <param name="TotalConsumedDurationInSeconds">The total duration consumed over every recorded session of every user, in seconds.</param>
/// <param name="CountedSessionCount">The number of recorded sessions of every user that count towards statistics.</param>
/// <param name="CompletedSessionCount">The number of recorded sessions of every user that completed.</param>
/// <param name="StoppedSessionCount">The number of recorded sessions of every user that stopped before they completed and count towards statistics.</param>
/// <param name="CompletionRate">The fraction of the counted sessions of every user that completed, between 0 and 1, or 0 when there is no counted session.</param>
/// <param name="MediaKindSummaries">The combined consumption statistics broken down by media kind.</param>
[DebuggerDisplay("CountedSessionCount: {CountedSessionCount}; CompletedSessionCount: {CompletedSessionCount}")]
public sealed record ConsumptionTotalsResponse(
double TotalConsumedDurationInSeconds,
int CountedSessionCount,
int CompletedSessionCount,
int StoppedSessionCount,
double CompletionRate,
IReadOnlyList<MediaKindConsumptionSummaryResponse> MediaKindSummaries
);
@@ -484,20 +484,57 @@ internal sealed class BookRepository : IBookRepository
/// <returns>An <see cref="Result{TValue}"/> containing either the display names of the authors of the books, keyed by book Id, or an error.</returns>
public async Task<Result<IReadOnlyDictionary<Guid, string?>>> GetAuthorsDisplayNamesByBookIdsAsync(IReadOnlyCollection<Guid> bookIds, CancellationToken cancellationToken)
{
List<AuthorRow> authorRows = await _luminaDbContext.BookContributors
.Where(bookContributor => bookIds.Contains(bookContributor.BookId) && bookContributor.Role == MediaContributorRole.Author)
.Join(_luminaDbContext.MediaContributors,
bookContributor => bookContributor.MediaContributorId,
contributor => contributor.Id,
(bookContributor, contributor) => new AuthorRow(bookContributor.BookId, contributor.DisplayName))
.ToListAsync(cancellationToken)
.ConfigureAwait(false);
List<AuthorRow> authorRows = [];
// The lookup is split into bounded chunks, so an unpaginated history never exceeds the storage parameter limit.
const int LOOKUP_CHUNK_SIZE = 500;
foreach (Guid[] chunk in bookIds.Chunk(LOOKUP_CHUNK_SIZE))
{
authorRows.AddRange(await _luminaDbContext.BookContributors
.Where(bookContributor => chunk.Contains(bookContributor.BookId) && bookContributor.Role == MediaContributorRole.Author)
.Join(_luminaDbContext.MediaContributors,
bookContributor => bookContributor.MediaContributorId,
contributor => contributor.Id,
(bookContributor, contributor) => new AuthorRow(bookContributor.BookId, contributor.DisplayName))
.ToListAsync(cancellationToken)
.ConfigureAwait(false));
}
return authorRows
.GroupBy(row => row.BookId)
.ToDictionary(group => group.Key, group => group.Min(row => row.DisplayName));
}
/// <summary>
/// Gets the books identified by <paramref name="bookIds"/>, optionally together with their navigation properties.
/// </summary>
/// <param name="bookIds">The Ids of the books to get.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the books should be loaded together with the books themselves.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the existing books, or an error.</returns>
public async Task<Result<IReadOnlyList<BookEntity>>> GetByIdsAsync(IReadOnlyCollection<Guid> bookIds, bool shouldIncludeNavigationProperties, CancellationToken cancellationToken)
{
List<BookEntity> books = [];
// The lookup is split into bounded chunks, so even an unpaginated history never exceeds the storage parameter limit.
const int LOOKUP_CHUNK_SIZE = 500;
foreach (Guid[] chunk in bookIds.Chunk(LOOKUP_CHUNK_SIZE))
{
IQueryable<BookEntity> query = _luminaDbContext.Books.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
query = query
.Include(book => book.Tags)
.Include(book => book.Genres)
.Include(book => book.ISBNs)
.Include(book => book.Ratings)
.Include(book => book.Contributors)
.Include(book => book.Artwork)
.AsSplitQuery();
}
books.AddRange(await query.Where(book => chunk.Contains(book.Id)).ToListAsync(cancellationToken).ConfigureAwait(false));
}
return Result.From<IReadOnlyList<BookEntity>>(books);
}
/// <summary>
/// The author row of a book, joining the participation of an author contributor in a book with the display name of the contributor.
/// </summary>
@@ -0,0 +1,102 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
using Lumina.Application.Common.DataAccess.Repositories.MediaConsumption;
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 the consumption records used to build consumption statistics.
/// </summary>
/// <remarks>
/// The repository only binds the filters and returns the records. Counting, grouping, ordering, display data resolution, and mapping stay in the
/// application handlers, so the same records can serve the summary, the history lists, the all-users summary, and the tag breakdown.
/// </remarks>
internal sealed class ConsumptionStatisticsRepository : IConsumptionStatisticsRepository
{
private readonly LuminaDbContext _luminaDbContext;
/// <summary>
/// Initializes a new instance of the <see cref="ConsumptionStatisticsRepository"/> class.
/// </summary>
/// <param name="luminaDbContext">Injected Entity Framework DbContext.</param>
public ConsumptionStatisticsRepository(LuminaDbContext luminaDbContext)
{
_luminaDbContext = luminaDbContext;
}
/// <summary>
/// Gets the consumption records of the user identified by <paramref name="userId"/>, optionally limited to a media library, a media kind, and a date range.
/// </summary>
/// <param name="userId">The Id of the user whose consumption records are retrieved.</param>
/// <param name="libraryId">The Id of the media library to restrict the records to, or <see langword="null"/> for every library.</param>
/// <param name="mediaKind">The kind of media to restrict the records to, or <see langword="null"/> for every kind.</param>
/// <param name="fromUtc">The start of the date range, or <see langword="null"/> when the range has no start.</param>
/// <param name="toUtc">The end of the date range, or <see langword="null"/> when the range has no end.</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 records of the user, or an error.</returns>
public async Task<Result<IReadOnlyList<MediaConsumptionRecordEntity>>> GetForUserAsync(
Guid userId, Guid? libraryId, MediaKind? mediaKind, DateTime? fromUtc, DateTime? toUtc, CancellationToken cancellationToken)
{
// The user is part of the query rather than a check performed after the read, so the storage medium never returns a record of another user.
IQueryable<MediaConsumptionRecordEntity> query = _luminaDbContext.MediaConsumptionRecords
.AsNoTracking()
.Where(record => record.UserId == userId);
query = ApplyFilters(query, libraryId, mediaKind, fromUtc, toUtc);
List<MediaConsumptionRecordEntity> records = await query.ToListAsync(cancellationToken).ConfigureAwait(false);
return Result.From<IReadOnlyList<MediaConsumptionRecordEntity>>(records);
}
/// <summary>
/// Gets the consumption records of every user, optionally limited to a media library, a media kind, and a date range.
/// </summary>
/// <param name="libraryId">The Id of the media library to restrict the records to, or <see langword="null"/> for every library.</param>
/// <param name="mediaKind">The kind of media to restrict the records to, or <see langword="null"/> for every kind.</param>
/// <param name="fromUtc">The start of the date range, or <see langword="null"/> when the range has no start.</param>
/// <param name="toUtc">The end of the date range, or <see langword="null"/> when the range has no end.</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 records of every user, or an error.</returns>
public async Task<Result<IReadOnlyList<MediaConsumptionRecordEntity>>> GetForAllUsersAsync(
Guid? libraryId, MediaKind? mediaKind, DateTime? fromUtc, DateTime? toUtc, CancellationToken cancellationToken)
{
// This is the only query that is not scoped to one user, and it exists only for the explicit admin all-users summary.
IQueryable<MediaConsumptionRecordEntity> query = _luminaDbContext.MediaConsumptionRecords.AsNoTracking();
query = ApplyFilters(query, libraryId, mediaKind, fromUtc, toUtc);
List<MediaConsumptionRecordEntity> records = await query.ToListAsync(cancellationToken).ConfigureAwait(false);
return Result.From<IReadOnlyList<MediaConsumptionRecordEntity>>(records);
}
/// <summary>
/// Applies the optional library, media kind, and date range filters to <paramref name="query"/>.
/// </summary>
/// <param name="query">The query to filter.</param>
/// <param name="libraryId">The Id of the media library to restrict the records to, or <see langword="null"/> for every library.</param>
/// <param name="mediaKind">The kind of media to restrict the records to, or <see langword="null"/> for every kind.</param>
/// <param name="fromUtc">The start of the date range, or <see langword="null"/> when the range has no start.</param>
/// <param name="toUtc">The end of the date range, or <see langword="null"/> when the range has no end.</param>
/// <returns>The filtered query.</returns>
private static IQueryable<MediaConsumptionRecordEntity> ApplyFilters(
IQueryable<MediaConsumptionRecordEntity> query, Guid? libraryId, MediaKind? mediaKind, DateTime? fromUtc, DateTime? toUtc)
{
// Every filter is bound in the query, so the database never materializes rows that the caller did not ask for.
if (libraryId.HasValue)
query = query.Where(record => record.LibraryId == libraryId.Value);
if (mediaKind.HasValue)
query = query.Where(record => record.MediaKind == mediaKind.Value);
// The date range is applied to the start of the session, which is the indexed timestamp the statistics of a user are read by.
if (fromUtc.HasValue)
query = query.Where(record => record.StartedOnUtc >= fromUtc.Value);
if (toUtc.HasValue)
query = query.Where(record => record.StartedOnUtc <= toUtc.Value);
return query;
}
}
@@ -106,9 +106,16 @@ internal sealed class MediaContributorRepository : IMediaContributorRepository
/// <returns>An <see cref="Result{TValue}"/> containing either the retrieved <see cref="MediaContributorEntity"/>s, or an error.</returns>
public async Task<Result<IReadOnlyList<MediaContributorEntity>>> GetByIdsAsync(IReadOnlyCollection<Guid> ids, CancellationToken cancellationToken)
{
return await _luminaDbContext.MediaContributors
.Where(contributor => ids.Contains(contributor.Id))
.ToListAsync(cancellationToken)
.ConfigureAwait(false);
List<MediaContributorEntity> contributors = [];
// The lookup is split into bounded chunks, so an unpaginated history never exceeds the storage parameter limit.
const int LOOKUP_CHUNK_SIZE = 500;
foreach (Guid[] chunk in ids.Chunk(LOOKUP_CHUNK_SIZE))
{
contributors.AddRange(await _luminaDbContext.MediaContributors
.Where(contributor => chunk.Contains(contributor.Id))
.ToListAsync(cancellationToken)
.ConfigureAwait(false));
}
return Result.From<IReadOnlyList<MediaContributorEntity>>(contributors);
}
}
@@ -62,6 +62,30 @@ internal sealed class MusicArtworkRepository : IMusicArtworkRepository
return Result.From(artwork);
}
/// <summary>
/// Gets the pieces of artwork owned by the music library items of the provided <paramref name="ownerType"/> identified by any of <paramref name="ownerIds"/>.
/// </summary>
/// <param name="ownerType">The type of the music library items that own the artwork.</param>
/// <param name="ownerIds">The Ids of the music library items that own the artwork.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the artwork of the existing owners, or an error.</returns>
public async Task<Result<IReadOnlyList<MusicArtworkEntity>>> GetByOwnersAsync(MusicArtworkOwnerType ownerType, IReadOnlyCollection<Guid> ownerIds, CancellationToken cancellationToken)
{
List<MusicArtworkEntity> artwork = [];
// The lookup is split into bounded chunks, so a history page never exceeds the storage parameter limit.
const int LOOKUP_CHUNK_SIZE = 500;
foreach (Guid[] chunk in ownerIds.Chunk(LOOKUP_CHUNK_SIZE))
{
artwork.AddRange(await _luminaDbContext.MusicArtwork
.AsNoTracking()
.Where(musicArtwork => musicArtwork.OwnerType == ownerType && chunk.Contains(musicArtwork.OwnerId))
.OrderBy(musicArtwork => musicArtwork.ArtworkType)
.ThenBy(musicArtwork => musicArtwork.Ordinal)
.ToListAsync(cancellationToken).ConfigureAwait(false));
}
return Result.From<IReadOnlyList<MusicArtworkEntity>>(artwork);
}
/// <summary>
/// Deletes all the pieces of artwork owned by the music library item of the provided <paramref name="ownerType"/> identified by <paramref name="ownerId"/>.
/// </summary>
@@ -559,6 +559,39 @@ internal sealed class TrackRepository : ITrackRepository
return Result.From(new TrackAccessSummaryDto(trackCount, [.. libraryIds]));
}
/// <summary>
/// Gets the tracks identified by <paramref name="trackIds"/>, optionally together with their navigation properties.
/// </summary>
/// <param name="trackIds">The Ids of the tracks to get.</param>
/// <param name="shouldIncludeNavigationProperties">Whether the navigation properties of the tracks should be loaded together with the tracks themselves.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the existing tracks, or an error.</returns>
public async Task<Result<IReadOnlyList<TrackEntity>>> GetByIdsAsync(IReadOnlyCollection<Guid> trackIds, bool shouldIncludeNavigationProperties, CancellationToken cancellationToken)
{
List<TrackEntity> tracks = [];
// The lookup is split into bounded chunks, so even an unpaginated history never exceeds the storage parameter limit.
const int LOOKUP_CHUNK_SIZE = 500;
foreach (Guid[] chunk in trackIds.Chunk(LOOKUP_CHUNK_SIZE))
{
IQueryable<TrackEntity> query = _luminaDbContext.Tracks.AsNoTracking();
if (shouldIncludeNavigationProperties)
{
query = query
.Include(track => track.Album)
.ThenInclude(album => album!.Artist)
.Include(track => track.Ratings)
.Include(track => track.Tags)
.Include(track => track.Genres)
.Include(track => track.Moods)
.Include(track => track.Isrcs)
.Include(track => track.Contributors)
.AsSplitQuery();
}
tracks.AddRange(await query.Where(track => chunk.Contains(track.Id)).ToListAsync(cancellationToken).ConfigureAwait(false));
}
return Result.From<IReadOnlyList<TrackEntity>>(tracks);
}
/// <summary>
/// The number of requested tracks that exist in one library.
/// </summary>
@@ -75,6 +75,7 @@ public class UnitOfWork : IUnitOfWork, IDisposable
private IFavoriteRepository? _favoriteRepository;
private IMediaConsumptionRecordRepository? _mediaConsumptionRecordRepository;
private IMediaResumePointRepository? _mediaResumePointRepository;
private IConsumptionStatisticsRepository? _consumptionStatisticsRepository;
/// <summary>
/// Gets the permission repository.
@@ -445,6 +446,18 @@ public class UnitOfWork : IUnitOfWork, IDisposable
}
}
/// <summary>
/// Gets the repository for the consumption records used to build consumption statistics.
/// </summary>
public IConsumptionStatisticsRepository ConsumptionStatisticsRepository
{
get
{
_consumptionStatisticsRepository ??= new ConsumptionStatisticsRepository(_luminaDbContext);
return _consumptionStatisticsRepository;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="UnitOfWork"/> class.
/// </summary>
@@ -18,6 +18,9 @@ public static partial class Errors
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 TargetUserIdIsInvalid => Error.Validation(description: nameof(TargetUserIdIsInvalid));
public static Error TagKindIsInvalid => Error.Validation(description: nameof(TagKindIsInvalid));
public static Error ConsumptionDateRangeIsInvalid => Error.Validation(description: nameof(ConsumptionDateRangeIsInvalid));
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));