mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 06:11:10 +00:00
Adds the media-neutral library statistics page and separates tags from genres
This commit is contained in:
1 parent
a61fbf407c
commit
00d7eff777
118 files changed
+6132
-1154
No files matched your search
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the consumption statistics of a genre, grouped across media kinds.
|
||||
/// </summary>
|
||||
/// <param name="Name">The lowercase name of the genre.</param>
|
||||
/// <param name="ConsumedItemCount">The number of distinct media items that carry the genre and were consumed.</param>
|
||||
/// <param name="ConsumedDurationMilliseconds">The active duration consumed in the media items that carry the genre, in milliseconds.</param>
|
||||
[DebuggerDisplay("Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")]
|
||||
public sealed record GenreConsumptionDto(
|
||||
string Name,
|
||||
int ConsumedItemCount,
|
||||
long ConsumedDurationMilliseconds
|
||||
);
|
||||
@@ -1,21 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.DTO.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for the consumption statistics of a tag or genre, grouped across media kinds.
|
||||
/// Data transfer object for the consumption statistics of a tag, grouped across media kinds.
|
||||
/// </summary>
|
||||
/// <param name="Name">The lowercase name of the tag or genre.</param>
|
||||
/// <param name="TagKind">Whether the entry is a genre or a tag.</param>
|
||||
/// <param name="ConsumedItemCount">The number of distinct media items that carry the term and were consumed.</param>
|
||||
/// <param name="ConsumedDurationMilliseconds">The active duration consumed in the media items that carry the term, in milliseconds.</param>
|
||||
[DebuggerDisplay("TagKind: {TagKind}; Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")]
|
||||
/// <param name="Name">The lowercase name of the tag.</param>
|
||||
/// <param name="ConsumedItemCount">The number of distinct media items that carry the tag and were consumed.</param>
|
||||
/// <param name="ConsumedDurationMilliseconds">The active duration consumed in the media items that carry the tag, in milliseconds.</param>
|
||||
[DebuggerDisplay("Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")]
|
||||
public sealed record TagConsumptionDto(
|
||||
string Name,
|
||||
TagKind TagKind,
|
||||
int ConsumedItemCount,
|
||||
long ConsumedDurationMilliseconds
|
||||
);
|
||||
+12
@@ -3,6 +3,7 @@ using Lumina.Application.Common.DataAccess.Entities.MediaConsumption;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
|
||||
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
|
||||
using Lumina.Domain.Common.Primitives;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -49,6 +50,17 @@ public interface IMediaConsumptionRecordRepository : IRepository<MediaConsumptio
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful deletion, or an error.</returns>
|
||||
Task<Result<Deleted>> DeleteForUserAsync(Guid id, Guid userId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes every consumption record of a media item of the user identified by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
/// <param name="userId">The Id of the user whose consumption records are deleted.</param>
|
||||
/// <param name="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="cancellationToken">Cancellation token that can be used to stop the execution.</param>
|
||||
/// <returns>An <see cref="Result{TValue}"/> representing either a successful deletion, or an error.</returns>
|
||||
Task<Result<Deleted>> DeleteAllByMediaItemIdForUserAsync(Guid userId, MediaKind mediaKind, Guid mediaItemId, Guid libraryId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Deletes every consumption record of the user identified by <paramref name="userId"/>.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.DTO.MediaConsumption;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Contracts.Responses.MediaConsumption;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GenreConsumptionDto"/>.
|
||||
/// </summary>
|
||||
public static class GenreConsumptionDtoMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="data"/> to <see cref="GenreConsumptionResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="data">The data transfer object to be converted.</param>
|
||||
/// <returns>The converted response.</returns>
|
||||
public static GenreConsumptionResponse ToResponse(this GenreConsumptionDto data)
|
||||
{
|
||||
return new GenreConsumptionResponse(
|
||||
data.Name,
|
||||
data.ConsumedItemCount,
|
||||
data.ConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Converts <paramref name="data"/> to a collection of <see cref="GenreConsumptionResponse"/>.
|
||||
/// </summary>
|
||||
/// <param name="data">The data transfer objects to be converted.</param>
|
||||
/// <returns>The converted responses.</returns>
|
||||
public static IReadOnlyList<GenreConsumptionResponse> ToResponses(this IReadOnlyList<GenreConsumptionDto> data)
|
||||
{
|
||||
return [.. data.Select(item => item.ToResponse())];
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption;
|
||||
using Lumina.Contracts.Requests.MediaConsumption;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Common.Mapping.MediaConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Extension methods for converting <see cref="GetGenreConsumptionRequest"/>.
|
||||
/// </summary>
|
||||
public static class GetGenreConsumptionRequestMapping
|
||||
{
|
||||
/// <summary>
|
||||
/// Converts <paramref name="request"/> to <see cref="GetGenreConsumptionQuery"/>.
|
||||
/// </summary>
|
||||
/// <param name="request">The request to be converted.</param>
|
||||
/// <param name="targetUserId">The Id of the user whose statistics are retrieved, taken from the route, or <see langword="null"/> for the current user.</param>
|
||||
/// <returns>The converted query.</returns>
|
||||
public static GetGenreConsumptionQuery ToQuery(this GetGenreConsumptionRequest request, string? targetUserId)
|
||||
{
|
||||
return new GetGenreConsumptionQuery(
|
||||
targetUserId,
|
||||
request.LibraryId,
|
||||
request.MediaKind,
|
||||
request.FromUtc,
|
||||
request.ToUtc
|
||||
);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -27,6 +27,6 @@ public static class GetMostConsumedRequestMapping
|
||||
PerPage = request.PerPage ?? 50
|
||||
};
|
||||
|
||||
return new GetMostConsumedQuery(targetUserId, request.LibraryId, request.MediaKind, paginationData);
|
||||
return new GetMostConsumedQuery(targetUserId, request.LibraryId, request.MediaKind, request.FromUtc, request.ToUtc, paginationData);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -27,6 +27,6 @@ public static class GetRecentlyConsumedRequestMapping
|
||||
PerPage = request.PerPage ?? 50
|
||||
};
|
||||
|
||||
return new GetRecentlyConsumedQuery(targetUserId, request.LibraryId, request.MediaKind, paginationData);
|
||||
return new GetRecentlyConsumedQuery(targetUserId, request.LibraryId, request.MediaKind, request.FromUtc, request.ToUtc, paginationData);
|
||||
}
|
||||
}
|
||||
-1
@@ -22,7 +22,6 @@ public static class GetTagConsumptionRequestMapping
|
||||
targetUserId,
|
||||
request.LibraryId,
|
||||
request.MediaKind,
|
||||
request.TagKind,
|
||||
request.FromUtc,
|
||||
request.ToUtc
|
||||
);
|
||||
|
||||
@@ -22,7 +22,6 @@ public static class TagConsumptionDtoMapping
|
||||
{
|
||||
return new TagConsumptionResponse(
|
||||
data.Name,
|
||||
data.TagKind,
|
||||
data.ConsumedItemCount,
|
||||
data.ConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds
|
||||
);
|
||||
|
||||
+23
@@ -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.Commands.DeleteConsumptionItemHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Command for deleting every consumption record of a media item of a user.
|
||||
/// </summary>
|
||||
/// <param name="TargetUserId">The Id of the user the records must belong to, or <see langword="null"/> for the current user.</param>
|
||||
/// <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>
|
||||
[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public record DeleteConsumptionItemHistoryCommand(
|
||||
string? TargetUserId,
|
||||
MediaKind MediaKind,
|
||||
Guid MediaItemId,
|
||||
Guid LibraryId
|
||||
) : ICommand;
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
#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.DeleteConsumptionItemHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the command to delete every consumption record of a media item of a user.
|
||||
/// </summary>
|
||||
public class DeleteConsumptionItemHistoryCommandHandler : ICommandHandler<DeleteConsumptionItemHistoryCommand, Result<Deleted>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IValidator<DeleteConsumptionItemHistoryCommand> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryCommandHandler"/> 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 DeleteConsumptionItemHistoryCommandHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IAuthorizationService authorizationService,
|
||||
IValidator<DeleteConsumptionItemHistoryCommand> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the command to delete every consumption record of a media item 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(DeleteConsumptionItemHistoryCommand 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 deletion covers every recorded session of the item in its library, not only the sessions of a date range, so the row
|
||||
// disappears from the history consistently with clearing the whole history.
|
||||
Result<Deleted> deleteResult = await _unitOfWork.MediaConsumptionRecordRepository
|
||||
.DeleteAllByMediaItemIdForUserAsync(targetUserId, command.MediaKind, command.MediaItemId, 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;
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Validation;
|
||||
using Lumina.Application.Common.Utilities;
|
||||
using Lumina.Domain.Common.Errors;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="DeleteConsumptionItemHistoryCommand"/>.
|
||||
/// </summary>
|
||||
public class DeleteConsumptionItemHistoryCommandValidator : AbstractValidator<DeleteConsumptionItemHistoryCommand>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="DeleteConsumptionItemHistoryCommandValidator"/> class.
|
||||
/// </summary>
|
||||
public DeleteConsumptionItemHistoryCommandValidator()
|
||||
{
|
||||
// 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.MediaKind)
|
||||
.IsInEnum()
|
||||
.WithError(Errors.MediaConsumption.UnsupportedMediaKind);
|
||||
|
||||
RuleFor(command => command.MediaKind)
|
||||
.Must(mediaKind => mediaKind != MediaKind.None)
|
||||
.WithError(Errors.MediaConsumption.UnsupportedMediaKind);
|
||||
|
||||
RuleFor(command => command.MediaItemId)
|
||||
.Must(mediaItemId => mediaItemId != Guid.Empty)
|
||||
.WithError(Errors.MediaConsumption.MediaItemIdCannotBeEmpty);
|
||||
|
||||
RuleFor(command => command.LibraryId)
|
||||
.Must(libraryId => libraryId != Guid.Empty)
|
||||
.WithError(Errors.Library.LibraryIdCannotBeEmpty);
|
||||
}
|
||||
}
|
||||
+25
@@ -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.GetGenreConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the consumption statistics of the 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="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 GetGenreConsumptionQuery(
|
||||
string? TargetUserId,
|
||||
string? LibraryId,
|
||||
MediaKind? MediaKind,
|
||||
DateTime? FromUtc,
|
||||
DateTime? ToUtc
|
||||
) : IQuery;
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
#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.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.GetGenreConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Handler for the query to get the consumption statistics of the genres of a user.
|
||||
/// </summary>
|
||||
public class GetGenreConsumptionQueryHandler : IQueryHandler<GetGenreConsumptionQuery, Result<IReadOnlyList<GenreConsumptionResponse>>>
|
||||
{
|
||||
private readonly IUnitOfWork _unitOfWork;
|
||||
private readonly ICurrentUserService _currentUserService;
|
||||
private readonly IAuthorizationService _authorizationService;
|
||||
private readonly IValidator<GetGenreConsumptionQuery> _validator;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetGenreConsumptionQueryHandler"/> 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 GetGenreConsumptionQueryHandler(
|
||||
IUnitOfWork unitOfWork,
|
||||
ICurrentUserService currentUserService,
|
||||
IAuthorizationService authorizationService,
|
||||
IValidator<GetGenreConsumptionQuery> validator)
|
||||
{
|
||||
_unitOfWork = unitOfWork;
|
||||
_currentUserService = currentUserService;
|
||||
_authorizationService = authorizationService;
|
||||
_validator = validator;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the consumption statistics of the 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 genre statistics, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<IReadOnlyList<GenreConsumptionResponse>>> HandleAsync(GetGenreConsumptionQuery 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 genre is
|
||||
// loaded. Genres 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<string>> genreNamesByItem = [];
|
||||
foreach (TrackEntity track in tracks)
|
||||
{
|
||||
List<string> itemGenres = [.. track.Genres.Select(genre => genre.Name).OfType<string>()];
|
||||
if (itemGenres.Count > 0)
|
||||
genreNamesByItem[(MediaKind.MusicTrack, track.Id, track.LibraryId)] = itemGenres;
|
||||
}
|
||||
foreach (BookEntity book in books)
|
||||
{
|
||||
List<string> itemGenres = [.. book.Genres.Select(genre => genre.Name).OfType<string>()];
|
||||
if (itemGenres.Count > 0)
|
||||
genreNamesByItem[(MediaKind.Book, book.Id, book.LibraryId)] = itemGenres;
|
||||
}
|
||||
|
||||
// The records are aggregated to one row per item and library first, so an item with several sessions contributes its genres 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 genres 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<string, (int ConsumedItemCount, long ConsumedDurationMilliseconds)> genres = [];
|
||||
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 (!genreNamesByItem.TryGetValue((itemGroup.Key.MediaKind, itemGroup.Key.MediaItemId, itemGroup.Key.LibraryId), out List<string>? itemGenres) ||
|
||||
itemGenres.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 genres 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);
|
||||
AddGenres(genres, itemGenres, consumedDurationMilliseconds);
|
||||
}
|
||||
|
||||
List<GenreConsumptionDto> genreConsumptions = [.. genres
|
||||
.Select(genre => new GenreConsumptionDto(
|
||||
genre.Key,
|
||||
genre.Value.ConsumedItemCount,
|
||||
genre.Value.ConsumedDurationMilliseconds))
|
||||
.OrderByDescending(genreConsumption => genreConsumption.ConsumedItemCount)
|
||||
.ThenByDescending(genreConsumption => genreConsumption.ConsumedDurationMilliseconds)
|
||||
.ThenBy(genreConsumption => genreConsumption.Name)];
|
||||
|
||||
return Result.From(genreConsumptions.ToResponses());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds the lowercase <paramref name="names"/> of one item to the accumulated <paramref name="genres"/>.
|
||||
/// </summary>
|
||||
/// <param name="genres">The accumulated genres, keyed by lowercase name.</param>
|
||||
/// <param name="names">The genre 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 AddGenres(
|
||||
Dictionary<string, (int ConsumedItemCount, long ConsumedDurationMilliseconds)> genres,
|
||||
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;
|
||||
if (genres.TryGetValue(name, out (int ConsumedItemCount, long ConsumedDurationMilliseconds) current))
|
||||
genres[name] = (current.ConsumedItemCount + 1, current.ConsumedDurationMilliseconds + consumedDurationMilliseconds);
|
||||
else
|
||||
genres[name] = (1, consumedDurationMilliseconds);
|
||||
}
|
||||
}
|
||||
}
|
||||
+46
@@ -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.GetGenreConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for <see cref="GetGenreConsumptionQuery"/>.
|
||||
/// </summary>
|
||||
public class GetGenreConsumptionQueryValidator : AbstractValidator<GetGenreConsumptionQuery>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="GetGenreConsumptionQueryValidator"/> class.
|
||||
/// </summary>
|
||||
public GetGenreConsumptionQueryValidator()
|
||||
{
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
+5
@@ -2,6 +2,7 @@
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
@@ -13,11 +14,15 @@ namespace Lumina.Application.Core.MediaConsumption.Queries.GetMostConsumed;
|
||||
/// <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="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>
|
||||
/// <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,
|
||||
DateTime? FromUtc,
|
||||
DateTime? ToUtc,
|
||||
PaginationDataDto? PaginationData
|
||||
) : IQuery;
|
||||
+1
-1
@@ -93,7 +93,7 @@ public class GetMostConsumedQueryHandler : IQueryHandler<GetMostConsumedQuery, R
|
||||
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);
|
||||
.GetForUserAsync(targetUserId, libraryId, query.MediaKind, query.FromUtc, query.ToUtc, cancellationToken).ConfigureAwait(false);
|
||||
if (getRecordsResult.IsFailure)
|
||||
return getRecordsResult.Errors;
|
||||
|
||||
|
||||
+5
@@ -37,5 +37,10 @@ public class GetMostConsumedQueryValidator : AbstractValidator<GetMostConsumedQu
|
||||
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);
|
||||
}
|
||||
}
|
||||
+5
@@ -2,6 +2,7 @@
|
||||
using Lumina.Application.Common.CQRS;
|
||||
using Lumina.Application.Common.DTO.Pagination;
|
||||
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
@@ -13,11 +14,15 @@ namespace Lumina.Application.Core.MediaConsumption.Queries.GetRecentlyConsumed;
|
||||
/// <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="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>
|
||||
/// <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,
|
||||
DateTime? FromUtc,
|
||||
DateTime? ToUtc,
|
||||
PaginationDataDto? PaginationData
|
||||
) : IQuery;
|
||||
+1
-1
@@ -93,7 +93,7 @@ public class GetRecentlyConsumedQueryHandler : IQueryHandler<GetRecentlyConsumed
|
||||
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);
|
||||
.GetForUserAsync(targetUserId, libraryId, query.MediaKind, query.FromUtc, query.ToUtc, cancellationToken).ConfigureAwait(false);
|
||||
if (getRecordsResult.IsFailure)
|
||||
return getRecordsResult.Errors;
|
||||
|
||||
|
||||
+5
@@ -37,5 +37,10 @@ public class GetRecentlyConsumedQueryValidator : AbstractValidator<GetRecentlyCo
|
||||
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);
|
||||
}
|
||||
}
|
||||
+2
-5
@@ -1,6 +1,5 @@
|
||||
#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;
|
||||
@@ -9,20 +8,18 @@ using System.Diagnostics;
|
||||
namespace Lumina.Application.Core.MediaConsumption.Queries.GetTagConsumption;
|
||||
|
||||
/// <summary>
|
||||
/// Query for getting the consumption statistics of the tags and genres of a user.
|
||||
/// Query for getting the consumption statistics of the tags 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}")]
|
||||
[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")]
|
||||
public record GetTagConsumptionQuery(
|
||||
string? TargetUserId,
|
||||
string? LibraryId,
|
||||
MediaKind? MediaKind,
|
||||
TagKind? TagKind,
|
||||
DateTime? FromUtc,
|
||||
DateTime? ToUtc
|
||||
) : IQuery;
|
||||
+32
-56
@@ -15,7 +15,6 @@ 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;
|
||||
@@ -28,7 +27,7 @@ using ApplicationErrors = Lumina.Application.Common.Errors.Errors;
|
||||
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.
|
||||
/// Handler for the query to get the consumption statistics of the tags of a user.
|
||||
/// </summary>
|
||||
public class GetTagConsumptionQueryHandler : IQueryHandler<GetTagConsumptionQuery, Result<IReadOnlyList<TagConsumptionResponse>>>
|
||||
{
|
||||
@@ -57,12 +56,12 @@ public class GetTagConsumptionQueryHandler : IQueryHandler<GetTagConsumptionQuer
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles the query to get the consumption statistics of the tags and genres of a user.
|
||||
/// Handles the query to get the consumption statistics of the tags 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.
|
||||
/// An <see cref="Result{TValue}"/> containing either the requested tag statistics, or an error message.
|
||||
/// </returns>
|
||||
public async Task<Result<IReadOnlyList<TagConsumptionResponse>>> HandleAsync(GetTagConsumptionQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -90,8 +89,8 @@ public class GetTagConsumptionQueryHandler : IQueryHandler<GetTagConsumptionQuer
|
||||
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.
|
||||
// The access decision only needs the library Id that the records already carry, so it is made once per distinct library before any tag is
|
||||
// loaded. Tags 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>(
|
||||
@@ -126,40 +125,36 @@ public class GetTagConsumptionQueryHandler : IQueryHandler<GetTagConsumptionQuer
|
||||
books = [.. getBooksResult.Value];
|
||||
}
|
||||
|
||||
Dictionary<(MediaKind MediaKind, Guid MediaItemId, Guid LibraryId), List<(TagKind TagKind, string Name)>> termsByItem = [];
|
||||
Dictionary<(MediaKind MediaKind, Guid MediaItemId, Guid LibraryId), List<string>> tagNamesByItem = [];
|
||||
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;
|
||||
List<string> itemTags = [.. track.Tags.Select(tag => tag.Name).OfType<string>()];
|
||||
if (itemTags.Count > 0)
|
||||
tagNamesByItem[(MediaKind.MusicTrack, track.Id, track.LibraryId)] = itemTags;
|
||||
}
|
||||
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;
|
||||
List<string> itemTags = [.. book.Tags.Select(tag => tag.Name).OfType<string>()];
|
||||
if (itemTags.Count > 0)
|
||||
tagNamesByItem[(MediaKind.Book, book.Id, book.LibraryId)] = itemTags;
|
||||
}
|
||||
|
||||
// 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
|
||||
// The records are aggregated to one row per item and library first, so an item with several sessions contributes its tags 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
|
||||
// borrow the tags 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 = [];
|
||||
Dictionary<string, (int ConsumedItemCount, long ConsumedDurationMilliseconds)> tags = [];
|
||||
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)
|
||||
if (!tagNamesByItem.TryGetValue((itemGroup.Key.MediaKind, itemGroup.Key.MediaItemId, itemGroup.Key.LibraryId), out List<string>? itemTags) ||
|
||||
itemTags.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.
|
||||
// contribute its tags or its duration to the breakdown.
|
||||
Optional<MediaConsumptionRule> ruleResult = MediaConsumptionRule.For(itemGroup.Key.MediaKind);
|
||||
if (!ruleResult.HasValue)
|
||||
continue;
|
||||
@@ -171,47 +166,29 @@ public class GetTagConsumptionQueryHandler : IQueryHandler<GetTagConsumptionQuer
|
||||
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);
|
||||
}
|
||||
AddTags(tags, itemTags, consumedDurationMilliseconds);
|
||||
}
|
||||
|
||||
List<TagConsumptionDto> tagConsumptions = [.. terms
|
||||
.Select(term => new TagConsumptionDto(
|
||||
term.Key.Name,
|
||||
term.Key.TagKind,
|
||||
term.Value.ConsumedItemCount,
|
||||
term.Value.ConsumedDurationMilliseconds))
|
||||
List<TagConsumptionDto> tagConsumptions = [.. tags
|
||||
.Select(tag => new TagConsumptionDto(
|
||||
tag.Key,
|
||||
tag.Value.ConsumedItemCount,
|
||||
tag.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"/>.
|
||||
/// Adds the lowercase <paramref name="names"/> of one item to the accumulated <paramref name="tags"/>.
|
||||
/// </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="tags">The accumulated tags, keyed by lowercase name.</param>
|
||||
/// <param name="names">The tag 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,
|
||||
private static void AddTags(
|
||||
Dictionary<string, (int ConsumedItemCount, long ConsumedDurationMilliseconds)> tags,
|
||||
List<string> names,
|
||||
long consumedDurationMilliseconds)
|
||||
{
|
||||
@@ -220,11 +197,10 @@ public class GetTagConsumptionQueryHandler : IQueryHandler<GetTagConsumptionQuer
|
||||
{
|
||||
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);
|
||||
if (tags.TryGetValue(name, out (int ConsumedItemCount, long ConsumedDurationMilliseconds) current))
|
||||
tags[name] = (current.ConsumedItemCount + 1, current.ConsumedDurationMilliseconds + consumedDurationMilliseconds);
|
||||
else
|
||||
terms[key] = (1, consumedDurationMilliseconds);
|
||||
tags[name] = (1, consumedDurationMilliseconds);
|
||||
}
|
||||
}
|
||||
}
|
||||
-6
@@ -2,7 +2,6 @@
|
||||
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
|
||||
@@ -39,11 +38,6 @@ public class GetTagConsumptionQueryValidator : AbstractValidator<GetTagConsumpti
|
||||
.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)
|
||||
|
||||
Reference in new issue
Block a user