diff --git a/src/Lumina.Application/Common/DTO/MediaConsumption/GenreConsumptionDto.cs b/src/Lumina.Application/Common/DTO/MediaConsumption/GenreConsumptionDto.cs
new file mode 100644
index 00000000..4d5b0e57
--- /dev/null
+++ b/src/Lumina.Application/Common/DTO/MediaConsumption/GenreConsumptionDto.cs
@@ -0,0 +1,18 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Common.DTO.MediaConsumption;
+
+///
+/// Data transfer object for the consumption statistics of a genre, grouped across media kinds.
+///
+/// The lowercase name of the genre.
+/// The number of distinct media items that carry the genre and were consumed.
+/// The active duration consumed in the media items that carry the genre, in milliseconds.
+[DebuggerDisplay("Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")]
+public sealed record GenreConsumptionDto(
+ string Name,
+ int ConsumedItemCount,
+ long ConsumedDurationMilliseconds
+);
diff --git a/src/Lumina.Application/Common/DTO/MediaConsumption/TagConsumptionDto.cs b/src/Lumina.Application/Common/DTO/MediaConsumption/TagConsumptionDto.cs
index c581c424..e836165d 100644
--- a/src/Lumina.Application/Common/DTO/MediaConsumption/TagConsumptionDto.cs
+++ b/src/Lumina.Application/Common/DTO/MediaConsumption/TagConsumptionDto.cs
@@ -1,21 +1,18 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DTO.MediaConsumption;
///
-/// 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.
///
-/// The lowercase name of the tag or genre.
-/// Whether the entry is a genre or a tag.
-/// The number of distinct media items that carry the term and were consumed.
-/// The active duration consumed in the media items that carry the term, in milliseconds.
-[DebuggerDisplay("TagKind: {TagKind}; Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")]
+/// The lowercase name of the tag.
+/// The number of distinct media items that carry the tag and were consumed.
+/// The active duration consumed in the media items that carry the tag, in milliseconds.
+[DebuggerDisplay("Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")]
public sealed record TagConsumptionDto(
string Name,
- TagKind TagKind,
int ConsumedItemCount,
long ConsumedDurationMilliseconds
);
diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MediaConsumption/IMediaConsumptionRecordRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MediaConsumption/IMediaConsumptionRecordRepository.cs
index 4ac364a3..ddbcad74 100644
--- a/src/Lumina.Application/Common/DataAccess/Repositories/MediaConsumption/IMediaConsumptionRecordRepository.cs
+++ b/src/Lumina.Application/Common/DataAccess/Repositories/MediaConsumption/IMediaConsumptionRecordRepository.cs
@@ -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 : IRepositoryAn representing either a successful deletion, or an error.
Task> DeleteForUserAsync(Guid id, Guid userId, CancellationToken cancellationToken);
+ ///
+ /// Deletes every consumption record of a media item of the user identified by .
+ ///
+ /// The Id of the user whose consumption records are deleted.
+ /// The kind of the consumed media item.
+ /// The Id of the consumed media item.
+ /// The Id of the media library that contains the media item.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful deletion, or an error.
+ Task> DeleteAllByMediaItemIdForUserAsync(Guid userId, MediaKind mediaKind, Guid mediaItemId, Guid libraryId, CancellationToken cancellationToken);
+
///
/// Deletes every consumption record of the user identified by .
///
diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GenreConsumptionDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GenreConsumptionDtoMapping.cs
new file mode 100644
index 00000000..b8e9c761
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GenreConsumptionDtoMapping.cs
@@ -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;
+
+///
+/// Extension methods for converting .
+///
+public static class GenreConsumptionDtoMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The data transfer object to be converted.
+ /// The converted response.
+ public static GenreConsumptionResponse ToResponse(this GenreConsumptionDto data)
+ {
+ return new GenreConsumptionResponse(
+ data.Name,
+ data.ConsumedItemCount,
+ data.ConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds
+ );
+ }
+
+ ///
+ /// Converts to a collection of .
+ ///
+ /// The data transfer objects to be converted.
+ /// The converted responses.
+ public static IReadOnlyList ToResponses(this IReadOnlyList data)
+ {
+ return [.. data.Select(item => item.ToResponse())];
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetGenreConsumptionRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetGenreConsumptionRequestMapping.cs
new file mode 100644
index 00000000..6a88e5a0
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetGenreConsumptionRequestMapping.cs
@@ -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;
+
+///
+/// Extension methods for converting .
+///
+public static class GetGenreConsumptionRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The Id of the user whose statistics are retrieved, taken from the route, or for the current user.
+ /// The converted query.
+ public static GetGenreConsumptionQuery ToQuery(this GetGenreConsumptionRequest request, string? targetUserId)
+ {
+ return new GetGenreConsumptionQuery(
+ targetUserId,
+ request.LibraryId,
+ request.MediaKind,
+ request.FromUtc,
+ request.ToUtc
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetMostConsumedRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetMostConsumedRequestMapping.cs
index 4013f809..03349cd7 100644
--- a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetMostConsumedRequestMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetMostConsumedRequestMapping.cs
@@ -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);
}
}
diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMapping.cs
index a73c82ac..5f06a893 100644
--- a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetRecentlyConsumedRequestMapping.cs
@@ -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);
}
}
diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetTagConsumptionRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetTagConsumptionRequestMapping.cs
index d0bf4ce1..526df04b 100644
--- a/src/Lumina.Application/Common/Mapping/MediaConsumption/GetTagConsumptionRequestMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/GetTagConsumptionRequestMapping.cs
@@ -22,7 +22,6 @@ public static class GetTagConsumptionRequestMapping
targetUserId,
request.LibraryId,
request.MediaKind,
- request.TagKind,
request.FromUtc,
request.ToUtc
);
diff --git a/src/Lumina.Application/Common/Mapping/MediaConsumption/TagConsumptionDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaConsumption/TagConsumptionDtoMapping.cs
index d65e0253..4db6a9f6 100644
--- a/src/Lumina.Application/Common/Mapping/MediaConsumption/TagConsumptionDtoMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaConsumption/TagConsumptionDtoMapping.cs
@@ -22,7 +22,6 @@ public static class TagConsumptionDtoMapping
{
return new TagConsumptionResponse(
data.Name,
- data.TagKind,
data.ConsumedItemCount,
data.ConsumedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds
);
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommand.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommand.cs
new file mode 100644
index 00000000..28ebb3c1
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommand.cs
@@ -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;
+
+///
+/// Command for deleting every consumption record of a media item of a user.
+///
+/// The Id of the user the records must belong to, or for the current user.
+/// The kind of the consumed media item.
+/// The Id of the consumed media item.
+/// The Id of the media library that contains the media item.
+[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
+public record DeleteConsumptionItemHistoryCommand(
+ string? TargetUserId,
+ MediaKind MediaKind,
+ Guid MediaItemId,
+ Guid LibraryId
+) : ICommand;
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandHandler.cs
new file mode 100644
index 00000000..4d431e3b
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandHandler.cs
@@ -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;
+
+///
+/// Handler for the command to delete every consumption record of a media item of a user.
+///
+public class DeleteConsumptionItemHistoryCommandHandler : ICommandHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for authorization related functionality.
+ /// Injected validator for application validation rules.
+ public DeleteConsumptionItemHistoryCommandHandler(
+ IUnitOfWork unitOfWork,
+ ICurrentUserService currentUserService,
+ IAuthorizationService authorizationService,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the command to delete every consumption record of a media item of a user.
+ ///
+ /// The command to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful deletion, or an error message.
+ public async Task> HandleAsync(DeleteConsumptionItemHistoryCommand command, CancellationToken cancellationToken)
+ {
+ List validationResult = _validator.Validate(command);
+ if (validationResult.Count > 0)
+ return validationResult;
+
+ // An authenticated request must always carry a user identity.
+ Guid? currentUserId = _currentUserService.UserId;
+ if (currentUserId is null)
+ return ApplicationErrors.Authorization.NotAuthorized;
+ Guid userId = currentUserId.Value;
+
+ // The 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(
+ 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 deleteResult = await _unitOfWork.MediaConsumptionRecordRepository
+ .DeleteAllByMediaItemIdForUserAsync(targetUserId, command.MediaKind, command.MediaItemId, command.LibraryId, cancellationToken).ConfigureAwait(false);
+ if (deleteResult.IsFailure)
+ return deleteResult.Errors;
+
+ Result saveChangesResult = await _unitOfWork.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
+ if (saveChangesResult.IsFailure)
+ return saveChangesResult.Errors;
+
+ return Result.Deleted;
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandValidator.cs
new file mode 100644
index 00000000..9f930037
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Commands/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryCommandValidator.cs
@@ -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;
+
+///
+/// Validates the needed validation rules for .
+///
+public class DeleteConsumptionItemHistoryCommandValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ 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);
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQuery.cs
new file mode 100644
index 00000000..7ca593a6
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQuery.cs
@@ -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;
+
+///
+/// Query for getting the consumption statistics of the genres of a user.
+///
+/// The Id of the user whose statistics are retrieved, or for the current user.
+/// The Id of the media library to restrict the statistics to, or for every library.
+/// The kind of media to restrict the statistics to, or for every kind.
+/// The inclusive start of the date range, or when the range has no start.
+/// The inclusive end of the date range, or when the range has no end.
+[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")]
+public record GetGenreConsumptionQuery(
+ string? TargetUserId,
+ string? LibraryId,
+ MediaKind? MediaKind,
+ DateTime? FromUtc,
+ DateTime? ToUtc
+) : IQuery;
diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryHandler.cs
new file mode 100644
index 00000000..2da2cb9c
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryHandler.cs
@@ -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;
+
+///
+/// Handler for the query to get the consumption statistics of the genres of a user.
+///
+public class GetGenreConsumptionQueryHandler : IQueryHandler>>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+ private readonly IValidator _validator;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected unit of work for interacting with the data access layer repositories.
+ /// Injected service to retrieve the current user information.
+ /// Injected service for authorization related functionality.
+ /// Injected validator for application validation rules.
+ public GetGenreConsumptionQueryHandler(
+ IUnitOfWork unitOfWork,
+ ICurrentUserService currentUserService,
+ IAuthorizationService authorizationService,
+ IValidator validator)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ _validator = validator;
+ }
+
+ ///
+ /// Handles the query to get the consumption statistics of the genres of a user.
+ ///
+ /// The query to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the requested genre statistics, or an error message.
+ ///
+ public async Task>> HandleAsync(GetGenreConsumptionQuery query, CancellationToken cancellationToken)
+ {
+ List 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(
+ 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> 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 libraryAccess = [];
+ foreach (Guid recordLibraryId in getRecordsResult.Value.Select(record => record.LibraryId).Distinct())
+ libraryAccess[recordLibraryId] = await _authorizationService.EvaluatePolicyAsync(
+ 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 trackIds = [.. getRecordsResult.Value
+ .Where(record => record.MediaKind == MediaKind.MusicTrack && libraryAccess[record.LibraryId])
+ .Select(record => record.MediaItemId)
+ .Distinct()];
+ List tracks = [];
+ if (trackIds.Count > 0)
+ {
+ Result> getTracksResult = await _unitOfWork.TrackRepository
+ .GetByIdsAsync(trackIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false);
+ if (getTracksResult.IsFailure)
+ return getTracksResult.Errors;
+ tracks = [.. getTracksResult.Value];
+ }
+
+ List bookIds = [.. getRecordsResult.Value
+ .Where(record => record.MediaKind == MediaKind.Book && libraryAccess[record.LibraryId])
+ .Select(record => record.MediaItemId)
+ .Distinct()];
+ List books = [];
+ if (bookIds.Count > 0)
+ {
+ Result> 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> genreNamesByItem = [];
+ foreach (TrackEntity track in tracks)
+ {
+ List itemGenres = [.. track.Genres.Select(genre => genre.Name).OfType()];
+ if (itemGenres.Count > 0)
+ genreNamesByItem[(MediaKind.MusicTrack, track.Id, track.LibraryId)] = itemGenres;
+ }
+ foreach (BookEntity book in books)
+ {
+ List itemGenres = [.. book.Genres.Select(genre => genre.Name).OfType()];
+ 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 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? 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 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 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());
+ }
+
+ ///
+ /// Adds the lowercase of one item to the accumulated .
+ ///
+ /// The accumulated genres, keyed by lowercase name.
+ /// The genre names carried by the item.
+ /// The duration consumed in the item, over all of its sessions, in milliseconds.
+ private static void AddGenres(
+ Dictionary genres,
+ List 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);
+ }
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryValidator.cs
new file mode 100644
index 00000000..58ab2f25
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetGenreConsumption/GetGenreConsumptionQueryValidator.cs
@@ -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;
+
+///
+/// Validates the needed validation rules for .
+///
+public class GetGenreConsumptionQueryValidator : AbstractValidator
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ 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);
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQuery.cs
index 9578fbba..7eeffc81 100644
--- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQuery.cs
+++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQuery.cs
@@ -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;
/// The Id of the user whose history is retrieved, or for the current user.
/// The Id of the media library to restrict the history to, or for every library.
/// The kind of media to restrict the history to, or for every kind.
+/// The inclusive start of the date range, or when the range has no start.
+/// The inclusive end of the date range, or when the range has no end.
/// The object containing the requested pagination data. When , every matching item is returned; when present, its requested page is returned.
[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")]
public record GetMostConsumedQuery(
string? TargetUserId,
string? LibraryId,
MediaKind? MediaKind,
+ DateTime? FromUtc,
+ DateTime? ToUtc,
PaginationDataDto? PaginationData
) : IQuery;
diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryHandler.cs
index 5e8e86f3..7db28a78 100644
--- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryHandler.cs
+++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryHandler.cs
@@ -93,7 +93,7 @@ public class GetMostConsumedQueryHandler : IQueryHandler> 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;
diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryValidator.cs
index e021b912..7d010cf8 100644
--- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryValidator.cs
+++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetMostConsumed/GetMostConsumedQueryValidator.cs
@@ -37,5 +37,10 @@ public class GetMostConsumedQueryValidator : AbstractValidator 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);
}
}
diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQuery.cs
index e3f0cc95..e0ac673b 100644
--- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQuery.cs
+++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQuery.cs
@@ -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;
/// The Id of the user whose history is retrieved, or for the current user.
/// The Id of the media library to restrict the history to, or for every library.
/// The kind of media to restrict the history to, or for every kind.
+/// The inclusive start of the date range, or when the range has no start.
+/// The inclusive end of the date range, or when the range has no end.
/// The object containing the requested pagination data. When , every matching item is returned; when present, its requested page is returned.
[DebuggerDisplay("TargetUserId: {TargetUserId}; MediaKind: {MediaKind}")]
public record GetRecentlyConsumedQuery(
string? TargetUserId,
string? LibraryId,
MediaKind? MediaKind,
+ DateTime? FromUtc,
+ DateTime? ToUtc,
PaginationDataDto? PaginationData
) : IQuery;
diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryHandler.cs
index ec75e379..4980b879 100644
--- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryHandler.cs
+++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryHandler.cs
@@ -93,7 +93,7 @@ public class GetRecentlyConsumedQueryHandler : IQueryHandler> 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;
diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryValidator.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryValidator.cs
index 9e7b0f48..241ac8ee 100644
--- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryValidator.cs
+++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetRecentlyConsumed/GetRecentlyConsumedQueryValidator.cs
@@ -37,5 +37,10 @@ public class GetRecentlyConsumedQueryValidator : AbstractValidator 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);
}
}
diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQuery.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQuery.cs
index 26398620..8ef7edd1 100644
--- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQuery.cs
+++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQuery.cs
@@ -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;
///
-/// 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.
///
/// The Id of the user whose statistics are retrieved, or for the current user.
/// The Id of the media library to restrict the statistics to, or for every library.
/// The kind of media to restrict the statistics to, or for every kind.
-/// Whether to return genres or tags, or for both.
/// The inclusive start of the date range, or when the range has no start.
/// The inclusive end of the date range, or when the range has no end.
-[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;
diff --git a/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryHandler.cs b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryHandler.cs
index f92b1ba0..66ca2a66 100644
--- a/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryHandler.cs
+++ b/src/Lumina.Application/Core/MediaConsumption/Queries/GetTagConsumption/GetTagConsumptionQueryHandler.cs
@@ -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;
///
-/// 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.
///
public class GetTagConsumptionQueryHandler : IQueryHandler>>
{
@@ -57,12 +56,12 @@ public class GetTagConsumptionQueryHandler : IQueryHandler
- /// 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.
///
/// The query to be handled.
/// Cancellation token that can be used to stop the execution.
///
- /// An containing either the requested tag and genre statistics, or an error message.
+ /// An containing either the requested tag statistics, or an error message.
///
public async Task>> HandleAsync(GetTagConsumptionQuery query, CancellationToken cancellationToken)
{
@@ -90,8 +89,8 @@ public class GetTagConsumptionQueryHandler : IQueryHandler libraryAccess = [];
foreach (Guid recordLibraryId in getRecordsResult.Value.Select(record => record.LibraryId).Distinct())
libraryAccess[recordLibraryId] = await _authorizationService.EvaluatePolicyAsync(
@@ -126,40 +125,36 @@ public class GetTagConsumptionQueryHandler : IQueryHandler> termsByItem = [];
+ Dictionary<(MediaKind MediaKind, Guid MediaItemId, Guid LibraryId), List> tagNamesByItem = [];
foreach (TrackEntity track in tracks)
{
- List<(TagKind TagKind, string Name)> itemTerms = [];
- itemTerms.AddRange(track.Tags.Select(tag => tag.Name).OfType().Select(name => (TagKind.Tag, name)));
- itemTerms.AddRange(track.Genres.Select(genre => genre.Name).OfType().Select(name => (TagKind.Genre, name)));
- if (itemTerms.Count > 0)
- termsByItem[(MediaKind.MusicTrack, track.Id, track.LibraryId)] = itemTerms;
+ List itemTags = [.. track.Tags.Select(tag => tag.Name).OfType()];
+ 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().Select(name => (TagKind.Tag, name)));
- itemTerms.AddRange(book.Genres.Select(genre => genre.Name).OfType().Select(name => (TagKind.Genre, name)));
- if (itemTerms.Count > 0)
- termsByItem[(MediaKind.Book, book.Id, book.LibraryId)] = itemTerms;
+ List itemTags = [.. book.Tags.Select(tag => tag.Name).OfType()];
+ 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 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? 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 ruleResult = MediaConsumptionRule.For(itemGroup.Key.MediaKind);
if (!ruleResult.HasValue)
continue;
@@ -171,47 +166,29 @@ public class GetTagConsumptionQueryHandler : IQueryHandler record.ConsumedDurationMilliseconds);
-
- if (query.TagKind is null || query.TagKind == TagKind.Tag)
- {
- List 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 genreNames = [.. itemTerms
- .Where(termRow => termRow.TagKind == TagKind.Genre)
- .Select(termRow => termRow.Name)];
- AddTerms(terms, TagKind.Genre, genreNames, consumedDurationMilliseconds);
- }
+ AddTags(tags, itemTags, consumedDurationMilliseconds);
}
- List tagConsumptions = [.. terms
- .Select(term => new TagConsumptionDto(
- term.Key.Name,
- term.Key.TagKind,
- term.Value.ConsumedItemCount,
- term.Value.ConsumedDurationMilliseconds))
+ List 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());
}
///
- /// Adds the lowercase of one item to the accumulated .
+ /// Adds the lowercase of one item to the accumulated .
///
- /// The accumulated terms, keyed by tag kind and lowercase name.
- /// Whether the names are tags or genres.
- /// The names carried by the item.
+ /// The accumulated tags, keyed by lowercase name.
+ /// The tag names carried by the item.
/// The duration consumed in the item, over all of its sessions, in milliseconds.
- private static void AddTerms(
- Dictionary<(TagKind TagKind, string Name), (int ConsumedItemCount, long ConsumedDurationMilliseconds)> terms,
- TagKind tagKind,
+ private static void AddTags(
+ Dictionary tags,
List names,
long consumedDurationMilliseconds)
{
@@ -220,11 +197,10 @@ public class GetTagConsumptionQueryHandler : IQueryHandler 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)
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/DeleteConsumptionItemHistoryRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/DeleteConsumptionItemHistoryRequest.cs
new file mode 100644
index 00000000..7014c957
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/DeleteConsumptionItemHistoryRequest.cs
@@ -0,0 +1,20 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.MediaConsumption;
+
+///
+/// Represents a request to delete every consumption record of a media item.
+///
+/// The kind of the consumed media item.
+/// The Id of the consumed media item.
+/// The Id of the media library that contains the media item.
+[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}; LibraryId: {LibraryId}")]
+public sealed record DeleteConsumptionItemHistoryRequest(
+ MediaKind MediaKind,
+ Guid MediaItemId,
+ Guid LibraryId
+);
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetGenreConsumptionRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetGenreConsumptionRequest.cs
new file mode 100644
index 00000000..f2a76b8c
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetGenreConsumptionRequest.cs
@@ -0,0 +1,22 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.MediaConsumption;
+
+///
+/// Represents a request for getting the consumption statistics of the genres of a user.
+///
+/// The Id of the media library to restrict the statistics to. Optional.
+/// The kind of media to restrict the statistics to. Optional.
+/// The inclusive start of the date range. Optional.
+/// The inclusive end of the date range. Optional.
+[DebuggerDisplay("MediaKind: {MediaKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")]
+public sealed record GetGenreConsumptionRequest(
+ string? LibraryId,
+ MediaKind? MediaKind,
+ DateTime? FromUtc,
+ DateTime? ToUtc
+);
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetMostConsumedRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetMostConsumedRequest.cs
index 24c85867..e754cd9d 100644
--- a/src/Lumina.Contracts/Requests/MediaConsumption/GetMostConsumedRequest.cs
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetMostConsumedRequest.cs
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
using System.Diagnostics;
#endregion
@@ -12,10 +13,14 @@ namespace Lumina.Contracts.Requests.MediaConsumption;
/// The kind of media to restrict the history to. Optional.
/// The one based page of media items to return. Optional.
/// The number of media items per page. Optional.
+/// The inclusive start of the date range. Optional.
+/// The inclusive end of the date range. Optional.
[DebuggerDisplay("MediaKind: {MediaKind}; CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
public sealed record GetMostConsumedRequest(
string? LibraryId,
MediaKind? MediaKind,
int? CurrentPage,
- int? PerPage
+ int? PerPage,
+ DateTime? FromUtc,
+ DateTime? ToUtc
);
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetRecentlyConsumedRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetRecentlyConsumedRequest.cs
index 273a9897..a32ec62f 100644
--- a/src/Lumina.Contracts/Requests/MediaConsumption/GetRecentlyConsumedRequest.cs
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetRecentlyConsumedRequest.cs
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using System;
using System.Diagnostics;
#endregion
@@ -12,10 +13,14 @@ namespace Lumina.Contracts.Requests.MediaConsumption;
/// The kind of media to restrict the history to. Optional.
/// The one based page of media items to return. Optional.
/// The number of media items per page. Optional.
+/// The inclusive start of the date range. Optional.
+/// The inclusive end of the date range. Optional.
[DebuggerDisplay("MediaKind: {MediaKind}; CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
public sealed record GetRecentlyConsumedRequest(
string? LibraryId,
MediaKind? MediaKind,
int? CurrentPage,
- int? PerPage
+ int? PerPage,
+ DateTime? FromUtc,
+ DateTime? ToUtc
);
diff --git a/src/Lumina.Contracts/Requests/MediaConsumption/GetTagConsumptionRequest.cs b/src/Lumina.Contracts/Requests/MediaConsumption/GetTagConsumptionRequest.cs
index dc4e93ab..bcffa4d9 100644
--- a/src/Lumina.Contracts/Requests/MediaConsumption/GetTagConsumptionRequest.cs
+++ b/src/Lumina.Contracts/Requests/MediaConsumption/GetTagConsumptionRequest.cs
@@ -1,5 +1,4 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using System;
using System.Diagnostics;
@@ -8,18 +7,16 @@ using System.Diagnostics;
namespace Lumina.Contracts.Requests.MediaConsumption;
///
-/// Represents a request for getting the consumption statistics of the tags and genres of a user.
+/// Represents a request for getting the consumption statistics of the tags of a user.
///
/// The Id of the media library to restrict the statistics to. Optional.
/// The kind of media to restrict the statistics to. Optional.
-/// Whether to return genres or tags. Optional.
/// The inclusive start of the date range. Optional.
/// The inclusive end of the date range. Optional.
-[DebuggerDisplay("MediaKind: {MediaKind}; TagKind: {TagKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")]
+[DebuggerDisplay("MediaKind: {MediaKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")]
public sealed record GetTagConsumptionRequest(
string? LibraryId,
MediaKind? MediaKind,
- TagKind? TagKind,
DateTime? FromUtc,
DateTime? ToUtc
);
diff --git a/src/Lumina.Contracts/Responses/MediaConsumption/GenreConsumptionResponse.cs b/src/Lumina.Contracts/Responses/MediaConsumption/GenreConsumptionResponse.cs
new file mode 100644
index 00000000..b78a9c22
--- /dev/null
+++ b/src/Lumina.Contracts/Responses/MediaConsumption/GenreConsumptionResponse.cs
@@ -0,0 +1,18 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Responses.MediaConsumption;
+
+///
+/// Represents the consumption statistics of a genre, grouped across media kinds.
+///
+/// The lowercase name of the genre.
+/// The number of distinct media items that carry the genre and were consumed.
+/// The active duration consumed in the media items that carry the genre, in seconds.
+[DebuggerDisplay("Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")]
+public sealed record GenreConsumptionResponse(
+ string Name,
+ int ConsumedItemCount,
+ double ConsumedDurationInSeconds
+);
diff --git a/src/Lumina.Contracts/Responses/MediaConsumption/TagConsumptionResponse.cs b/src/Lumina.Contracts/Responses/MediaConsumption/TagConsumptionResponse.cs
index 5508643c..48468318 100644
--- a/src/Lumina.Contracts/Responses/MediaConsumption/TagConsumptionResponse.cs
+++ b/src/Lumina.Contracts/Responses/MediaConsumption/TagConsumptionResponse.cs
@@ -1,21 +1,18 @@
#region ========================================================================= USING =====================================================================================
-using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.MediaConsumption;
///
-/// Represents the consumption statistics of a tag or genre, grouped across media kinds.
+/// Represents the consumption statistics of a tag, grouped across media kinds.
///
-/// The lowercase name of the tag or genre.
-/// Whether the entry is a genre or a tag.
-/// The number of distinct media items that carry the term and were consumed.
-/// The active duration consumed in the media items that carry the term, in seconds.
-[DebuggerDisplay("TagKind: {TagKind}; Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")]
+/// The lowercase name of the tag.
+/// The number of distinct media items that carry the tag and were consumed.
+/// The active duration consumed in the media items that carry the tag, in seconds.
+[DebuggerDisplay("Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")]
public sealed record TagConsumptionResponse(
string Name,
- TagKind TagKind,
int ConsumedItemCount,
double ConsumedDurationInSeconds
);
diff --git a/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaConsumptionRecordRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaConsumptionRecordRepository.cs
index 3732ecb8..218dc426 100644
--- a/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaConsumptionRecordRepository.cs
+++ b/src/Lumina.DataAccess/Core/Repositories/MediaConsumption/MediaConsumptionRecordRepository.cs
@@ -130,6 +130,28 @@ internal sealed class MediaConsumptionRecordRepository : IMediaConsumptionRecord
return Result.Deleted;
}
+ ///
+ /// Deletes every consumption record of a media item of the user identified by .
+ ///
+ /// The Id of the user whose consumption records are deleted.
+ /// The kind of the consumed media item.
+ /// The Id of the consumed media item.
+ /// The Id of the media library that contains the media item.
+ /// Cancellation token that can be used to stop the execution.
+ /// An representing either a successful deletion, or an error.
+ public async Task> DeleteAllByMediaItemIdForUserAsync(Guid userId, MediaKind mediaKind, Guid mediaItemId, Guid libraryId, CancellationToken cancellationToken)
+ {
+ List records = await _luminaDbContext.MediaConsumptionRecords
+ .Where(record => record.UserId == userId &&
+ record.MediaKind == mediaKind &&
+ record.MediaItemId == mediaItemId &&
+ record.LibraryId == libraryId)
+ .ToListAsync(cancellationToken).ConfigureAwait(false);
+ if (records.Count > 0)
+ _luminaDbContext.MediaConsumptionRecords.RemoveRange(records);
+ return Result.Deleted;
+ }
+
///
/// Deletes every consumption record of the user identified by .
///
diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaConsumption/TagKind.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/MediaConsumption/TagKind.cs
deleted file mode 100644
index 84745686..00000000
--- a/src/Lumina.Domain.SharedKernel/Common/Enums/MediaConsumption/TagKind.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-namespace Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
-
-///
-/// Enumeration for the kinds of terms that a consumed media item can be classified by.
-///
-public enum TagKind
-{
- ///
- /// A genre.
- ///
- Genre,
-
- ///
- /// A tag.
- ///
- Tag
-}
diff --git a/src/Lumina.Domain/Common/Errors/Errors.MediaConsumption.cs b/src/Lumina.Domain/Common/Errors/Errors.MediaConsumption.cs
index 7490fbf5..09a5a71a 100644
--- a/src/Lumina.Domain/Common/Errors/Errors.MediaConsumption.cs
+++ b/src/Lumina.Domain/Common/Errors/Errors.MediaConsumption.cs
@@ -19,7 +19,6 @@ public static partial class Errors
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));
diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/Statistics/ApiRoutes.LibraryStatistics.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/Statistics/ApiRoutes.LibraryStatistics.cs
index 9879ddf9..2eb93dc2 100644
--- a/src/Lumina.Presentation.Api/Common/Routes/Library/Statistics/ApiRoutes.LibraryStatistics.cs
+++ b/src/Lumina.Presentation.Api/Common/Routes/Library/Statistics/ApiRoutes.LibraryStatistics.cs
@@ -14,13 +14,17 @@ public static partial class ApiRoutes
public const string GET_MOST_CONSUMED = "/users/me/consumption-history/most-consumed";
public const string GET_CONSUMPTION_STATISTICS = "/users/me/consumption-statistics";
public const string GET_TAG_CONSUMPTION = "/users/me/consumption-statistics/tags";
+ public const string GET_GENRE_CONSUMPTION = "/users/me/consumption-statistics/genres";
public const string GET_USER_RECENTLY_CONSUMED = "/users/{userId}/consumption-history/recently-consumed";
public const string GET_USER_MOST_CONSUMED = "/users/{userId}/consumption-history/most-consumed";
public const string GET_USER_CONSUMPTION_STATISTICS = "/users/{userId}/consumption-statistics";
public const string GET_USER_TAG_CONSUMPTION = "/users/{userId}/consumption-statistics/tags";
+ public const string GET_USER_GENRE_CONSUMPTION = "/users/{userId}/consumption-statistics/genres";
public const string GET_ALL_USERS_CONSUMPTION_STATISTICS = "/users/consumption-statistics";
public const string DELETE_CONSUMPTION_RECORD = "/users/me/consumption-history/{recordId}";
public const string DELETE_USER_CONSUMPTION_RECORD = "/users/{userId}/consumption-history/{recordId}";
+ public const string DELETE_CONSUMPTION_ITEM_HISTORY = "/users/me/consumption-history/media-items/{mediaKind}/{mediaItemId}/{libraryId}";
+ public const string DELETE_USER_CONSUMPTION_ITEM_HISTORY = "/users/{userId}/consumption-history/media-items/{mediaKind}/{mediaItemId}/{libraryId}";
public const string CLEAR_CONSUMPTION_HISTORY = "/users/me/consumption-history";
public const string CLEAR_USER_CONSUMPTION_HISTORY = "/users/{userId}/consumption-history";
public const string CLEAR_RESUME_POINTS = "/users/me/media-resume-points";
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpoint.cs
new file mode 100644
index 00000000..ccb8ccda
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpoint.cs
@@ -0,0 +1,60 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+using Lumina.Presentation.Api.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Http;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
+
+///
+/// API endpoint for the /users/me/consumption-history/media-items/{mediaKind}/{mediaItemId}/{libraryId} route.
+///
+///
+/// Uses "me" because it is always for the currently authenticated user.
+///
+public class DeleteConsumptionItemHistoryEndpoint : BaseEndpoint
+{
+ private readonly ICommandHandler> _deleteConsumptionItemHistoryCommandHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling delete consumption item history commands.
+ public DeleteConsumptionItemHistoryEndpoint(ICommandHandler> deleteConsumptionItemHistoryCommandHandler)
+ {
+ _deleteConsumptionItemHistoryCommandHandler = deleteConsumptionItemHistoryCommandHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.DELETE);
+ Routes(ApiRoutes.LibraryStatistics.DELETE_CONSUMPTION_ITEM_HISTORY);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Deletes every consumption record of a media item of the current user.
+ ///
+ /// The request containing the media item and its library.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(DeleteConsumptionItemHistoryRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption records belong to the authenticated user, so no intermediary may store any response of this route, including its problem
+ // responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ Result result = await _deleteConsumptionItemHistoryCommandHandler
+ .HandleAsync(new DeleteConsumptionItemHistoryCommand(TargetUserId: null, request.MediaKind, request.MediaItemId, request.LibraryId), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointSummary.cs
new file mode 100644
index 00000000..56fcb2e6
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointSummary.cs
@@ -0,0 +1,99 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteConsumptionItemHistoryEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public DeleteConsumptionItemHistoryEndpointSummary()
+ {
+ Summary = "Deletes every consumption record of a media item of the current user.";
+ Description = "Deletes every recorded consumption session of one media item of the current user, in the library named by the route. The deletion covers every session of the item, independent of any date range, so the item disappears from the history consistently with clearing the whole history. Deleting an item that has no recorded session changes nothing and is not an error, so a retried deletion is safe; a concurrent write can still be rejected with a conflict. The resume point of the media item is not deleted: removing an item from the history and removing it from continue watching are separate user actions. The records of another user are never deleted by this route.";
+
+ Params["mediaKind"] = "The kind of the consumed media item.";
+ Params["mediaItemId"] = "The Id of the consumed media item.";
+ Params["libraryId"] = "The Id of the media library that contains the media item.";
+
+ Response(200, "The consumption records of the media item were successfully deleted.");
+
+ Response(401, "Authentication required.", "application/problem+json",
+ example: new[]
+ {
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "Authentication failed",
+ instance = "/api/v1/users/me/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/me/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/me/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
+ title = "General.Conflict",
+ status = 409,
+ detail = "ConcurrencyConflict",
+ instance = "/api/v1/users/me/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(422, "The request did not pass validation checks.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc4918#section-11.2",
+ title = "General.Validation",
+ status = 422,
+ detail = "OneOrMoreValidationErrorsOccurred",
+ instance = "/api/v1/users/me/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "UnsupportedMediaKind",
+ "MediaItemIdCannotBeEmpty",
+ "LibraryIdCannotBeEmpty"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpoint.cs
new file mode 100644
index 00000000..5b674a3b
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpoint.cs
@@ -0,0 +1,58 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Core.MediaConsumption.Commands.DeleteConsumptionItemHistory;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+using Lumina.Presentation.Api.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Http;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
+
+///
+/// API endpoint for the /users/{userId}/consumption-history/media-items/{mediaKind}/{mediaItemId}/{libraryId} route.
+///
+public class DeleteUserConsumptionItemHistoryEndpoint : BaseEndpoint
+{
+ private readonly ICommandHandler> _deleteConsumptionItemHistoryCommandHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling delete consumption item history commands.
+ public DeleteUserConsumptionItemHistoryEndpoint(ICommandHandler> deleteConsumptionItemHistoryCommandHandler)
+ {
+ _deleteConsumptionItemHistoryCommandHandler = deleteConsumptionItemHistoryCommandHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.DELETE);
+ Routes(ApiRoutes.LibraryStatistics.DELETE_USER_CONSUMPTION_ITEM_HISTORY);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Deletes every consumption record of a media item of a user.
+ ///
+ /// The request containing the media item and its library.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(DeleteConsumptionItemHistoryRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption records belong to the target user, and only that user or an Admin may delete them, so no intermediary may store any
+ // response of this route, including its problem responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString();
+ Result result = await _deleteConsumptionItemHistoryCommandHandler
+ .HandleAsync(new DeleteConsumptionItemHistoryCommand(targetUserId, request.MediaKind, request.MediaItemId, request.LibraryId), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpointSummary.cs
new file mode 100644
index 00000000..1ccf64b4
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteUserConsumptionItemHistoryEndpointSummary.cs
@@ -0,0 +1,101 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteUserConsumptionItemHistoryEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public DeleteUserConsumptionItemHistoryEndpointSummary()
+ {
+ Summary = "Deletes every consumption record of a media item of a user.";
+ Description = "Deletes every recorded consumption session of one media item of a user, in the library named by the route. The deletion covers every session of the item, independent of any date range, so the item disappears from the history consistently with clearing the whole history. A user can delete only their own history, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. Deleting an item that has no recorded session changes nothing and is not an error, so a retried deletion is safe; a concurrent write can still be rejected with a conflict. The resume point of the media item is not deleted: removing an item from the history and removing it from continue watching are separate user actions.";
+
+ Params["userId"] = "The Id of the user whose history is deleted. An Admin can name any user; a regular user can only name themselves.";
+ Params["mediaKind"] = "The kind of the consumed media item.";
+ Params["mediaItemId"] = "The Id of the consumed media item.";
+ Params["libraryId"] = "The Id of the media library that contains the media item.";
+
+ Response(200, "The consumption records of the media item were successfully deleted.");
+
+ Response(401, "Authentication required.", "application/problem+json",
+ example: new[]
+ {
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "Authentication failed",
+ instance = "/api/v1/users/1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(409, "The request failed because the deletion could not be stored, because the database is busy or locked, or because another request changed the same data after this request read it. Repeating the request is safe.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.10",
+ title = "General.Conflict",
+ status = 409,
+ detail = "ConcurrencyConflict",
+ instance = "/api/v1/users/1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(422, "The request did not pass validation checks.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc4918#section-11.2",
+ title = "General.Validation",
+ status = 422,
+ detail = "OneOrMoreValidationErrorsOccurred",
+ instance = "/api/v1/users/1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d/consumption-history/media-items/MusicTrack/9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f/3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "TargetUserIdIsInvalid",
+ "UnsupportedMediaKind",
+ "MediaItemIdCannotBeEmpty",
+ "LibraryIdCannotBeEmpty"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpoint.cs
new file mode 100644
index 00000000..79424078
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpoint.cs
@@ -0,0 +1,62 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+using Lumina.Presentation.Api.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Http;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
+
+///
+/// API endpoint for the /users/me/consumption-statistics/genres route.
+///
+///
+/// Uses "me" because it is always for the currently authenticated user.
+///
+public class GetGenreConsumptionEndpoint : BaseEndpoint
+{
+ private readonly IQueryHandler>> _getGenreConsumptionQueryHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling get genre consumption queries.
+ public GetGenreConsumptionEndpoint(IQueryHandler>> getGenreConsumptionQueryHandler)
+ {
+ _getGenreConsumptionQueryHandler = getGenreConsumptionQueryHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.GET);
+ Routes(ApiRoutes.LibraryStatistics.GET_GENRE_CONSUMPTION);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Gets the consumption statistics of the genres of the current user.
+ ///
+ /// The request containing the optional filters and the date range.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(GetGenreConsumptionRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption statistics belong to the authenticated user, so no intermediary may store any response of this route, including its
+ // problem responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ Result> result = await _getGenreConsumptionQueryHandler.HandleAsync(request.ToQuery(targetUserId: null), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs
new file mode 100644
index 00000000..7b738174
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs
@@ -0,0 +1,120 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.MediaConsumption;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetGenreConsumptionEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetGenreConsumptionEndpointSummary()
+ {
+ Summary = "Gets the consumption statistics of the genres of the current user.";
+ Description = "Gets the genres carried by the media items the current user consumed, grouped by lowercase name across every media kind, or restricted to one kind, one library, and a date range. Only an item with at least one session that counts towards statistics contributes, and each item contributes its genres once regardless of how many sessions it had, so a multi-genre item adds one to each of its genres, not one per session. The names are always lowercase and culture invariant, so a genre that is shared by a book and a track appears in one bucket. Genres of an item whose media item was deleted, or whose media library the user can no longer access, are not included, because their genres cannot be resolved, while their sessions still count in the summary. The statistics of another user are never returned by this route.";
+
+ ExampleRequest = new GetGenreConsumptionRequest(
+ LibraryId: null,
+ MediaKind: null,
+ FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
+ ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc)
+ );
+
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
+ RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
+ RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
+ RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
+
+ ResponseParam(response => response.Name, "The lowercase name of the genre.");
+ ResponseParam(response => response.ConsumedItemCount, "The number of distinct media items that carry the genre and were consumed.");
+ ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media items that carry the genre, in seconds.");
+
+ Response>(statusCode: 200, description: "The consumption statistics of the genres of the current user are returned.", contentType: "application/json",
+ example:
+ [
+ new GenreConsumptionResponse(
+ Name: "horror",
+ ConsumedItemCount: 3,
+ ConsumedDurationInSeconds: 5400
+ ),
+ new GenreConsumptionResponse(
+ Name: "fantasy",
+ ConsumedItemCount: 2,
+ ConsumedDurationInSeconds: 7320
+ ),
+ new GenreConsumptionResponse(
+ Name: "science fiction",
+ ConsumedItemCount: 1,
+ ConsumedDurationInSeconds: 1424.5
+ )
+ ]
+ );
+
+ Response(401, "Authentication required.", "application/problem+json",
+ example: new[]
+ {
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "Authentication failed",
+ instance = "/api/v1/users/me/consumption-statistics/genres"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/me/consumption-statistics/genres"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/me/consumption-statistics/genres",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(422, "The request did not pass validation checks.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc4918#section-11.2",
+ title = "General.Validation",
+ status = 422,
+ detail = "OneOrMoreValidationErrorsOccurred",
+ instance = "/api/v1/users/me/consumption-statistics/genres",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "LibraryIdCannotBeEmpty",
+ "UnsupportedMediaKind",
+ "ConsumptionDateRangeIsInvalid"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpoint.cs
new file mode 100644
index 00000000..0103a081
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpoint.cs
@@ -0,0 +1,62 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Mapping.MediaConsumption;
+using Lumina.Application.Core.MediaConsumption.Queries.GetGenreConsumption;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.MediaConsumption;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.Statistics;
+using Lumina.Presentation.Api.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Http;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
+
+///
+/// API endpoint for the /users/{userId}/consumption-statistics/genres route.
+///
+public class GetUserGenreConsumptionEndpoint : BaseEndpoint
+{
+ private readonly IQueryHandler>> _getGenreConsumptionQueryHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling get genre consumption queries.
+ public GetUserGenreConsumptionEndpoint(IQueryHandler>> getGenreConsumptionQueryHandler)
+ {
+ _getGenreConsumptionQueryHandler = getGenreConsumptionQueryHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(FastEndpoints.Http.GET);
+ Routes(ApiRoutes.LibraryStatistics.GET_USER_GENRE_CONSUMPTION);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Gets the consumption statistics of the genres of a user.
+ ///
+ /// The request containing the optional filters and the date range.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(GetGenreConsumptionRequest request, CancellationToken cancellationToken)
+ {
+ // The consumption statistics belong to the target user, and only that user or an Admin may read them, so no intermediary may store any response
+ // of this route, including its problem responses, and every response varies by the bearer token that authorized it.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers.Append("Vary", "Authorization");
+ // Take the target user from the route. The access policy in the query decides whether the caller is the target user or an admin, and a
+ // regular user targeting another user receives the same not authorized result as a route that names no accessible user.
+ string? targetUserId = HttpContext.Request.RouteValues["userId"]?.ToString();
+ Result> result = await _getGenreConsumptionQueryHandler.HandleAsync(request.ToQuery(targetUserId), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointSummary.cs
new file mode 100644
index 00000000..ed53aae1
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetUserGenreConsumptionEndpointSummary.cs
@@ -0,0 +1,122 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaConsumption;
+using Lumina.Contracts.Responses.MediaConsumption;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.Statistics.GetGenreConsumption;
+
+///
+/// Class used for providing a textual description for the API endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetUserGenreConsumptionEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetUserGenreConsumptionEndpointSummary()
+ {
+ Summary = "Gets the consumption statistics of the genres of a user.";
+ Description = "Gets the genres carried by the media items a user consumed, grouped by lowercase name across every media kind, or restricted to one kind, one library, and a date range. A user can read only their own statistics, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. Only an item with at least one session that counts towards statistics contributes, and each item contributes its genres once regardless of how many sessions it had, so a multi-genre item adds one to each of its genres, not one per session. The names are always lowercase and culture invariant, so a genre that is shared by a book and a track appears in one bucket. Genres of an item whose media item was deleted, or whose media library the user can no longer access, are not included, because their genres cannot be resolved, while their sessions still count in the summary.";
+
+ ExampleRequest = new GetGenreConsumptionRequest(
+ LibraryId: null,
+ MediaKind: null,
+ FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
+ ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc)
+ );
+
+ Params["userId"] = "The Id of the user whose statistics are retrieved. An Admin can name any user; a regular user can only name themselves.";
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
+ RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
+ RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
+ RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
+
+ ResponseParam(response => response.Name, "The lowercase name of the genre.");
+ ResponseParam(response => response.ConsumedItemCount, "The number of distinct media items that carry the genre and were consumed.");
+ ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media items that carry the genre, in seconds.");
+
+ Response>(statusCode: 200, description: "The consumption statistics of the genres of the user are returned.", contentType: "application/json",
+ example:
+ [
+ new GenreConsumptionResponse(
+ Name: "horror",
+ ConsumedItemCount: 3,
+ ConsumedDurationInSeconds: 5400
+ ),
+ new GenreConsumptionResponse(
+ Name: "fantasy",
+ ConsumedItemCount: 2,
+ ConsumedDurationInSeconds: 7320
+ ),
+ new GenreConsumptionResponse(
+ Name: "science fiction",
+ ConsumedItemCount: 1,
+ ConsumedDurationInSeconds: 1424.5
+ )
+ ]
+ );
+
+ Response(401, "Authentication required.", "application/problem+json",
+ example: new[]
+ {
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "Authentication failed",
+ instance = "/api/v1/users/{userId}/consumption-statistics/genres"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token has expired",
+ instance = "/api/v1/users/{userId}/consumption-statistics/genres"
+ }
+ }
+ );
+
+ Response(403, "The request failed because the authenticated request does not carry the identity of a user, or because the current user is neither the target user nor an Admin.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc9110#section-15.5.4",
+ title = "General.Unauthorized",
+ status = 403,
+ detail = "NotAuthorized",
+ instance = "/api/v1/users/{userId}/consumption-statistics/genres",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+
+ Response(422, "The request did not pass validation checks.", "application/problem+json",
+ example: new
+ {
+ type = "https://tools.ietf.org/html/rfc4918#section-11.2",
+ title = "General.Validation",
+ status = 422,
+ detail = "OneOrMoreValidationErrorsOccurred",
+ instance = "/api/v1/users/{userId}/consumption-statistics/genres",
+ errors = new Dictionary
+ {
+ {
+ "General.Validation", new[]
+ {
+ "TargetUserIdIsInvalid",
+ "LibraryIdCannotBeEmpty",
+ "UnsupportedMediaKind",
+ "ConsumptionDateRangeIsInvalid"
+ }
+ }
+ },
+ traceId = "00-2470be4248a2a5a0c6f70579975a6954-b9c3ba9544a03500-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs
index 51cc7d80..cf7aa224 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs
@@ -23,19 +23,23 @@ public class GetMostConsumedEndpointSummary : Summary request.LibraryId, "The Id of the media library to restrict the history to. Optional.");
RequestParam(request => request.MediaKind, "The kind of media to restrict the history to. Optional.");
RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional.");
RequestParam(request => request.PerPage, "The number of media items per page. Optional.");
+ RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
+ RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
ResponseParam>(response => response.Data, "The most consumed media items of the requested page, ordered by counted sessions, consumed duration, and last consumption date.");
ResponseParam>(response => response.CurrentPage, "The current page number.");
@@ -55,7 +59,7 @@ public class GetMostConsumedEndpointSummary : Summary(response => response.CompletedSessionCount, "The number of consumption sessions of the media item that completed.");
ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media item, over all of its sessions, in seconds.");
- Response(statusCode: 200, description: "The most consumed media items of the current user are returned.", contentType: "application/json",
+ Response(200, "The most consumed media items of the current user are returned.", "application/json",
example: new PaginatedResponse
{
Data =
@@ -144,7 +148,8 @@ public class GetMostConsumedEndpointSummary : Summary request.MediaKind, "The kind of media to restrict the history to. Optional.");
RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional.");
RequestParam(request => request.PerPage, "The number of media items per page. Optional.");
+ RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
+ RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
ResponseParam>(response => response.Data, "The most consumed media items of the requested page, ordered by counted sessions, consumed duration, and last consumption date.");
ResponseParam>(response => response.CurrentPage, "The current page number.");
@@ -56,7 +60,7 @@ public class GetUserMostConsumedEndpointSummary : Summary(response => response.CompletedSessionCount, "The number of consumption sessions of the media item that completed.");
ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media item, over all of its sessions, in seconds.");
- Response(statusCode: 200, description: "The most consumed media items of the user are returned.", contentType: "application/json",
+ Response(200, "The most consumed media items of the user are returned.", "application/json",
example: new PaginatedResponse
{
Data =
@@ -146,7 +150,8 @@ public class GetUserMostConsumedEndpointSummary : Summary request.LibraryId, "The Id of the media library to restrict the history to. Optional.");
RequestParam(request => request.MediaKind, "The kind of media to restrict the history to. Optional.");
RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional.");
RequestParam(request => request.PerPage, "The number of media items per page. Optional.");
+ RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
+ RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
ResponseParam>(response => response.Data, "The recently consumed media items of the requested page, from the most recently consumed.");
ResponseParam>(response => response.CurrentPage, "The current page number.");
@@ -55,7 +59,7 @@ public class GetRecentlyConsumedEndpointSummary : Summary(response => response.CompletedSessionCount, "The number of consumption sessions of the media item that completed.");
ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media item, over all of its sessions, in seconds.");
- Response(statusCode: 200, description: "The recently consumed media items of the current user are returned.", contentType: "application/json",
+ Response(200, "The recently consumed media items of the current user are returned.", "application/json",
example: new PaginatedResponse
{
Data =
@@ -144,7 +148,8 @@ public class GetRecentlyConsumedEndpointSummary : Summary request.MediaKind, "The kind of media to restrict the history to. Optional.");
RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional.");
RequestParam(request => request.PerPage, "The number of media items per page. Optional.");
+ RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
+ RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
ResponseParam>(response => response.Data, "The recently consumed media items of the requested page, from the most recently consumed.");
ResponseParam>(response => response.CurrentPage, "The current page number.");
@@ -56,7 +60,7 @@ public class GetUserRecentlyConsumedEndpointSummary : Summary(response => response.CompletedSessionCount, "The number of consumption sessions of the media item that completed.");
ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media item, over all of its sessions, in seconds.");
- Response(statusCode: 200, description: "The recently consumed media items of the user are returned.", contentType: "application/json",
+ Response(200, "The recently consumed media items of the user are returned.", "application/json",
example: new PaginatedResponse
{
Data =
@@ -146,7 +150,8 @@ public class GetUserRecentlyConsumedEndpointSummary : Summary
- /// Gets the consumption statistics of the tags and genres of the current user.
+ /// Gets the consumption statistics of the tags of the current user.
///
/// The request containing the optional filters and the date range.
/// Cancellation token that can be used to stop the execution.
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs
index ef95b6af..ef8ebdb5 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs
@@ -2,7 +2,6 @@
using FastEndpoints;
using Lumina.Contracts.Requests.MediaConsumption;
using Lumina.Contracts.Responses.MediaConsumption;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -21,46 +20,40 @@ public class GetTagConsumptionEndpointSummary : Summary
public GetTagConsumptionEndpointSummary()
{
- Summary = "Gets the consumption statistics of the tags and genres of the current user.";
- Description = "Gets the tags and genres carried by the media items the current user consumed, grouped by lowercase name across every media kind, or restricted to one kind, one library, one term kind, and a date range. Only an item with at least one session that counts towards statistics contributes, and each item contributes its terms once regardless of how many sessions it had, so a multi-genre item adds one to each of its genres, not one per session. The names are always lowercase and culture invariant, so a tag or genre that is shared by a book and a track appears in one bucket. Tags and genres of an item whose media item was deleted, or whose media library the user can no longer access, are not included, because their terms cannot be resolved, while their sessions still count in the summary. The statistics of another user are never returned by this route.";
+ Summary = "Gets the consumption statistics of the tags of the current user.";
+ Description = "Gets the tags carried by the media items the current user consumed, grouped by lowercase name across every media kind, or restricted to one kind, one library, and a date range. Only an item with at least one session that counts towards statistics contributes, and each item contributes its tags once regardless of how many sessions it had, so a multi-tag item adds one to each of its tags, not one per session. The names are always lowercase and culture invariant, so a tag that is shared by a book and a track appears in one bucket. Tags of an item whose media item was deleted, or whose media library the user can no longer access, are not included, because their tags cannot be resolved, while their sessions still count in the summary. The statistics of another user are never returned by this route.";
ExampleRequest = new GetTagConsumptionRequest(
LibraryId: null,
MediaKind: null,
- TagKind: null,
FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc)
);
RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
- RequestParam(request => request.TagKind, "Whether to return genres or tags. Optional.");
RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
- ResponseParam(response => response.Name, "The lowercase name of the tag or genre.");
- ResponseParam(response => response.TagKind, "Whether the entry is a genre or a tag.");
- ResponseParam(response => response.ConsumedItemCount, "The number of distinct media items that carry the term and were consumed.");
- ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media items that carry the term, in seconds.");
+ ResponseParam(response => response.Name, "The lowercase name of the tag.");
+ ResponseParam(response => response.ConsumedItemCount, "The number of distinct media items that carry the tag and were consumed.");
+ ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media items that carry the tag, in seconds.");
- Response>(statusCode: 200, description: "The consumption statistics of the tags and genres of the current user are returned.", contentType: "application/json",
+ Response>(statusCode: 200, description: "The consumption statistics of the tags of the current user are returned.", contentType: "application/json",
example:
[
new TagConsumptionResponse(
- Name: "horror",
- TagKind: TagKind.Genre,
+ Name: "favourite",
ConsumedItemCount: 3,
ConsumedDurationInSeconds: 5400
),
new TagConsumptionResponse(
- Name: "fantasy",
- TagKind: TagKind.Genre,
+ Name: "book-club",
ConsumedItemCount: 2,
ConsumedDurationInSeconds: 7320
),
new TagConsumptionResponse(
- Name: "favourite",
- TagKind: TagKind.Tag,
+ Name: "comfort-read",
ConsumedItemCount: 1,
ConsumedDurationInSeconds: 1424.5
)
@@ -116,7 +109,6 @@ public class GetTagConsumptionEndpointSummary : Summary
- /// Gets the consumption statistics of the tags and genres of a user.
+ /// Gets the consumption statistics of the tags of a user.
///
/// The request containing the optional filters and the date range.
/// Cancellation token that can be used to stop the execution.
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointSummary.cs
index df006d73..068fc130 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointSummary.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetTagConsumption/GetUserTagConsumptionEndpointSummary.cs
@@ -2,7 +2,6 @@
using FastEndpoints;
using Lumina.Contracts.Requests.MediaConsumption;
using Lumina.Contracts.Responses.MediaConsumption;
-using Lumina.Domain.SharedKernel.Common.Enums.MediaConsumption;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
@@ -21,13 +20,12 @@ public class GetUserTagConsumptionEndpointSummary : Summary
public GetUserTagConsumptionEndpointSummary()
{
- Summary = "Gets the consumption statistics of the tags and genres of a user.";
- Description = "Gets the tags and genres carried by the media items a user consumed, grouped by lowercase name across every media kind, or restricted to one kind, one library, one term kind, and a date range. A user can read only their own statistics, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. Only an item with at least one session that counts towards statistics contributes, and each item contributes its terms once regardless of how many sessions it had, so a multi-genre item adds one to each of its genres, not one per session. The names are always lowercase and culture invariant, so a tag or genre that is shared by a book and a track appears in one bucket. Tags and genres of an item whose media item was deleted, or whose media library the user can no longer access, are not included, because their terms cannot be resolved, while their sessions still count in the summary.";
+ Summary = "Gets the consumption statistics of the tags of a user.";
+ Description = "Gets the tags carried by the media items a user consumed, grouped by lowercase name across every media kind, or restricted to one kind, one library, and a date range. A user can read only their own statistics, while an Admin can select any user with the userId route parameter; a regular user targeting another user receives the same not authorized result as a route that names no accessible user. Only an item with at least one session that counts towards statistics contributes, and each item contributes its tags once regardless of how many sessions it had, so a multi-tag item adds one to each of its tags, not one per session. The names are always lowercase and culture invariant, so a tag that is shared by a book and a track appears in one bucket. Tags of an item whose media item was deleted, or whose media library the user can no longer access, are not included, because their tags cannot be resolved, while their sessions still count in the summary.";
ExampleRequest = new GetTagConsumptionRequest(
LibraryId: null,
MediaKind: null,
- TagKind: null,
FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc)
);
@@ -35,33 +33,28 @@ public class GetUserTagConsumptionEndpointSummary : Summary request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
- RequestParam(request => request.TagKind, "Whether to return genres or tags. Optional.");
RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
- ResponseParam(response => response.Name, "The lowercase name of the tag or genre.");
- ResponseParam(response => response.TagKind, "Whether the entry is a genre or a tag.");
- ResponseParam(response => response.ConsumedItemCount, "The number of distinct media items that carry the term and were consumed.");
- ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media items that carry the term, in seconds.");
+ ResponseParam(response => response.Name, "The lowercase name of the tag.");
+ ResponseParam(response => response.ConsumedItemCount, "The number of distinct media items that carry the tag and were consumed.");
+ ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media items that carry the tag, in seconds.");
- Response>(statusCode: 200, description: "The consumption statistics of the tags and genres of the user are returned.", contentType: "application/json",
+ Response>(statusCode: 200, description: "The consumption statistics of the tags of the user are returned.", contentType: "application/json",
example:
[
new TagConsumptionResponse(
- Name: "horror",
- TagKind: TagKind.Genre,
+ Name: "favourite",
ConsumedItemCount: 3,
ConsumedDurationInSeconds: 5400
),
new TagConsumptionResponse(
- Name: "fantasy",
- TagKind: TagKind.Genre,
+ Name: "book-club",
ConsumedItemCount: 2,
ConsumedDurationInSeconds: 7320
),
new TagConsumptionResponse(
- Name: "favourite",
- TagKind: TagKind.Tag,
+ Name: "comfort-read",
ConsumedItemCount: 1,
ConsumedDurationInSeconds: 1424.5
)
@@ -118,7 +111,6 @@ public class GetUserTagConsumptionEndpointSummary : Summary
-/// Data transfer object for the listening statistics of the current user.
-///
-/// The total duration the user listened to, over every recorded play, in seconds.
-/// The number of recorded plays that count as plays. An in-progress play counts once it reaches the threshold, so this total can exceed the completed and stopped plays together.
-/// The number of recorded plays that completed.
-/// The number of recorded plays that stopped before the track completed and count as plays.
-/// The fraction of the plays that count as plays that completed, between 0 and 1, or 0 when there is no counted play.
-[DebuggerDisplay("TotalPlayCount: {TotalPlayCount}; CompletedPlayCount: {CompletedPlayCount}")]
-public sealed record MusicPlayStatisticsDto(
- double TotalListeningDurationInSeconds,
- int TotalPlayCount,
- int CompletedPlayCount,
- int StoppedPlayCount,
- double CompletionRate
-);
diff --git a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlayHistory/PlayedTrackDto.cs b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlayHistory/PlayedTrackDto.cs
deleted file mode 100644
index 36ed80a0..00000000
--- a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlayHistory/PlayedTrackDto.cs
+++ /dev/null
@@ -1,37 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using System;
-using System.Diagnostics;
-#endregion
-
-namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary.PlayHistory;
-
-///
-/// Data transfer object for a track of the listening statistics of the current user, together with its aggregated play counts.
-///
-/// The Id of the track.
-/// The Id of the media library that contains the track.
-/// The Id of the album that contains the track.
-/// The Id of the artist that produced the track.
-/// The title of the track, if it still exists and the user can access its library.
-/// The title of the album that contains the track, if it still exists and the user can access its library.
-/// The name of the artist that produced the track, if it still exists and the user can access its library.
-/// The path of the cover art of the album, if available.
-/// The date and time of the last recorded activity of the track's most recent play.
-/// The number of plays of the track that count as plays.
-/// The number of plays of the track that completed.
-/// The duration the user listened to the track, over all of its counted plays, in seconds.
-[DebuggerDisplay("TrackId: {TrackId}; PlayCount: {PlayCount}")]
-public sealed record PlayedTrackDto(
- Guid TrackId,
- Guid LibraryId,
- Guid AlbumId,
- Guid ArtistId,
- string? Title,
- string? AlbumTitle,
- string? ArtistName,
- string? CoverPath,
- DateTime LastPlayedOnUtc,
- int PlayCount,
- int CompletedPlayCount,
- double ListenedDurationInSeconds
-);
diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/AllUsersConsumptionStatisticsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/AllUsersConsumptionStatisticsDto.cs
new file mode 100644
index 00000000..1712e52d
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/AllUsersConsumptionStatisticsDto.cs
@@ -0,0 +1,17 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+
+///
+/// Data transfer object for the consumption statistics of every user, together with their combined totals.
+///
+/// The combined consumption statistics of every user.
+/// The consumption statistics of each user.
+[DebuggerDisplay("UserCount: {Users.Count}; CountedSessionCount: {Total.CountedSessionCount}")]
+public sealed record AllUsersConsumptionStatisticsDto(
+ ConsumptionTotalsDto Total,
+ IReadOnlyList Users
+);
diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumedItemDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumedItemDto.cs
new file mode 100644
index 00000000..041de9f4
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumedItemDto.cs
@@ -0,0 +1,38 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+
+///
+/// Data transfer object for a media item of the consumption history, together with its aggregated consumption counts and display details.
+///
+/// The kind of the consumed media item.
+/// The Id of the consumed media item.
+/// The Id of the media library that contains the media item.
+/// Whether the media item still exists and can be accessed by the user. When , the title, collection title, creator name, and cover path are blank, while the identity and aggregation fields remain.
+/// The title of the media item, or an empty string when the item is not available.
+/// The title of the collection that contains the media item, or an empty string when there is none.
+/// The name of the creator of the media item, or an empty string when there is none.
+/// The path of the cover art of the media item, if available.
+/// The date and time when the media item was last consumed.
+/// The number of consumption sessions of the media item that count towards statistics.
+/// The number of consumption sessions of the media item that completed.
+/// The active duration consumed in the media item, over all of its sessions, in seconds.
+[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}; CountedSessionCount: {CountedSessionCount}")]
+public sealed record ConsumedItemDto(
+ MediaKind MediaKind,
+ Guid MediaItemId,
+ Guid LibraryId,
+ bool IsAvailable,
+ string Title,
+ string CollectionTitle,
+ string CreatorName,
+ string? CoverPath,
+ DateTime LastConsumedOnUtc,
+ int CountedSessionCount,
+ int CompletedSessionCount,
+ double ConsumedDurationInSeconds
+);
diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumptionSummaryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumptionSummaryDto.cs
new file mode 100644
index 00000000..624c709a
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumptionSummaryDto.cs
@@ -0,0 +1,28 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+
+///
+/// Data transfer object for the consumption statistics of a user.
+///
+/// The Id of the user the statistics belong to.
+/// The total duration consumed over every recorded session, in seconds.
+/// The number of recorded sessions that count towards statistics.
+/// The number of recorded sessions that completed.
+/// The number of recorded sessions that stopped before they completed and count towards statistics.
+/// The fraction of the counted sessions that completed, between 0 and 1, or 0 when there is no counted session.
+/// The consumption statistics broken down by media kind.
+[DebuggerDisplay("UserId: {UserId}; CountedSessionCount: {CountedSessionCount}")]
+public sealed record ConsumptionSummaryDto(
+ Guid UserId,
+ double TotalConsumedDurationInSeconds,
+ int CountedSessionCount,
+ int CompletedSessionCount,
+ int StoppedSessionCount,
+ double CompletionRate,
+ IReadOnlyList MediaKindSummaries
+);
diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumptionTotalsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumptionTotalsDto.cs
new file mode 100644
index 00000000..3ab6abcb
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/ConsumptionTotalsDto.cs
@@ -0,0 +1,25 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+
+///
+/// Data transfer object for the combined consumption statistics of every user.
+///
+/// The total duration consumed over every recorded session of every user, in seconds.
+/// The number of recorded sessions of every user that count towards statistics.
+/// The number of recorded sessions of every user that completed.
+/// The number of recorded sessions of every user that stopped before they completed and count towards statistics.
+/// The fraction of the counted sessions of every user that completed, between 0 and 1, or 0 when there is no counted session.
+/// The combined consumption statistics broken down by media kind.
+[DebuggerDisplay("CountedSessionCount: {CountedSessionCount}; CompletedSessionCount: {CompletedSessionCount}")]
+public sealed record ConsumptionTotalsDto(
+ double TotalConsumedDurationInSeconds,
+ int CountedSessionCount,
+ int CompletedSessionCount,
+ int StoppedSessionCount,
+ double CompletionRate,
+ IReadOnlyList MediaKindSummaries
+);
diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/GenreConsumptionDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/GenreConsumptionDto.cs
new file mode 100644
index 00000000..48b116e4
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/GenreConsumptionDto.cs
@@ -0,0 +1,18 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+
+///
+/// Data transfer object for the consumption statistics of a genre, grouped across media kinds.
+///
+/// The lowercase name of the genre.
+/// The number of distinct media items that carry the genre and were consumed.
+/// The active duration consumed in the media items that carry the genre, in seconds.
+[DebuggerDisplay("Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")]
+public sealed record GenreConsumptionDto(
+ string Name,
+ int ConsumedItemCount,
+ double ConsumedDurationInSeconds
+);
diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/MediaKindConsumptionSummaryDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/MediaKindConsumptionSummaryDto.cs
new file mode 100644
index 00000000..bdb52f31
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/MediaKindConsumptionSummaryDto.cs
@@ -0,0 +1,25 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+
+///
+/// Data transfer object for the consumption statistics of one kind of media.
+///
+/// The kind of media the statistics belong to.
+/// The total duration consumed over every recorded session of the media kind, in seconds.
+/// The number of recorded sessions of the media kind that count towards statistics.
+/// The number of recorded sessions of the media kind that completed.
+/// The number of recorded sessions of the media kind that stopped before they completed and count towards statistics.
+/// The fraction of the counted sessions of the media kind that completed, between 0 and 1.
+[DebuggerDisplay("MediaKind: {MediaKind}; CountedSessionCount: {CountedSessionCount}")]
+public sealed record MediaKindConsumptionSummaryDto(
+ MediaKind MediaKind,
+ double TotalConsumedDurationInSeconds,
+ int CountedSessionCount,
+ int CompletedSessionCount,
+ int StoppedSessionCount,
+ double CompletionRate
+);
diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/StatisticsPageDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/StatisticsPageDto.cs
new file mode 100644
index 00000000..60ca939b
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/StatisticsPageDto.cs
@@ -0,0 +1,43 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+
+///
+/// Data transfer object for the data and the proxy routes of the statistics page.
+///
+/// The localized title of the page.
+/// Whether the current user is an administrator and can select another user or all users.
+/// The Id of the current user, or when it cannot be determined.
+/// The culture of the page.
+/// The route that returns the statistics of the selected user.
+/// The route that returns the statistics of every user.
+/// The route that returns the recently consumed media items of the selected user.
+/// The route that returns the most consumed media items of the selected user.
+/// The route that returns the tag consumption of the selected user.
+/// The route that returns the genre consumption of the selected user.
+/// The route that returns the libraries available for the library filter.
+/// The route that returns the users available for the administrator user selector, or an empty string for a regular user.
+/// The route that deletes every consumption record of a media item.
+/// The route that deletes the consumption history of the selected user.
+/// The route that deletes the resume points of the selected user.
+[DebuggerDisplay("IsAdmin: {IsAdmin}; CurrentUserId: {CurrentUserId}")]
+public sealed record StatisticsPageDto(
+ string Title,
+ bool IsAdmin,
+ Guid? CurrentUserId,
+ string Culture,
+ string GetStatisticsUrl,
+ string GetAllUsersStatisticsUrl,
+ string GetRecentlyConsumedUrl,
+ string GetMostConsumedUrl,
+ string GetTagConsumptionUrl,
+ string GetGenreConsumptionUrl,
+ string GetLibrariesUrl,
+ string GetUsersUrl,
+ string DeleteConsumptionItemHistoryUrl,
+ string ClearConsumptionHistoryUrl,
+ string ClearResumePointsUrl
+);
diff --git a/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/TagConsumptionDto.cs b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/TagConsumptionDto.cs
new file mode 100644
index 00000000..9d377976
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/DTO/MediaConsumption/TagConsumptionDto.cs
@@ -0,0 +1,18 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+
+///
+/// Data transfer object for the consumption statistics of a tag, grouped across media kinds.
+///
+/// The lowercase name of the tag.
+/// The number of distinct media items that carry the tag and were consumed.
+/// The active duration consumed in the media items that carry the tag, in seconds.
+[DebuggerDisplay("Name: {Name}; ConsumedItemCount: {ConsumedItemCount}")]
+public sealed record TagConsumptionDto(
+ string Name,
+ int ConsumedItemCount,
+ double ConsumedDurationInSeconds
+);
diff --git a/src/Lumina.Presentation.Web/Common/Enums/MediaConsumption/MediaKind.cs b/src/Lumina.Presentation.Web/Common/Enums/MediaConsumption/MediaKind.cs
new file mode 100644
index 00000000..6a1c7401
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Enums/MediaConsumption/MediaKind.cs
@@ -0,0 +1,52 @@
+namespace Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+
+///
+/// Enumeration for the kinds of media items of the consumption history and statistics.
+///
+public enum MediaKind
+{
+ ///
+ /// No media kind. Used as the default value; it is not a valid kind for a media item.
+ ///
+ None = 0,
+
+ ///
+ /// A track of a music library.
+ ///
+ MusicTrack,
+
+ ///
+ /// An episode of a podcast.
+ ///
+ PodcastEpisode,
+
+ ///
+ /// An audiobook.
+ ///
+ Audiobook,
+
+ ///
+ /// A movie.
+ ///
+ Movie,
+
+ ///
+ /// An episode of a TV show.
+ ///
+ TvEpisode,
+
+ ///
+ /// A book of a written content library.
+ ///
+ Book,
+
+ ///
+ /// A photo.
+ ///
+ Photo,
+
+ ///
+ /// A video file.
+ ///
+ Video
+}
diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayedRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayedRequest.cs
deleted file mode 100644
index 4dc4add5..00000000
--- a/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayedRequest.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using System.Diagnostics;
-#endregion
-
-namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.PlayHistory;
-
-///
-/// Represents a request for getting a page of the most played tracks of the current user.
-///
-/// The one based page of tracks to return. Optional. Defaults to 1.
-/// The number of tracks per page. Optional. Defaults to 10.
-[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
-public record GetMostPlayedRequest(
- int? CurrentPage,
- int? PerPage
-);
diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayedRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayedRequest.cs
deleted file mode 100644
index 5a5c0244..00000000
--- a/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayedRequest.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-#region ========================================================================= USING =====================================================================================
-using System.Diagnostics;
-#endregion
-
-namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.PlayHistory;
-
-///
-/// Represents a request for getting a page of the recently played tracks of the current user.
-///
-/// The one based page of tracks to return. Optional. Defaults to 1.
-/// The number of tracks per page. Optional. Defaults to 10.
-[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
-public record GetRecentlyPlayedRequest(
- int? CurrentPage,
- int? PerPage
-);
diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/ClearConsumptionHistoryRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/ClearConsumptionHistoryRequest.cs
new file mode 100644
index 00000000..3cfc8a43
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/ClearConsumptionHistoryRequest.cs
@@ -0,0 +1,14 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+
+///
+/// Represents a request to delete the consumption history of a user.
+///
+/// The Id of the user whose history is deleted. Optional; when omitted, the current user is used.
+[DebuggerDisplay("UserId: {UserId}")]
+public sealed record ClearConsumptionHistoryRequest(
+ string? UserId
+);
diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/ClearResumePointsRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/ClearResumePointsRequest.cs
new file mode 100644
index 00000000..2eb58a34
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/ClearResumePointsRequest.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+
+///
+/// Represents a request to delete the resume points of a user.
+///
+/// The Id of the user whose resume points are deleted. Optional; when omitted, the current user is used.
+/// The Id of the media library to restrict the deletion to. Optional.
+[DebuggerDisplay("UserId: {UserId}; LibraryId: {LibraryId}")]
+public sealed record ClearResumePointsRequest(
+ string? UserId,
+ string? LibraryId
+);
diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/DeleteConsumptionItemHistoryRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/DeleteConsumptionItemHistoryRequest.cs
new file mode 100644
index 00000000..30c20d47
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/DeleteConsumptionItemHistoryRequest.cs
@@ -0,0 +1,22 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+
+///
+/// Represents a request to delete every consumption record of a media item.
+///
+/// The Id of the user whose history is deleted. Optional; when omitted, the current user is used.
+/// The kind of the consumed media item.
+/// The Id of the consumed media item.
+/// The Id of the media library that contains the media item.
+[DebuggerDisplay("UserId: {UserId}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
+public sealed record DeleteConsumptionItemHistoryRequest(
+ string? UserId,
+ MediaKind MediaKind,
+ Guid MediaItemId,
+ Guid LibraryId
+);
diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetAllUsersConsumptionStatisticsRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetAllUsersConsumptionStatisticsRequest.cs
new file mode 100644
index 00000000..b4355740
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetAllUsersConsumptionStatisticsRequest.cs
@@ -0,0 +1,22 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+
+///
+/// Represents a request for getting the consumption statistics of every user.
+///
+/// The Id of the media library to restrict the statistics to. Optional.
+/// The kind of media to restrict the statistics to. Optional.
+/// The inclusive start of the date range. Optional.
+/// The inclusive end of the date range. Optional.
+[DebuggerDisplay("MediaKind: {MediaKind}; FromUtc: {FromUtc}; ToUtc: {ToUtc}")]
+public sealed record GetAllUsersConsumptionStatisticsRequest(
+ string? LibraryId,
+ MediaKind? MediaKind,
+ DateTime? FromUtc,
+ DateTime? ToUtc
+);
diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetConsumptionStatisticsRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetConsumptionStatisticsRequest.cs
new file mode 100644
index 00000000..f87208b3
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetConsumptionStatisticsRequest.cs
@@ -0,0 +1,24 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+
+///
+/// Represents a request for getting the consumption statistics of a user.
+///
+/// The Id of the user whose statistics are retrieved. Optional; when omitted, the current user is used.
+/// The Id of the media library to restrict the statistics to. Optional.
+/// The kind of media to restrict the statistics to. Optional.
+/// The inclusive start of the date range. Optional.
+/// The inclusive end of the date range. Optional.
+[DebuggerDisplay("UserId: {UserId}; MediaKind: {MediaKind}")]
+public sealed record GetConsumptionStatisticsRequest(
+ string? UserId,
+ string? LibraryId,
+ MediaKind? MediaKind,
+ DateTime? FromUtc,
+ DateTime? ToUtc
+);
diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetGenreConsumptionRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetGenreConsumptionRequest.cs
new file mode 100644
index 00000000..53a9ef80
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetGenreConsumptionRequest.cs
@@ -0,0 +1,24 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+
+///
+/// Represents a request for getting the consumption statistics of the genres of a user.
+///
+/// The Id of the user whose statistics are retrieved. Optional; when omitted, the current user is used.
+/// The Id of the media library to restrict the statistics to. Optional.
+/// The kind of media to restrict the statistics to. Optional.
+/// The inclusive start of the date range. Optional.
+/// The inclusive end of the date range. Optional.
+[DebuggerDisplay("UserId: {UserId}; MediaKind: {MediaKind}; FromUtc: {FromUtc}")]
+public sealed record GetGenreConsumptionRequest(
+ string? UserId,
+ string? LibraryId,
+ MediaKind? MediaKind,
+ DateTime? FromUtc,
+ DateTime? ToUtc
+);
diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetMostConsumedRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetMostConsumedRequest.cs
new file mode 100644
index 00000000..d9cd7cd3
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetMostConsumedRequest.cs
@@ -0,0 +1,28 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+
+///
+/// Represents a request for getting a window of the most consumed media items of a user.
+///
+/// The Id of the user whose history is retrieved. Optional; when omitted, the current user is used.
+/// The Id of the media library to restrict the history to. Optional.
+/// The kind of media to restrict the history to. Optional.
+/// The inclusive start of the date range. Optional.
+/// The inclusive end of the date range. Optional.
+/// The one based page of media items to return. Optional.
+/// The number of media items per page. Optional.
+[DebuggerDisplay("UserId: {UserId}; MediaKind: {MediaKind}; CurrentPage: {CurrentPage}")]
+public sealed record GetMostConsumedRequest(
+ string? UserId,
+ string? LibraryId,
+ MediaKind? MediaKind,
+ DateTime? FromUtc,
+ DateTime? ToUtc,
+ int? CurrentPage,
+ int? PerPage
+);
diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetRecentlyConsumedRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetRecentlyConsumedRequest.cs
new file mode 100644
index 00000000..9463c355
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetRecentlyConsumedRequest.cs
@@ -0,0 +1,28 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+
+///
+/// Represents a request for getting a window of the recently consumed media items of a user.
+///
+/// The Id of the user whose history is retrieved. Optional; when omitted, the current user is used.
+/// The Id of the media library to restrict the history to. Optional.
+/// The kind of media to restrict the history to. Optional.
+/// The inclusive start of the date range. Optional.
+/// The inclusive end of the date range. Optional.
+/// The one based page of media items to return. Optional.
+/// The number of media items per page. Optional.
+[DebuggerDisplay("UserId: {UserId}; MediaKind: {MediaKind}; CurrentPage: {CurrentPage}")]
+public sealed record GetRecentlyConsumedRequest(
+ string? UserId,
+ string? LibraryId,
+ MediaKind? MediaKind,
+ DateTime? FromUtc,
+ DateTime? ToUtc,
+ int? CurrentPage,
+ int? PerPage
+);
diff --git a/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetTagConsumptionRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetTagConsumptionRequest.cs
new file mode 100644
index 00000000..744acaaf
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Requests/Library/Statistics/GetTagConsumptionRequest.cs
@@ -0,0 +1,24 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+
+///
+/// Represents a request for getting the consumption statistics of the tags of a user.
+///
+/// The Id of the user whose statistics are retrieved. Optional; when omitted, the current user is used.
+/// The Id of the media library to restrict the statistics to. Optional.
+/// The kind of media to restrict the statistics to. Optional.
+/// The inclusive start of the date range. Optional.
+/// The inclusive end of the date range. Optional.
+[DebuggerDisplay("UserId: {UserId}; MediaKind: {MediaKind}; FromUtc: {FromUtc}")]
+public sealed record GetTagConsumptionRequest(
+ string? UserId,
+ string? LibraryId,
+ MediaKind? MediaKind,
+ DateTime? FromUtc,
+ DateTime? ToUtc
+);
diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.LibraryStatistics.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.LibraryStatistics.cs
new file mode 100644
index 00000000..ea682d5f
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.LibraryStatistics.cs
@@ -0,0 +1,31 @@
+namespace Lumina.Presentation.Web.Common.Routes;
+
+///
+/// Class for the collection of remote API routes called by this Web application.
+///
+public static partial class ApiRoutes
+{
+ ///
+ /// Routes for the consumption history, consumption statistics, and resume points of the remote API.
+ ///
+ public static class LibraryStatistics
+ {
+ public const string GET_RECENTLY_CONSUMED = "users/me/consumption-history/recently-consumed";
+ public const string GET_MOST_CONSUMED = "users/me/consumption-history/most-consumed";
+ public const string GET_CONSUMPTION_STATISTICS = "users/me/consumption-statistics";
+ public const string GET_TAG_CONSUMPTION = "users/me/consumption-statistics/tags";
+ public const string GET_GENRE_CONSUMPTION = "users/me/consumption-statistics/genres";
+ public const string GET_USER_RECENTLY_CONSUMED = "users/{userId}/consumption-history/recently-consumed";
+ public const string GET_USER_MOST_CONSUMED = "users/{userId}/consumption-history/most-consumed";
+ public const string GET_USER_CONSUMPTION_STATISTICS = "users/{userId}/consumption-statistics";
+ public const string GET_USER_TAG_CONSUMPTION = "users/{userId}/consumption-statistics/tags";
+ public const string GET_USER_GENRE_CONSUMPTION = "users/{userId}/consumption-statistics/genres";
+ public const string GET_ALL_USERS_CONSUMPTION_STATISTICS = "users/consumption-statistics";
+ public const string DELETE_CONSUMPTION_ITEM_HISTORY = "users/me/consumption-history/media-items/{mediaKind}/{mediaItemId}/{libraryId}";
+ public const string DELETE_USER_CONSUMPTION_ITEM_HISTORY = "users/{userId}/consumption-history/media-items/{mediaKind}/{mediaItemId}/{libraryId}";
+ public const string CLEAR_CONSUMPTION_HISTORY = "users/me/consumption-history";
+ public const string CLEAR_USER_CONSUMPTION_HISTORY = "users/{userId}/consumption-history";
+ public const string CLEAR_RESUME_POINTS = "users/me/media-resume-points";
+ public const string CLEAR_USER_RESUME_POINTS = "users/{userId}/media-resume-points";
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.PlayStatistics.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.PlayStatistics.cs
deleted file mode 100644
index 744299fd..00000000
--- a/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.PlayStatistics.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-namespace Lumina.Presentation.Web.Common.Routes;
-
-///
-/// Class for the collection of remote API routes called by this Web application.
-///
-public static partial class ApiRoutes
-{
- ///
- /// Routes for the music play statistics endpoints of the remote API.
- ///
- public static class PlayStatistics
- {
- public const string GET_RECENTLY_PLAYED = "users/me/music-play-history/recently-played";
- public const string GET_MOST_PLAYED = "users/me/music-play-history/most-played";
- public const string GET_MUSIC_PLAY_STATISTICS = "users/me/music-play-history/statistics";
- }
-}
diff --git a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryStatistics.cs b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryStatistics.cs
index e0099360..9135ff8e 100644
--- a/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryStatistics.cs
+++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryStatistics.cs
@@ -11,8 +11,16 @@ public static partial class WebRoutes
public static class LibraryStatistics
{
public const string INDEX = "{culture}/library/statistics";
- public const string GET_RECENTLY_PLAYED = "{culture}/library/statistics/api-get-recently-played";
- public const string GET_MOST_PLAYED = "{culture}/library/statistics/api-get-most-played";
- public const string GET_MUSIC_PLAY_STATISTICS = "{culture}/library/statistics/api-get-music-play-statistics";
+ public const string GET_STATISTICS = "{culture}/library/statistics/api-get-statistics";
+ public const string GET_ALL_USERS_STATISTICS = "{culture}/library/statistics/api-get-all-users-statistics";
+ public const string GET_RECENTLY_CONSUMED = "{culture}/library/statistics/api-get-recently-consumed";
+ public const string GET_MOST_CONSUMED = "{culture}/library/statistics/api-get-most-consumed";
+ public const string GET_TAG_CONSUMPTION = "{culture}/library/statistics/api-get-tag-consumption";
+ public const string GET_GENRE_CONSUMPTION = "{culture}/library/statistics/api-get-genre-consumption";
+ public const string GET_LIBRARIES = "{culture}/library/statistics/api-get-libraries";
+ public const string GET_USERS = "{culture}/library/statistics/api-get-users";
+ public const string DELETE_CONSUMPTION_ITEM_HISTORY = "{culture}/library/statistics/api-delete-consumption-item-history";
+ public const string CLEAR_CONSUMPTION_HISTORY = "{culture}/library/statistics/api-clear-consumption-history";
+ public const string CLEAR_RESUME_POINTS = "{culture}/library/statistics/api-clear-resume-points";
}
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpoint.cs
new file mode 100644
index 00000000..5470368c
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpoint.cs
@@ -0,0 +1,61 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.Api;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Common.Routes;
+using Lumina.Presentation.Web.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
+
+///
+/// API endpoint for the /{culture}/library/statistics/api-clear-consumption-history route.
+///
+public class ClearConsumptionHistoryEndpoint : BaseEndpoint
+{
+ private readonly IApiHttpClient _apiHttpClient;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for interactions with the API.
+ public ClearConsumptionHistoryEndpoint(IApiHttpClient apiHttpClient)
+ {
+ _apiHttpClient = apiHttpClient;
+ }
+
+ ///
+ /// Configures the endpoint.
+ ///
+ public override void Configure()
+ {
+ base.Configure();
+ Verbs(Http.DELETE);
+ Routes(WebRoutes.LibraryStatistics.CLEAR_CONSUMPTION_HISTORY);
+ DontAutoTag();
+ Options(options => options.WithTags("Statistics"));
+ EnableAntiforgery();
+ }
+
+ ///
+ /// Deletes every consumption record of the selected user.
+ ///
+ /// The request containing the selected user.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(ClearConsumptionHistoryRequest request, CancellationToken cancellationToken)
+ {
+ // The history belongs to the selected user, so no intermediary may store any response of this route, and the response varies by the sign in cookie.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers["Vary"] = "Cookie";
+ string path = string.IsNullOrWhiteSpace(request.UserId)
+ ? ApiRoutes.LibraryStatistics.CLEAR_CONSUMPTION_HISTORY
+ : ApiRoutes.LibraryStatistics.CLEAR_USER_CONSUMPTION_HISTORY.Replace("{userId}", Uri.EscapeDataString(request.UserId), StringComparison.Ordinal);
+ await _apiHttpClient.DeleteAsync(path, cancellationToken).ConfigureAwait(false);
+ return JsonSuccess();
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointSummary.cs
new file mode 100644
index 00000000..06a48a23
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearConsumptionHistory/ClearConsumptionHistoryEndpointSummary.cs
@@ -0,0 +1,32 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.DTO.Common;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.ClearConsumptionHistory;
+
+///
+/// Class used for providing a textual description for the endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class ClearConsumptionHistoryEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public ClearConsumptionHistoryEndpointSummary()
+ {
+ Summary = "Deletes every consumption record of the selected user.";
+ Description = "Proxies the request that deletes every recorded consumption session of the selected user to the API server. When userId is omitted, the history of the current user is deleted; an administrator can name another user. Clearing an already empty history succeeds without changing anything. The resume points are not deleted. A failure is returned as a JSON object with success set to false and a localized errorMessage.";
+
+ RequestParam(request => request.UserId, "The Id of the user whose history is deleted. Optional; when omitted, the current user is used.");
+
+ ResponseParam(response => response.IsSuccess, "Whether the operation succeeded.");
+
+ Response(200, "The consumption history was cleared, or a JSON error with success set to false.",
+ example: new SuccessResponse(true)
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpoint.cs
new file mode 100644
index 00000000..dc523a6a
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpoint.cs
@@ -0,0 +1,63 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.Api;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Common.Routes;
+using Lumina.Presentation.Web.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.ClearResumePoints;
+
+///
+/// API endpoint for the /{culture}/library/statistics/api-clear-resume-points route.
+///
+public class ClearResumePointsEndpoint : BaseEndpoint
+{
+ private readonly IApiHttpClient _apiHttpClient;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for interactions with the API.
+ public ClearResumePointsEndpoint(IApiHttpClient apiHttpClient)
+ {
+ _apiHttpClient = apiHttpClient;
+ }
+
+ ///
+ /// Configures the endpoint.
+ ///
+ public override void Configure()
+ {
+ base.Configure();
+ Verbs(Http.DELETE);
+ Routes(WebRoutes.LibraryStatistics.CLEAR_RESUME_POINTS);
+ DontAutoTag();
+ Options(options => options.WithTags("Statistics"));
+ EnableAntiforgery();
+ }
+
+ ///
+ /// Deletes the resume points of the selected user.
+ ///
+ /// The request containing the selected user and the optional library filter.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(ClearResumePointsRequest request, CancellationToken cancellationToken)
+ {
+ // The resume points belong to the selected user, so no intermediary may store any response of this route, and the response varies by the sign in cookie.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers["Vary"] = "Cookie";
+ string path = string.IsNullOrWhiteSpace(request.UserId)
+ ? ApiRoutes.LibraryStatistics.CLEAR_RESUME_POINTS
+ : ApiRoutes.LibraryStatistics.CLEAR_USER_RESUME_POINTS.Replace("{userId}", Uri.EscapeDataString(request.UserId), StringComparison.Ordinal);
+ if (!string.IsNullOrWhiteSpace(request.LibraryId))
+ path += $"?libraryId={Uri.EscapeDataString(request.LibraryId)}";
+ await _apiHttpClient.DeleteAsync(path, cancellationToken).ConfigureAwait(false);
+ return JsonSuccess();
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointSummary.cs
new file mode 100644
index 00000000..f628f584
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/ClearResumePoints/ClearResumePointsEndpointSummary.cs
@@ -0,0 +1,33 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.DTO.Common;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.ClearResumePoints;
+
+///
+/// Class used for providing a textual description for the endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class ClearResumePointsEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public ClearResumePointsEndpointSummary()
+ {
+ Summary = "Deletes the resume points of the selected user.";
+ Description = "Proxies the request that deletes the resume points of the selected user, optionally limited to one library, to the API server. When userId is omitted, the resume points of the current user are deleted; an administrator can name another user. The consumption history is not deleted. A failure is returned as a JSON object with success set to false and a localized errorMessage.";
+
+ RequestParam(request => request.UserId, "The Id of the user whose resume points are deleted. Optional; when omitted, the current user is used.");
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the deletion to. Optional.");
+
+ ResponseParam(response => response.IsSuccess, "Whether the operation succeeded.");
+
+ Response(200, "The resume points were removed, or a JSON error with success set to false.",
+ example: new SuccessResponse(true)
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpoint.cs
new file mode 100644
index 00000000..9c6833f2
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpoint.cs
@@ -0,0 +1,65 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.Api;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Common.Routes;
+using Lumina.Presentation.Web.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
+
+///
+/// API endpoint for the /{culture}/library/statistics/api-delete-consumption-item-history route.
+///
+public class DeleteConsumptionItemHistoryEndpoint : BaseEndpoint
+{
+ private readonly IApiHttpClient _apiHttpClient;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for interactions with the API.
+ public DeleteConsumptionItemHistoryEndpoint(IApiHttpClient apiHttpClient)
+ {
+ _apiHttpClient = apiHttpClient;
+ }
+
+ ///
+ /// Configures the endpoint.
+ ///
+ public override void Configure()
+ {
+ base.Configure();
+ Verbs(Http.DELETE);
+ Routes(WebRoutes.LibraryStatistics.DELETE_CONSUMPTION_ITEM_HISTORY);
+ DontAutoTag();
+ Options(options => options.WithTags("Statistics"));
+ EnableAntiforgery();
+ }
+
+ ///
+ /// Deletes every consumption record of a media item of the selected user.
+ ///
+ /// The request containing the selected user, the media item, and its library.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(DeleteConsumptionItemHistoryRequest request, CancellationToken cancellationToken)
+ {
+ // The records belong to the selected user, so no intermediary may store any response of this route, and the response varies by the sign in cookie.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers["Vary"] = "Cookie";
+ string path = string.IsNullOrWhiteSpace(request.UserId)
+ ? ApiRoutes.LibraryStatistics.DELETE_CONSUMPTION_ITEM_HISTORY
+ : ApiRoutes.LibraryStatistics.DELETE_USER_CONSUMPTION_ITEM_HISTORY.Replace("{userId}", Uri.EscapeDataString(request.UserId), StringComparison.Ordinal);
+ path = path
+ .Replace("{mediaKind}", request.MediaKind.ToString(), StringComparison.Ordinal)
+ .Replace("{mediaItemId}", request.MediaItemId.ToString(), StringComparison.Ordinal)
+ .Replace("{libraryId}", request.LibraryId.ToString(), StringComparison.Ordinal);
+ await _apiHttpClient.DeleteAsync(path, cancellationToken).ConfigureAwait(false);
+ return JsonSuccess();
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointSummary.cs
new file mode 100644
index 00000000..87c5718d
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/DeleteConsumptionItemHistory/DeleteConsumptionItemHistoryEndpointSummary.cs
@@ -0,0 +1,35 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.DTO.Common;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.DeleteConsumptionItemHistory;
+
+///
+/// Class used for providing a textual description for the endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class DeleteConsumptionItemHistoryEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public DeleteConsumptionItemHistoryEndpointSummary()
+ {
+ Summary = "Deletes every consumption record of a media item of the selected user.";
+ Description = "Proxies the request that deletes every recorded consumption session of one media item of the selected user, in the library named by the request, to the API server. The deletion covers every session of the item, independent of any date range. When userId is omitted, the history of the current user is deleted; an administrator can name another user. Deleting an item that has no recorded session succeeds without changing anything. The resume point of the media item is not deleted. A failure is returned as a JSON object with success set to false and a localized errorMessage.";
+
+ RequestParam(request => request.UserId, "The Id of the user whose history is deleted. Optional; when omitted, the current user is used.");
+ RequestParam(request => request.MediaKind, "The kind of the consumed media item.");
+ RequestParam(request => request.MediaItemId, "The Id of the consumed media item.");
+ RequestParam(request => request.LibraryId, "The Id of the media library that contains the media item.");
+
+ ResponseParam(response => response.IsSuccess, "Whether the operation succeeded.");
+
+ Response(200, "The consumption records of the media item were deleted, or a JSON error with success set to false.",
+ example: new SuccessResponse(true)
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpoint.cs
new file mode 100644
index 00000000..8cadf88d
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpoint.cs
@@ -0,0 +1,86 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.Api;
+using Lumina.Presentation.Web.Common.Authorization;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Common.Routes;
+using Lumina.Presentation.Web.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
+
+///
+/// API endpoint for the /{culture}/library/statistics/api-get-all-users-statistics route.
+///
+public class GetAllUsersConsumptionStatisticsEndpoint : BaseEndpoint
+{
+ private readonly IApiHttpClient _apiHttpClient;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for interactions with the API.
+ public GetAllUsersConsumptionStatisticsEndpoint(IApiHttpClient apiHttpClient)
+ {
+ _apiHttpClient = apiHttpClient;
+ }
+
+ ///
+ /// Configures the endpoint.
+ ///
+ public override void Configure()
+ {
+ base.Configure();
+ Verbs(Http.GET);
+ Routes(WebRoutes.LibraryStatistics.GET_ALL_USERS_STATISTICS);
+ DontAutoTag();
+ Options(options => options.WithTags("Statistics"));
+ Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE);
+ }
+
+ ///
+ /// Retrieves the combined consumption statistics of every user.
+ ///
+ /// The request containing the optional filters.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(GetAllUsersConsumptionStatisticsRequest request, CancellationToken cancellationToken)
+ {
+ // The statistics belong to every user of the server, so no intermediary may store them, and the response varies by the sign in cookie.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers["Vary"] = "Cookie";
+ AllUsersConsumptionStatisticsDto response = await _apiHttpClient.GetAsync(BuildStatisticsEndpoint(request), cancellationToken).ConfigureAwait(false);
+ return JsonSuccess(response);
+ }
+
+ ///
+ /// Builds the API endpoint used to retrieve the combined consumption statistics of every user.
+ ///
+ /// The request containing the optional filters.
+ /// The API endpoint to which the statistics request is sent.
+ private static string BuildStatisticsEndpoint(GetAllUsersConsumptionStatisticsRequest request)
+ {
+ // The query string is rebuilt from the typed request values instead of forwarding the raw one, so that crafted text can never alter the upstream URL.
+ StringBuilder endpoint = new(ApiRoutes.LibraryStatistics.GET_ALL_USERS_CONSUMPTION_STATISTICS);
+ List parameters = [];
+ if (!string.IsNullOrWhiteSpace(request.LibraryId))
+ parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
+ if (request.MediaKind is not null)
+ parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
+ if (request.FromUtc is not null)
+ parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ if (request.ToUtc is not null)
+ parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ if (parameters.Count > 0)
+ endpoint.Append('?').Append(string.Join('&', parameters));
+ return endpoint.ToString();
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs
new file mode 100644
index 00000000..af94c620
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs
@@ -0,0 +1,113 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.DTO.Common;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetAllUsersConsumptionStatistics;
+
+///
+/// Class used for providing a textual description for the endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetAllUsersConsumptionStatisticsEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetAllUsersConsumptionStatisticsEndpointSummary()
+ {
+ Summary = "Gets the consumption statistics of every user.";
+ Description = "Proxies the request that gets the combined consumption statistics of every user, together with the statistics of each user, to the API server. Only an administrator can call it. The date range is inclusive. A failure is returned as a JSON object with success set to false and a localized errorMessage.";
+
+ ExampleRequest = new GetAllUsersConsumptionStatisticsRequest(
+ LibraryId: null,
+ MediaKind: null,
+ FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
+ ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc)
+ );
+
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
+ RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
+ RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
+ RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
+
+ ResponseParam>(response => response.IsSuccess, "Whether the operation succeeded.");
+ ResponseParam(response => response.Total, "The combined consumption statistics of every user.");
+ ResponseParam(response => response.Users, "The consumption statistics of each user, ordered by user Id.");
+ ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of every user, in seconds.");
+ ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions of every user that count towards statistics.");
+ ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions of every user that completed.");
+ ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions of every user that stopped before they completed and count towards statistics.");
+ ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions of every user that completed, between 0 and 1, or 0 when there is no counted session.");
+ ResponseParam(response => response.MediaKindSummaries, "The combined consumption statistics broken down by media kind.");
+ ResponseParam(response => response.UserId, "The Id of the user the summary belongs to.");
+ ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of the user, in seconds.");
+ ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions of the user that count towards statistics.");
+ ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions of the user that completed.");
+ ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions of the user that stopped before they completed and count towards statistics.");
+ ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions of the user that completed, between 0 and 1, or 0 when there is no counted session.");
+ ResponseParam(response => response.MediaKindSummaries, "The consumption statistics of the user broken down by media kind.");
+ ResponseParam(response => response.MediaKind, "The kind of media the breakdown entry belongs to.");
+ ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of the media kind, in seconds.");
+ ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions of the media kind that count towards statistics.");
+ ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions of the media kind that completed.");
+ ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions of the media kind that stopped before they completed and count towards statistics.");
+ ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions of the media kind that completed, between 0 and 1, or 0 when there is no counted session.");
+
+ Response(200, "The consumption statistics of every user are returned, or a JSON error with success set to false.",
+ example: new SuccessResponse(true, new AllUsersConsumptionStatisticsDto(
+ Total: new ConsumptionTotalsDto(
+ TotalConsumedDurationInSeconds: 8744.5,
+ CountedSessionCount: 6,
+ CompletedSessionCount: 4,
+ StoppedSessionCount: 2,
+ CompletionRate: 0.6667,
+ MediaKindSummaries:
+ [
+ new MediaKindConsumptionSummaryDto(
+ MediaKind: MediaKind.MusicTrack,
+ TotalConsumedDurationInSeconds: 1424.5,
+ CountedSessionCount: 4,
+ CompletedSessionCount: 3,
+ StoppedSessionCount: 1,
+ CompletionRate: 0.75
+ ),
+ new MediaKindConsumptionSummaryDto(
+ MediaKind: MediaKind.Book,
+ TotalConsumedDurationInSeconds: 7320,
+ CountedSessionCount: 2,
+ CompletedSessionCount: 1,
+ StoppedSessionCount: 1,
+ CompletionRate: 0.5
+ )
+ ]),
+ Users:
+ [
+ new ConsumptionSummaryDto(
+ UserId: Guid.Parse("1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d"),
+ TotalConsumedDurationInSeconds: 8744.5,
+ CountedSessionCount: 6,
+ CompletedSessionCount: 4,
+ StoppedSessionCount: 2,
+ CompletionRate: 0.6667,
+ MediaKindSummaries:
+ [
+ new MediaKindConsumptionSummaryDto(
+ MediaKind: MediaKind.MusicTrack,
+ TotalConsumedDurationInSeconds: 1424.5,
+ CountedSessionCount: 4,
+ CompletedSessionCount: 3,
+ StoppedSessionCount: 1,
+ CompletionRate: 0.75
+ )
+ ])
+ ]))
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpoint.cs
new file mode 100644
index 00000000..5db57330
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpoint.cs
@@ -0,0 +1,86 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.Api;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Common.Routes;
+using Lumina.Presentation.Web.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
+
+///
+/// API endpoint for the /{culture}/library/statistics/api-get-statistics route.
+///
+public class GetConsumptionStatisticsEndpoint : BaseEndpoint
+{
+ private readonly IApiHttpClient _apiHttpClient;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for interactions with the API.
+ public GetConsumptionStatisticsEndpoint(IApiHttpClient apiHttpClient)
+ {
+ _apiHttpClient = apiHttpClient;
+ }
+
+ ///
+ /// Configures the endpoint.
+ ///
+ public override void Configure()
+ {
+ base.Configure();
+ Verbs(Http.GET);
+ Routes(WebRoutes.LibraryStatistics.GET_STATISTICS);
+ DontAutoTag();
+ Options(options => options.WithTags("Statistics"));
+ }
+
+ ///
+ /// Retrieves the consumption statistics of the selected user.
+ ///
+ /// The request containing the selected user and the optional filters.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(GetConsumptionStatisticsRequest request, CancellationToken cancellationToken)
+ {
+ // The statistics belong to the selected user, so no intermediary may store them, and the response varies by the sign in cookie.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers["Vary"] = "Cookie";
+ ConsumptionSummaryDto response = await _apiHttpClient.GetAsync(BuildStatisticsEndpoint(request), cancellationToken).ConfigureAwait(false);
+ return JsonSuccess(response);
+ }
+
+ ///
+ /// Builds the API endpoint used to retrieve the consumption statistics of the selected user.
+ ///
+ /// The request containing the selected user and the optional filters.
+ /// The API endpoint to which the statistics request is sent.
+ private static string BuildStatisticsEndpoint(GetConsumptionStatisticsRequest request)
+ {
+ // The query string is rebuilt from the typed request values instead of forwarding the raw one, so that crafted text can never alter the upstream URL.
+ StringBuilder endpoint = new(string.IsNullOrWhiteSpace(request.UserId)
+ ? ApiRoutes.LibraryStatistics.GET_CONSUMPTION_STATISTICS
+ : ApiRoutes.LibraryStatistics.GET_USER_CONSUMPTION_STATISTICS.Replace("{userId}", Uri.EscapeDataString(request.UserId), StringComparison.Ordinal));
+ List parameters = [];
+ if (!string.IsNullOrWhiteSpace(request.LibraryId))
+ parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
+ if (request.MediaKind is not null)
+ parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
+ if (request.FromUtc is not null)
+ parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ if (request.ToUtc is not null)
+ parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ if (parameters.Count > 0)
+ endpoint.Append('?').Append(string.Join('&', parameters));
+ return endpoint.ToString();
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs
new file mode 100644
index 00000000..9d8cb2c8
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs
@@ -0,0 +1,86 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.DTO.Common;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetConsumptionStatistics;
+
+///
+/// Class used for providing a textual description for the endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetConsumptionStatisticsEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetConsumptionStatisticsEndpointSummary()
+ {
+ Summary = "Gets the consumption statistics of the selected user.";
+ Description = "Proxies the request that gets the total consumed duration, the counted sessions, the completed sessions, the stopped sessions, the completion rate, and the per media kind breakdown of the selected user to the API server. When userId is omitted, the statistics of the current user are returned; an administrator can name another user. The date range is inclusive. A failure is returned as a JSON object with success set to false and a localized errorMessage.";
+
+ ExampleRequest = new GetConsumptionStatisticsRequest(
+ UserId: null,
+ LibraryId: null,
+ MediaKind: null,
+ FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
+ ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc)
+ );
+
+ RequestParam(request => request.UserId, "The Id of the user whose statistics are retrieved. Optional; when omitted, the current user is used.");
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
+ RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
+ RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
+ RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
+
+ ResponseParam>(response => response.IsSuccess, "Whether the operation succeeded.");
+ ResponseParam(response => response.UserId, "The Id of the user the statistics belong to.");
+ ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session, in seconds.");
+ ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions that count towards statistics.");
+ ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions that completed.");
+ ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions that stopped before they completed and count towards statistics.");
+ ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions that completed, between 0 and 1, or 0 when there is no counted session.");
+ ResponseParam(response => response.MediaKindSummaries, "The consumption statistics broken down by media kind.");
+ ResponseParam(response => response.MediaKind, "The kind of media the breakdown entry belongs to.");
+ ResponseParam(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of the media kind, in seconds.");
+ ResponseParam(response => response.CountedSessionCount, "The number of recorded sessions of the media kind that count towards statistics.");
+ ResponseParam(response => response.CompletedSessionCount, "The number of recorded sessions of the media kind that completed.");
+ ResponseParam(response => response.StoppedSessionCount, "The number of recorded sessions of the media kind that stopped before they completed and count towards statistics.");
+ ResponseParam(response => response.CompletionRate, "The fraction of the counted sessions of the media kind that completed, between 0 and 1, or 0 when there is no counted session.");
+
+ Response(200, "The consumption statistics of the selected user are returned, or a JSON error with success set to false.",
+ example: new SuccessResponse(true, new ConsumptionSummaryDto(
+ UserId: Guid.Parse("1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d"),
+ TotalConsumedDurationInSeconds: 8744.5,
+ CountedSessionCount: 6,
+ CompletedSessionCount: 4,
+ StoppedSessionCount: 2,
+ CompletionRate: 0.6667,
+ MediaKindSummaries:
+ [
+ new MediaKindConsumptionSummaryDto(
+ MediaKind: MediaKind.MusicTrack,
+ TotalConsumedDurationInSeconds: 1424.5,
+ CountedSessionCount: 4,
+ CompletedSessionCount: 3,
+ StoppedSessionCount: 1,
+ CompletionRate: 0.75
+ ),
+ new MediaKindConsumptionSummaryDto(
+ MediaKind: MediaKind.Book,
+ TotalConsumedDurationInSeconds: 7320,
+ CountedSessionCount: 2,
+ CompletedSessionCount: 1,
+ StoppedSessionCount: 1,
+ CompletionRate: 0.5
+ )
+ ]))
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpoint.cs
new file mode 100644
index 00000000..b37f84d6
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpoint.cs
@@ -0,0 +1,86 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.Api;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Common.Routes;
+using Lumina.Presentation.Web.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetGenreConsumption;
+
+///
+/// API endpoint for the /{culture}/library/statistics/api-get-genre-consumption route.
+///
+public class GetGenreConsumptionEndpoint : BaseEndpoint
+{
+ private readonly IApiHttpClient _apiHttpClient;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for interactions with the API.
+ public GetGenreConsumptionEndpoint(IApiHttpClient apiHttpClient)
+ {
+ _apiHttpClient = apiHttpClient;
+ }
+
+ ///
+ /// Configures the endpoint.
+ ///
+ public override void Configure()
+ {
+ base.Configure();
+ Verbs(Http.GET);
+ Routes(WebRoutes.LibraryStatistics.GET_GENRE_CONSUMPTION);
+ DontAutoTag();
+ Options(options => options.WithTags("Statistics"));
+ }
+
+ ///
+ /// Retrieves the genre consumption of the selected user.
+ ///
+ /// The request containing the selected user and the optional filters.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(GetGenreConsumptionRequest request, CancellationToken cancellationToken)
+ {
+ // The statistics belong to the selected user, so no intermediary may store them, and the response varies by the sign in cookie.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers["Vary"] = "Cookie";
+ GenreConsumptionDto[] response = await _apiHttpClient.GetAsync(BuildGenreConsumptionEndpoint(request), cancellationToken).ConfigureAwait(false);
+ return JsonSuccess(response);
+ }
+
+ ///
+ /// Builds the API endpoint used to retrieve the genre consumption of the selected user.
+ ///
+ /// The request containing the selected user and the optional filters.
+ /// The API endpoint to which the genre request is sent.
+ private static string BuildGenreConsumptionEndpoint(GetGenreConsumptionRequest request)
+ {
+ // The query string is rebuilt from the typed request values instead of forwarding the raw one, so that crafted text can never alter the upstream URL.
+ StringBuilder endpoint = new(string.IsNullOrWhiteSpace(request.UserId)
+ ? ApiRoutes.LibraryStatistics.GET_GENRE_CONSUMPTION
+ : ApiRoutes.LibraryStatistics.GET_USER_GENRE_CONSUMPTION.Replace("{userId}", Uri.EscapeDataString(request.UserId), StringComparison.Ordinal));
+ List parameters = [];
+ if (!string.IsNullOrWhiteSpace(request.LibraryId))
+ parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
+ if (request.MediaKind is not null)
+ parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
+ if (request.FromUtc is not null)
+ parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ if (request.ToUtc is not null)
+ parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ if (parameters.Count > 0)
+ endpoint.Append('?').Append(string.Join('&', parameters));
+ return endpoint.ToString();
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs
new file mode 100644
index 00000000..f8a4d153
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetGenreConsumption/GetGenreConsumptionEndpointSummary.cs
@@ -0,0 +1,64 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.DTO.Common;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetGenreConsumption;
+
+///
+/// Class used for providing a textual description for the endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetGenreConsumptionEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetGenreConsumptionEndpointSummary()
+ {
+ Summary = "Gets the genre consumption of the selected user.";
+ Description = "Proxies the request that gets the genres carried by the media items the selected user consumed to the API server. When userId is omitted, the statistics of the current user are returned; an administrator can name another user. The names are lowercase and grouped across media kinds, so a genre shared by a book and a track appears in one bucket. The date range is inclusive. A failure is returned as a JSON object with success set to false and a localized errorMessage.";
+
+ ExampleRequest = new GetGenreConsumptionRequest(
+ UserId: null,
+ LibraryId: null,
+ MediaKind: null,
+ FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
+ ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc)
+ );
+
+ RequestParam(request => request.UserId, "The Id of the user whose statistics are retrieved. Optional; when omitted, the current user is used.");
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the statistics to. Optional.");
+ RequestParam(request => request.MediaKind, "The kind of media to restrict the statistics to. Optional.");
+ RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
+ RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
+
+ ResponseParam>(response => response.IsSuccess, "Whether the operation succeeded.");
+ ResponseParam(response => response.Name, "The lowercase name of the genre.");
+ ResponseParam(response => response.ConsumedItemCount, "The number of distinct media items that carry the genre and were consumed.");
+ ResponseParam(response => response.ConsumedDurationInSeconds, "The active duration consumed in the media items that carry the genre, in seconds.");
+
+ Response(200, "The genre consumption of the selected user is returned, or a JSON error with success set to false.",
+ example: new SuccessResponse(true,
+ [
+ new GenreConsumptionDto(
+ Name: "horror",
+ ConsumedItemCount: 3,
+ ConsumedDurationInSeconds: 5400),
+ new GenreConsumptionDto(
+ Name: "fantasy",
+ ConsumedItemCount: 2,
+ ConsumedDurationInSeconds: 7320),
+ new GenreConsumptionDto(
+ Name: "science fiction",
+ ConsumedItemCount: 1,
+ ConsumedDurationInSeconds: 1424.5)
+ ])
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMusicPlayStatistics/GetMusicPlayStatisticsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetLibraries/GetLibrariesEndpoint.cs
similarity index 63%
rename from src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMusicPlayStatistics/GetMusicPlayStatisticsEndpoint.cs
rename to src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetLibraries/GetLibrariesEndpoint.cs
index 8dcec382..a07a14da 100644
--- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMusicPlayStatistics/GetMusicPlayStatisticsEndpoint.cs
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetLibraries/GetLibrariesEndpoint.cs
@@ -1,28 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
-using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
-namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetMusicPlayStatistics;
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetLibraries;
///
-/// API endpoint for the /{culture}/library/statistics/api-get-music-play-statistics route.
+/// API endpoint for the /{culture}/library/statistics/api-get-libraries route.
///
-public class GetMusicPlayStatisticsEndpoint : BaseEndpoint
+public class GetLibrariesEndpoint : BaseEndpoint
{
private readonly IApiHttpClient _apiHttpClient;
///
- /// Initializes a new instance of the class.
+ /// Initializes a new instance of the class.
///
/// Injected service for interactions with the API.
- public GetMusicPlayStatisticsEndpoint(IApiHttpClient apiHttpClient)
+ public GetLibrariesEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
@@ -34,22 +35,22 @@ public class GetMusicPlayStatisticsEndpoint : BaseEndpoint options.WithTags("Statistics"));
}
///
- /// Retrieves the listening statistics of the current user.
+ /// Retrieves the libraries available for the library filter.
///
/// The request object.
/// Cancellation token that can be used to stop the execution.
public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
{
- // The statistics belong to the authenticated user, so no intermediary may store them, and the response varies by the sign in cookie.
+ // The library list belongs to the current user, so no intermediary may store it, and the response varies by the sign in cookie.
HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
HttpContext.Response.Headers["Vary"] = "Cookie";
- MusicPlayStatisticsDto statistics = await _apiHttpClient.GetAsync(ApiRoutes.PlayStatistics.GET_MUSIC_PLAY_STATISTICS, cancellationToken).ConfigureAwait(false);
- return JsonSuccess(statistics);
+ LibraryDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Libraries.GET_ENABLED_LIBRARIES, cancellationToken).ConfigureAwait(false);
+ return JsonSuccess(response);
}
}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetLibraries/GetLibrariesEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetLibraries/GetLibrariesEndpointSummary.cs
new file mode 100644
index 00000000..de8d1393
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetLibraries/GetLibrariesEndpointSummary.cs
@@ -0,0 +1,27 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.DTO.Common;
+using Lumina.Presentation.Web.Common.DTO.Libraries;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetLibraries;
+
+///
+/// Class used for providing a textual description for the endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetLibrariesEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetLibrariesEndpointSummary()
+ {
+ Summary = "Gets the enabled libraries available for the library filter.";
+ Description = "Proxies the request that gets the enabled media libraries available to the current user to the API server. A regular user receives only their own libraries; an administrator receives every enabled library. A failure is returned as a JSON object with success set to false and a localized errorMessage.";
+
+ Response(200, "The enabled media libraries are returned, or a JSON error with success set to false.",
+ example: new SuccessResponse(true, default));
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpoint.cs
new file mode 100644
index 00000000..8a62b830
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpoint.cs
@@ -0,0 +1,92 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.Api;
+using Lumina.Presentation.Web.Common.DTO.Common;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using Lumina.Presentation.Web.Common.Routes;
+using Lumina.Presentation.Web.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Http;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetMostConsumed;
+
+///
+/// API endpoint for the /{culture}/library/statistics/api-get-most-consumed route.
+///
+public class GetMostConsumedEndpoint : BaseEndpoint
+{
+ private const int DEFAULT_PAGE_SIZE = 10;
+
+ private readonly IApiHttpClient _apiHttpClient;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for interactions with the API.
+ public GetMostConsumedEndpoint(IApiHttpClient apiHttpClient)
+ {
+ _apiHttpClient = apiHttpClient;
+ }
+
+ ///
+ /// Configures the endpoint.
+ ///
+ public override void Configure()
+ {
+ base.Configure();
+ Verbs(Http.GET);
+ Routes(WebRoutes.LibraryStatistics.GET_MOST_CONSUMED);
+ DontAutoTag();
+ Options(options => options.WithTags("Statistics"));
+ }
+
+ ///
+ /// Retrieves a page of the most consumed media items of the selected user.
+ ///
+ /// The request containing the selected user, the optional filters, and the page bounds.
+ /// Cancellation token that can be used to stop the execution.
+ public override async Task ExecuteAsync(GetMostConsumedRequest request, CancellationToken cancellationToken)
+ {
+ // The history belongs to the selected user, so no intermediary may store it, and the response varies by the sign in cookie.
+ HttpContext.Response.Headers["Cache-Control"] = "private, no-store";
+ HttpContext.Response.Headers["Vary"] = "Cookie";
+ PaginatedDto response = await _apiHttpClient.GetAsync>(BuildHistoryEndpoint(request), cancellationToken).ConfigureAwait(false);
+ return JsonSuccess(response);
+ }
+
+ ///
+ /// Builds the API endpoint used to retrieve the most consumed media items of the selected user.
+ ///
+ /// The request containing the selected user, the optional filters, and the page bounds.
+ /// The API endpoint to which the history request is sent.
+ private static string BuildHistoryEndpoint(GetMostConsumedRequest request)
+ {
+ // The query string is rebuilt from the typed request values instead of forwarding the raw one, so that crafted text can never alter the upstream URL.
+ StringBuilder endpoint = new(string.IsNullOrWhiteSpace(request.UserId)
+ ? ApiRoutes.LibraryStatistics.GET_MOST_CONSUMED
+ : ApiRoutes.LibraryStatistics.GET_USER_MOST_CONSUMED.Replace("{userId}", Uri.EscapeDataString(request.UserId), StringComparison.Ordinal));
+ int currentPage = request.CurrentPage ?? 1;
+ int perPage = request.PerPage ?? DEFAULT_PAGE_SIZE;
+ List parameters = [];
+ if (!string.IsNullOrWhiteSpace(request.LibraryId))
+ parameters.Add($"libraryId={Uri.EscapeDataString(request.LibraryId)}");
+ if (request.MediaKind is not null)
+ parameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
+ if (request.FromUtc is not null)
+ parameters.Add($"fromUtc={Uri.EscapeDataString(request.FromUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ if (request.ToUtc is not null)
+ parameters.Add($"toUtc={Uri.EscapeDataString(request.ToUtc.Value.ToString("O", CultureInfo.InvariantCulture))}");
+ parameters.Add($"currentPage={currentPage.ToString(CultureInfo.InvariantCulture)}");
+ parameters.Add($"perPage={perPage.ToString(CultureInfo.InvariantCulture)}");
+ endpoint.Append('?').Append(string.Join('&', parameters));
+ return endpoint.ToString();
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs
new file mode 100644
index 00000000..fbf4896f
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostConsumed/GetMostConsumedEndpointSummary.cs
@@ -0,0 +1,102 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.DTO.Common;
+using Lumina.Presentation.Web.Common.DTO.MediaConsumption;
+using Lumina.Presentation.Web.Common.Enums.MediaConsumption;
+using Lumina.Presentation.Web.Common.Requests.Library.Statistics;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetMostConsumed;
+
+///
+/// Class used for providing a textual description for the endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class GetMostConsumedEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public GetMostConsumedEndpointSummary()
+ {
+ Summary = "Gets the most consumed media items of the selected user.";
+ Description = "Proxies the request that gets a page of the most consumed media items of the selected user to the API server. When userId is omitted, the history of the current user is returned; an administrator can name another user. The items are ordered by counted sessions, consumed duration, last consumption date, and media item Id. Music and book sessions appear in the same list. The date range is inclusive. An item whose media item was deleted, or whose library is no longer accessible, is returned with isAvailable set to false and empty display fields. A failure is returned as a JSON object with success set to false and a localized errorMessage.";
+
+ ExampleRequest = new GetMostConsumedRequest(
+ UserId: null,
+ LibraryId: null,
+ MediaKind: null,
+ FromUtc: new DateTime(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc),
+ ToUtc: new DateTime(2026, 10, 31, 23, 59, 59, DateTimeKind.Utc),
+ CurrentPage: 1,
+ PerPage: 10
+ );
+
+ RequestParam(request => request.UserId, "The Id of the user whose history is retrieved. Optional; when omitted, the current user is used.");
+ RequestParam(request => request.LibraryId, "The Id of the media library to restrict the history to. Optional.");
+ RequestParam(request => request.MediaKind, "The kind of media to restrict the history to. Optional.");
+ RequestParam(request => request.FromUtc, "The inclusive start of the date range. Optional.");
+ RequestParam(request => request.ToUtc, "The inclusive end of the date range. Optional.");
+ RequestParam(request => request.CurrentPage, "The one based page of media items to return. Optional. Defaults to 1.");
+ RequestParam(request => request.PerPage, "The number of media items per page. Optional. Defaults to 10.");
+
+ ResponseParam>>(response => response.IsSuccess, "Whether the operation succeeded.");
+ ResponseParam>(response => response.Data, "The most consumed media items of the requested page, ordered by counted sessions, consumed duration, last consumption date, and media item Id.");
+ ResponseParam>(response => response.CurrentPage, "The current page number.");
+ ResponseParam>(response => response.PerPage, "The number of media items retrieved per page.");
+ ResponseParam>(response => response.Count, "The total number of distinct media items that match the filters.");
+ ResponseParam>(response => response.NumberOfPages, "The total number of pages.");
+ ResponseParam(response => response.MediaKind, "The kind of the consumed media item.");
+ ResponseParam(response => response.MediaItemId, "The Id of the consumed media item.");
+ ResponseParam(response => response.LibraryId, "The Id of the media library that contains the media item.");
+ ResponseParam(response => response.IsAvailable, "Whether the media item still exists and its library is accessible.");
+ ResponseParam