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(response => response.Title, "The title of the media item, or an empty string when the item is not available."); + ResponseParam(response => response.CollectionTitle, "The title of the collection that contains the media item, or an empty string when there is none."); + ResponseParam(response => response.CreatorName, "The name of the creator of the media item, or an empty string when there is none."); + ResponseParam(response => response.CoverPath, "The path of the cover art of the media item, if available."); + ResponseParam(response => response.LastConsumedOnUtc, "The date and time when the media item was last consumed."); + ResponseParam(response => response.CountedSessionCount, "The number of consumption sessions of the media item that count towards statistics."); + ResponseParam(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(200, "The requested page of most consumed media items is returned, or a JSON error with success set to false.", + example: new SuccessResponse>(true, new PaginatedDto( + Data: + [ + new ConsumedItemDto( + MediaKind: MediaKind.MusicTrack, + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + IsAvailable: true, + Title: "The Show Must Go On", + CollectionTitle: "Innuendo", + CreatorName: "Queen", + CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc), + CountedSessionCount: 4, + CompletedSessionCount: 3, + ConsumedDurationInSeconds: 1424.5), + new ConsumedItemDto( + MediaKind: MediaKind.Book, + MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"), + LibraryId: Guid.Parse("6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f"), + IsAvailable: true, + Title: "The Fellowship of the Ring", + CollectionTitle: string.Empty, + CreatorName: "J. R. R. Tolkien", + CoverPath: "/artwork/books/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 23, 20, 40, 0, DateTimeKind.Utc), + CountedSessionCount: 2, + CompletedSessionCount: 1, + ConsumedDurationInSeconds: 7320) + ], + CurrentPage: 1, + PerPage: 10, + Count: 2, + NumberOfPages: 1)) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostPlayed/GetMostPlayedEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostPlayed/GetMostPlayedEndpoint.cs deleted file mode 100644 index d4e01ba9..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostPlayed/GetMostPlayedEndpoint.cs +++ /dev/null @@ -1,64 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.DTO.Common; -using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary.PlayHistory; -using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.PlayHistory; -using Lumina.Presentation.Web.Common.Routes; -using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Http; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetMostPlayed; - -/// -/// API endpoint for the /{culture}/library/statistics/api-get-most-played route. -/// -public class GetMostPlayedEndpoint : 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 GetMostPlayedEndpoint(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Configures the endpoint. - /// - public override void Configure() - { - base.Configure(); - Verbs(Http.GET); - Routes(WebRoutes.LibraryStatistics.GET_MOST_PLAYED); - DontAutoTag(); - Options(options => options.WithTags("Statistics")); - } - - /// - /// Retrieves a page of the most played tracks of the current user. - /// - /// The request object. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(GetMostPlayedRequest 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. - HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; - HttpContext.Response.Headers["Vary"] = "Cookie"; - // 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. - int currentPage = request.CurrentPage ?? 1; - int perPage = request.PerPage ?? DEFAULT_PAGE_SIZE; - string url = ApiRoutes.PlayStatistics.GET_MOST_PLAYED + $"?currentPage={currentPage.ToString(CultureInfo.InvariantCulture)}&perPage={perPage.ToString(CultureInfo.InvariantCulture)}"; - PaginatedDto mostPlayed = await _apiHttpClient.GetAsync>(url, cancellationToken).ConfigureAwait(false); - return JsonSuccess(mostPlayed); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostPlayed/GetMostPlayedEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostPlayed/GetMostPlayedEndpointSummary.cs deleted file mode 100644 index 84184375..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostPlayed/GetMostPlayedEndpointSummary.cs +++ /dev/null @@ -1,73 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.DTO.Common; -using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary.PlayHistory; -using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.PlayHistory; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetMostPlayed; - -/// -/// Class used for providing a textual description for the endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class GetMostPlayedEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public GetMostPlayedEndpointSummary() - { - Summary = "Gets the most played tracks of the current user."; - Description = "Proxies the request that gets a page of the most played tracks of the current user to the API server. Each track is returned once, from the most played, with its counted plays, its completed plays and the duration the user listened to it."; - - ExampleRequest = new GetMostPlayedRequest(CurrentPage: 1, PerPage: 10); - RequestParam(request => request.CurrentPage, "The one based page of tracks to return. Optional. Defaults to 1."); - RequestParam(request => request.PerPage, "The number of tracks per page. Optional. Defaults to 10."); - - ResponseParam>>(response => response.IsSuccess, "Whether the operation succeeded."); - ResponseParam>(response => response.Data, "The most played tracks of the requested page, ordered by counted plays, listened duration, last activity, and track Id."); - ResponseParam>(response => response.CurrentPage, "The current page number."); - ResponseParam>(response => response.PerPage, "The number of tracks retrieved per page."); - ResponseParam>(response => response.Count, "The total number of tracks that match the filters."); - ResponseParam>(response => response.NumberOfPages, "The total number of pages."); - ResponseParam(response => response.TrackId, "The Id of the track."); - ResponseParam(response => response.LibraryId, "The Id of the media library that contains the track."); - ResponseParam(response => response.AlbumId, "The Id of the album that contains the track."); - ResponseParam(response => response.ArtistId, "The Id of the artist that produced the track."); - ResponseParam(response => response.Title, "The title of the track, if it still exists and the user can access its library."); - ResponseParam(response => response.AlbumTitle, "The title of the album that contains the track, if available."); - ResponseParam(response => response.ArtistName, "The name of the artist that produced the track, if available."); - ResponseParam(response => response.CoverPath, "The path of the cover art of the album, if available."); - ResponseParam(response => response.LastPlayedOnUtc, "The date and time of the last recorded activity of the track's most recent play."); - ResponseParam(response => response.PlayCount, "The number of plays of the track that count as plays."); - ResponseParam(response => response.CompletedPlayCount, "The number of plays of the track that completed."); - ResponseParam(response => response.ListenedDurationInSeconds, "The duration the user listened to the track, over all of its counted plays, in seconds."); - - Response(200, "The requested page of most played tracks is returned.", - example: new SuccessResponse>(true, new PaginatedDto( - Data: - [ - new PlayedTrackDto( - TrackId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), - LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), - AlbumId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"), - ArtistId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"), - Title: "Time", - AlbumTitle: "The Dark Side of the Moon", - ArtistName: "Pink Floyd", - CoverPath: "covers/dark-side-of-the-moon.jpg", - LastPlayedOnUtc: new DateTime(2026, 10, 20, 18, 30, 0, DateTimeKind.Utc), - PlayCount: 12, - CompletedPlayCount: 9, - ListenedDurationInSeconds: 4230.5) - ], - CurrentPage: 1, - PerPage: 10, - Count: 1, - NumberOfPages: 1)) - ); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMusicPlayStatistics/GetMusicPlayStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMusicPlayStatistics/GetMusicPlayStatisticsEndpointSummary.cs deleted file mode 100644 index 17b9f695..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMusicPlayStatistics/GetMusicPlayStatisticsEndpointSummary.cs +++ /dev/null @@ -1,40 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.DTO.Common; -using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary.PlayHistory; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetMusicPlayStatistics; - -/// -/// Class used for providing a textual description for the endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class GetMusicPlayStatisticsEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public GetMusicPlayStatisticsEndpointSummary() - { - Summary = "Gets the listening statistics of the current user."; - Description = "Proxies the request that gets the total listening time, the counted plays, the completed plays, the stopped plays that count, and the completion rate of the current user to the API server. A play that is still in progress counts once it reaches the threshold, so the counted total can exceed the completed and stopped plays together."; - - ResponseParam>(response => response.IsSuccess, "Whether the operation succeeded."); - ResponseParam(response => response.TotalListeningDurationInSeconds, "The total duration the user listened to, over every recorded play, in seconds."); - ResponseParam(response => response.TotalPlayCount, "The number of recorded plays that count as plays. It includes an in-progress play that has already reached the threshold, so it need not equal the completed and stopped plays together."); - ResponseParam(response => response.CompletedPlayCount, "The number of recorded plays that completed."); - ResponseParam(response => response.StoppedPlayCount, "The number of recorded plays that stopped before the track completed and count as plays."); - ResponseParam(response => response.CompletionRate, "The fraction of the counted plays that completed, between 0 and 1, or 0 when there is no counted play."); - - Response(200, "The listening statistics of the current user are returned.", - example: new SuccessResponse(true, new MusicPlayStatisticsDto( - TotalListeningDurationInSeconds: 93840.5, - TotalPlayCount: 512, - CompletedPlayCount: 388, - StoppedPlayCount: 124, - CompletionRate: 0.7578125)) - ); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpoint.cs new file mode 100644 index 00000000..d5ed57ce --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpoint.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.GetRecentlyConsumed; + +/// +/// API endpoint for the /{culture}/library/statistics/api-get-recently-consumed route. +/// +public class GetRecentlyConsumedEndpoint : 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 GetRecentlyConsumedEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryStatistics.GET_RECENTLY_CONSUMED); + DontAutoTag(); + Options(options => options.WithTags("Statistics")); + } + + /// + /// Retrieves a page of the recently 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(GetRecentlyConsumedRequest 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 recently 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(GetRecentlyConsumedRequest 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_RECENTLY_CONSUMED + : ApiRoutes.LibraryStatistics.GET_USER_RECENTLY_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/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.cs new file mode 100644 index 00000000..58a1ea01 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyConsumed/GetRecentlyConsumedEndpointSummary.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.GetRecentlyConsumed; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetRecentlyConsumedEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetRecentlyConsumedEndpointSummary() + { + Summary = "Gets the recently consumed media items of the selected user."; + Description = "Proxies the request that gets a page of the recently 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. 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 GetRecentlyConsumedRequest( + 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 recently consumed media items of the requested page, from the most recently consumed."); + 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(response => response.Title, "The title of the media item, or an empty string when the item is not available."); + ResponseParam(response => response.CollectionTitle, "The title of the collection that contains the media item, or an empty string when there is none."); + ResponseParam(response => response.CreatorName, "The name of the creator of the media item, or an empty string when there is none."); + ResponseParam(response => response.CoverPath, "The path of the cover art of the media item, if available."); + ResponseParam(response => response.LastConsumedOnUtc, "The date and time when the media item was last consumed."); + ResponseParam(response => response.CountedSessionCount, "The number of consumption sessions of the media item that count towards statistics."); + ResponseParam(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(200, "The requested page of recently consumed media items is returned, or a JSON error with success set to false.", + example: new SuccessResponse>(true, new PaginatedDto( + Data: + [ + new ConsumedItemDto( + MediaKind: MediaKind.MusicTrack, + MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), + LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), + IsAvailable: true, + Title: "The Show Must Go On", + CollectionTitle: "Innuendo", + CreatorName: "Queen", + CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 24, 12, 12, 0, DateTimeKind.Utc), + CountedSessionCount: 4, + CompletedSessionCount: 3, + ConsumedDurationInSeconds: 1424.5), + new ConsumedItemDto( + MediaKind: MediaKind.Book, + MediaItemId: Guid.Parse("7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d"), + LibraryId: Guid.Parse("6c7d8e9f-0a1b-4c2d-9e3f-4a5b6c7d8e9f"), + IsAvailable: true, + Title: "The Fellowship of the Ring", + CollectionTitle: string.Empty, + CreatorName: "J. R. R. Tolkien", + CoverPath: "/artwork/books/7a6b5c4d-3e2f-4a1b-8c9d-0e1f2a3b4c5d/cover.jpg", + LastConsumedOnUtc: new DateTime(2026, 10, 23, 20, 40, 0, DateTimeKind.Utc), + CountedSessionCount: 2, + CompletedSessionCount: 1, + ConsumedDurationInSeconds: 7320) + ], + CurrentPage: 1, + PerPage: 10, + Count: 2, + NumberOfPages: 1)) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyPlayed/GetRecentlyPlayedEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyPlayed/GetRecentlyPlayedEndpoint.cs deleted file mode 100644 index 955b3873..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyPlayed/GetRecentlyPlayedEndpoint.cs +++ /dev/null @@ -1,64 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.Api; -using Lumina.Presentation.Web.Common.DTO.Common; -using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary.PlayHistory; -using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.PlayHistory; -using Lumina.Presentation.Web.Common.Routes; -using Lumina.Presentation.Web.Core.Endpoints.Common; -using Microsoft.AspNetCore.Http; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetRecentlyPlayed; - -/// -/// API endpoint for the /{culture}/library/statistics/api-get-recently-played route. -/// -public class GetRecentlyPlayedEndpoint : 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 GetRecentlyPlayedEndpoint(IApiHttpClient apiHttpClient) - { - _apiHttpClient = apiHttpClient; - } - - /// - /// Configures the endpoint. - /// - public override void Configure() - { - base.Configure(); - Verbs(Http.GET); - Routes(WebRoutes.LibraryStatistics.GET_RECENTLY_PLAYED); - DontAutoTag(); - Options(options => options.WithTags("Statistics")); - } - - /// - /// Retrieves a page of the recently played tracks of the current user. - /// - /// The request object. - /// Cancellation token that can be used to stop the execution. - public override async Task ExecuteAsync(GetRecentlyPlayedRequest 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. - HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; - HttpContext.Response.Headers["Vary"] = "Cookie"; - // 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. - int currentPage = request.CurrentPage ?? 1; - int perPage = request.PerPage ?? DEFAULT_PAGE_SIZE; - string url = ApiRoutes.PlayStatistics.GET_RECENTLY_PLAYED + $"?currentPage={currentPage.ToString(CultureInfo.InvariantCulture)}&perPage={perPage.ToString(CultureInfo.InvariantCulture)}"; - PaginatedDto recentlyPlayed = await _apiHttpClient.GetAsync>(url, cancellationToken).ConfigureAwait(false); - return JsonSuccess(recentlyPlayed); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyPlayed/GetRecentlyPlayedEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyPlayed/GetRecentlyPlayedEndpointSummary.cs deleted file mode 100644 index 31996a35..00000000 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyPlayed/GetRecentlyPlayedEndpointSummary.cs +++ /dev/null @@ -1,73 +0,0 @@ -#region ========================================================================= USING ===================================================================================== -using FastEndpoints; -using Lumina.Presentation.Web.Common.DTO.Common; -using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary.PlayHistory; -using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.PlayHistory; -using System; -using System.Diagnostics.CodeAnalysis; -#endregion - -namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetRecentlyPlayed; - -/// -/// Class used for providing a textual description for the endpoint, for OpenAPI. -/// -[ExcludeFromCodeCoverage] -public class GetRecentlyPlayedEndpointSummary : Summary -{ - /// - /// Initializes a new instance of the class. - /// - public GetRecentlyPlayedEndpointSummary() - { - Summary = "Gets the recently played tracks of the current user."; - Description = "Proxies the request that gets a page of the recently played tracks of the current user to the API server. Each track is returned once, from the most recently played, with its counted plays, its completed plays and the duration the user listened to it."; - - ExampleRequest = new GetRecentlyPlayedRequest(CurrentPage: 1, PerPage: 10); - RequestParam(request => request.CurrentPage, "The one based page of tracks to return. Optional. Defaults to 1."); - RequestParam(request => request.PerPage, "The number of tracks per page. Optional. Defaults to 10."); - - ResponseParam>>(response => response.IsSuccess, "Whether the operation succeeded."); - ResponseParam>(response => response.Data, "The recently played tracks of the requested page, from the most recently played."); - ResponseParam>(response => response.CurrentPage, "The current page number."); - ResponseParam>(response => response.PerPage, "The number of tracks retrieved per page."); - ResponseParam>(response => response.Count, "The total number of tracks that match the filters."); - ResponseParam>(response => response.NumberOfPages, "The total number of pages."); - ResponseParam(response => response.TrackId, "The Id of the track."); - ResponseParam(response => response.LibraryId, "The Id of the media library that contains the track."); - ResponseParam(response => response.AlbumId, "The Id of the album that contains the track."); - ResponseParam(response => response.ArtistId, "The Id of the artist that produced the track."); - ResponseParam(response => response.Title, "The title of the track, if it still exists and the user can access its library."); - ResponseParam(response => response.AlbumTitle, "The title of the album that contains the track, if available."); - ResponseParam(response => response.ArtistName, "The name of the artist that produced the track, if available."); - ResponseParam(response => response.CoverPath, "The path of the cover art of the album, if available."); - ResponseParam(response => response.LastPlayedOnUtc, "The date and time of the last recorded activity of the track's most recent play."); - ResponseParam(response => response.PlayCount, "The number of plays of the track that count as plays."); - ResponseParam(response => response.CompletedPlayCount, "The number of plays of the track that completed."); - ResponseParam(response => response.ListenedDurationInSeconds, "The duration the user listened to the track, over all of its counted plays, in seconds."); - - Response(200, "The requested page of recently played tracks is returned.", - example: new SuccessResponse>(true, new PaginatedDto( - Data: - [ - new PlayedTrackDto( - TrackId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"), - LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"), - AlbumId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"), - ArtistId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"), - Title: "Time", - AlbumTitle: "The Dark Side of the Moon", - ArtistName: "Pink Floyd", - CoverPath: "covers/dark-side-of-the-moon.jpg", - LastPlayedOnUtc: new DateTime(2026, 10, 20, 18, 30, 0, DateTimeKind.Utc), - PlayCount: 12, - CompletedPlayCount: 9, - ListenedDurationInSeconds: 4230.5) - ], - CurrentPage: 1, - PerPage: 10, - Count: 1, - NumberOfPages: 1)) - ); - } -} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpoint.cs new file mode 100644 index 00000000..d14e93f3 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpoint.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.GetTagConsumption; + +/// +/// API endpoint for the /{culture}/library/statistics/api-get-tag-consumption route. +/// +public class GetTagConsumptionEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetTagConsumptionEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryStatistics.GET_TAG_CONSUMPTION); + DontAutoTag(); + Options(options => options.WithTags("Statistics")); + } + + /// + /// Retrieves the tag 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(GetTagConsumptionRequest 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"; + TagConsumptionDto[] response = await _apiHttpClient.GetAsync(BuildTagConsumptionEndpoint(request), cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } + + /// + /// Builds the API endpoint used to retrieve the tag consumption of the selected user. + /// + /// The request containing the selected user and the optional filters. + /// The API endpoint to which the tag request is sent. + private static string BuildTagConsumptionEndpoint(GetTagConsumptionRequest 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_TAG_CONSUMPTION + : ApiRoutes.LibraryStatistics.GET_USER_TAG_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/GetTagConsumption/GetTagConsumptionEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.cs new file mode 100644 index 00000000..43b82a19 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetTagConsumption/GetTagConsumptionEndpointSummary.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.GetTagConsumption; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetTagConsumptionEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetTagConsumptionEndpointSummary() + { + Summary = "Gets the tag consumption of the selected user."; + Description = "Proxies the request that gets the tags 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 tag 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 GetTagConsumptionRequest( + 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 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(200, "The tag consumption of the selected user is returned, or a JSON error with success set to false.", + example: new SuccessResponse(true, + [ + new TagConsumptionDto( + Name: "favourite", + ConsumedItemCount: 3, + ConsumedDurationInSeconds: 5400), + new TagConsumptionDto( + Name: "book-club", + ConsumedItemCount: 2, + ConsumedDurationInSeconds: 7320), + new TagConsumptionDto( + Name: "comfort-read", + ConsumedItemCount: 1, + ConsumedDurationInSeconds: 1424.5) + ]) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetUsers/GetUsersEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetUsers/GetUsersEndpoint.cs new file mode 100644 index 00000000..915519a0 --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetUsers/GetUsersEndpoint.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.Api; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +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.GetUsers; + +/// +/// API endpoint for the /{culture}/library/statistics/api-get-users route. +/// +public class GetUsersEndpoint : BaseEndpoint +{ + private readonly IApiHttpClient _apiHttpClient; + + /// + /// Initializes a new instance of the class. + /// + /// Injected service for interactions with the API. + public GetUsersEndpoint(IApiHttpClient apiHttpClient) + { + _apiHttpClient = apiHttpClient; + } + + /// + /// Configures the endpoint. + /// + public override void Configure() + { + base.Configure(); + Verbs(Http.GET); + Routes(WebRoutes.LibraryStatistics.GET_USERS); + DontAutoTag(); + Options(options => options.WithTags("Statistics")); + Policies(AuthorizationPolicies.REQUIRE_ADMIN_ROLE); + } + + /// + /// Retrieves the users available for the administrator user selector. + /// + /// The request object. + /// Cancellation token that can be used to stop the execution. + public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken) + { + // The user list is administrative data, 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"; + UserDto[] response = await _apiHttpClient.GetAsync(ApiRoutes.Authentication.USERS, cancellationToken).ConfigureAwait(false); + return JsonSuccess(response); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetUsers/GetUsersEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetUsers/GetUsersEndpointSummary.cs new file mode 100644 index 00000000..062fd67f --- /dev/null +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetUsers/GetUsersEndpointSummary.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using FastEndpoints; +using Lumina.Presentation.Web.Common.DTO.Common; +using Lumina.Presentation.Web.Common.DTO.UsersManagement; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetUsers; + +/// +/// Class used for providing a textual description for the endpoint, for OpenAPI. +/// +[ExcludeFromCodeCoverage] +public class GetUsersEndpointSummary : Summary +{ + /// + /// Initializes a new instance of the class. + /// + public GetUsersEndpointSummary() + { + Summary = "Gets the users available for the administrator user selector."; + Description = "Proxies the request that gets the list of users to the API server. Only an administrator can call it. A failure is returned as a JSON object with success set to false and a localized errorMessage."; + + ResponseParam>(response => response.IsSuccess, "Whether the operation succeeded."); + ResponseParam(response => response.Id, "The unique identifier of the user."); + ResponseParam(response => response.Username, "The username of the user."); + + Response(200, "The users available for the selector are returned, or a JSON error with success set to false.", + example: new SuccessResponse(true, + [ + new UserDto( + Id: Guid.Parse("1a2b3c4d-5e6f-4a1b-8c2d-3e4f5a6b7c8d"), + Username: "john.doe"), + new UserDto( + Id: Guid.Parse("2b3c4d5e-6f7a-4b8c-9d0e-1f2a3b4c5d6e"), + Username: "jane.doe") + ]) + ); + } +} diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpoint.cs index a0199b22..b8c91a7b 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpoint.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpoint.cs @@ -1,5 +1,7 @@ #region ========================================================================= USING ===================================================================================== using FastEndpoints; +using Lumina.Presentation.Web.Common.Authorization; +using Lumina.Presentation.Web.Common.DTO.MediaConsumption; using Lumina.Presentation.Web.Common.DTO.Themes; using Lumina.Presentation.Web.Common.Primitives; using Lumina.Presentation.Web.Common.Routes; @@ -10,6 +12,7 @@ using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Localization; using System; using System.Collections.Generic; +using System.Security.Claims; using System.Threading; using System.Threading.Tasks; #endregion @@ -30,6 +33,7 @@ public class StatisticsIndexViewEndpoint : BaseEndpoint private readonly IUrlService _urlService; private readonly ThemePageRenderer _themePageRenderer; private readonly IStringLocalizer _localizer; + private readonly IAuthorizationService _authorizationService; /// /// Initializes a new instance of the class. @@ -37,11 +41,13 @@ public class StatisticsIndexViewEndpoint : BaseEndpoint /// Injected service for generating URLs from action and controller names, with localization. /// Injected service for rendering themed pages. /// Injected factory used to create the localizer of the view resources. - public StatisticsIndexViewEndpoint(IUrlService urlService, ThemePageRenderer themePageRenderer, IStringLocalizerFactory stringLocalizerFactory) + /// Injected service used to resolve the role of the current user. + public StatisticsIndexViewEndpoint(IUrlService urlService, ThemePageRenderer themePageRenderer, IStringLocalizerFactory stringLocalizerFactory, IAuthorizationService authorizationService) { _urlService = urlService; _themePageRenderer = themePageRenderer; _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION); + _authorizationService = authorizationService; } /// @@ -57,7 +63,7 @@ public class StatisticsIndexViewEndpoint : BaseEndpoint } /// - /// Displays the statistics of the current user, rendered by the active theme with a fallback to the Razor view. + /// Displays the statistics page, rendered by the active theme with a fallback to the Razor view. /// /// The request object. /// Cancellation token that can be used to stop the execution. @@ -67,9 +73,28 @@ public class StatisticsIndexViewEndpoint : BaseEndpoint HttpContext.Response.Headers["Cache-Control"] = "private, no-store"; HttpContext.Response.Headers["Vary"] = "Cookie"; string title = _localizer["Title"].Value; + bool isAdmin = await _authorizationService.IsInRoleAsync("Admin", cancellationToken).ConfigureAwait(false); + string? currentUserId = HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; + Guid? parsedCurrentUserId = Guid.TryParse(currentUserId, out Guid userId) ? userId : null; + + StatisticsPageDto page = new( + Title: title, + IsAdmin: isAdmin, + CurrentUserId: parsedCurrentUserId, + Culture: Culture, + GetStatisticsUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_STATISTICS) ?? string.Empty, + GetAllUsersStatisticsUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_ALL_USERS_STATISTICS) ?? string.Empty, + GetRecentlyConsumedUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_RECENTLY_CONSUMED) ?? string.Empty, + GetMostConsumedUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_MOST_CONSUMED) ?? string.Empty, + GetTagConsumptionUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_TAG_CONSUMPTION) ?? string.Empty, + GetGenreConsumptionUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_GENRE_CONSUMPTION) ?? string.Empty, + GetLibrariesUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_LIBRARIES) ?? string.Empty, + GetUsersUrl: isAdmin ? _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_USERS) ?? string.Empty : string.Empty, + DeleteConsumptionItemHistoryUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.DELETE_CONSUMPTION_ITEM_HISTORY) ?? string.Empty, + ClearConsumptionHistoryUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.CLEAR_CONSUMPTION_HISTORY) ?? string.Empty, + ClearResumePointsUrl: _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.CLEAR_RESUME_POINTS) ?? string.Empty + ); - // The track link template carries the all-zero Guid placeholders of its route values, in route order (artist, album and track), which the - // page replaces one at a time. The detail page of a track expects the Id of its media library in the libraryId query parameter. ThemePageDto pageModel = new() { PageKey = VIEW_PAGE_KEY, @@ -77,18 +102,27 @@ public class StatisticsIndexViewEndpoint : BaseEndpoint Description = string.Empty, PageData = new Dictionary { - ["getRecentlyPlayedUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_RECENTLY_PLAYED) ?? string.Empty, - ["getMostPlayedUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_MOST_PLAYED) ?? string.Empty, - ["getStatisticsUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_MUSIC_PLAY_STATISTICS) ?? string.Empty, - ["trackUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.TRACK, new { artistId = default(Guid), albumId = default(Guid), trackId = default(Guid) }) ?? string.Empty, - ["culture"] = Culture, + ["getStatisticsUrl"] = page.GetStatisticsUrl, + ["getAllUsersStatisticsUrl"] = page.GetAllUsersStatisticsUrl, + ["getRecentlyConsumedUrl"] = page.GetRecentlyConsumedUrl, + ["getMostConsumedUrl"] = page.GetMostConsumedUrl, + ["getTagConsumptionUrl"] = page.GetTagConsumptionUrl, + ["getGenreConsumptionUrl"] = page.GetGenreConsumptionUrl, + ["getLibrariesUrl"] = page.GetLibrariesUrl, + ["getUsersUrl"] = page.GetUsersUrl, + ["deleteConsumptionItemHistoryUrl"] = page.DeleteConsumptionItemHistoryUrl, + ["clearConsumptionHistoryUrl"] = page.ClearConsumptionHistoryUrl, + ["clearResumePointsUrl"] = page.ClearResumePointsUrl, + ["culture"] = page.Culture, + ["isAdmin"] = page.IsAdmin, + ["currentUserId"] = page.CurrentUserId, ["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer) } }; Result sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false); if (sectionResult.IsFailure) - return View("/Core/Views/Library/Statistics/Index.cshtml", viewData: new Dictionary { ["Title"] = title }); + return View("/Core/Views/Library/Statistics/Index.cshtml", page, new Dictionary { ["Title"] = title }); return View("/Core/Views/Shared/_ThemedView.cshtml", new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), new Dictionary { ["Title"] = title }); } diff --git a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpointSummary.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpointSummary.cs index be24f999..28902d13 100644 --- a/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpointSummary.cs +++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpointSummary.cs @@ -17,7 +17,7 @@ public class StatisticsIndexViewEndpointSummary : Summary + text/microsoft-resx @@ -15,29 +15,149 @@ الإحصائيات - - إجمالي وقت الاستماع + + إجمالي وقت الاستهلاك - - مرات التشغيل + + الجلسات المحتسبة - - مرات التشغيل المكتملة + + الجلسات المكتملة معدل الإكمال - - شُغّل مؤخراً + + حسب نوع الوسائط - - الأكثر تشغيلاً + + نوع الوسائط - - لا توجد مرات تشغيل محتسبة بعد. + + الوقت + + + متوقفة + + + محتسبة + + + مكتملة + + + الأنواع + + + العلامات + + + لا توجد بيانات أنواع لهذه عوامل التصفية. + + + لا توجد بيانات علامات لهذه عوامل التصفية. + + + عناصر + + + المستهلك مؤخراً + + + الأكثر استهلاكاً + + + لا توجد عناصر مستهلكة مؤخراً. + + + لا توجد عناصر أكثر استهلاكاً. + + + آخر استهلاك - هذا المقطع لم يعد متاحاً. + هذا العنصر لم يعد متاحاً. + + + حذف من السجل + + + هل تريد حذف كل الجلسات المسجلة لهذا العنصر من السجل؟ + + + تم حذف إدخال السجل. + + + مسح السجل + + + هل تريد حذف سجل الاستهلاك بالكامل للمستخدم المحدد؟ + + + تم مسح سجل الاستهلاك. + + + إزالة من متابعة المشاهدة + + + هل تريد إزالة كل نقاط الاستئناف للمستخدم المحدد؟ يتم الاحتفاظ بالسجل. + + + تمت إزالة نقاط الاستئناف. + + + عوامل التصفية + + + المكتبة + + + كل المكتبات + + + كل أنواع الوسائط + + + من + + + إلى + + + تطبيق + + + إعادة تعيين + + + يجب ألا يكون تاريخ البداية بعد تاريخ النهاية. + + + المستخدم + + + كل المستخدمين + + + أنا + + + السجل وتفصيل العلامات متاحان لكل مستخدم. اختر مستخدماً لعرضهما. + + + لكل مستخدم + + + لا يوجد مستخدمون لديهم إحصائيات استهلاك لهذه عوامل التصفية. + + + لا توجد بيانات نوع وسائط لهذه عوامل التصفية. + + + لا يوجد سجل استهلاك لهذه عوامل التصفية. + + + جارٍ التحميل... تعذر تحميل الإحصائيات. @@ -45,20 +165,29 @@ إعادة المحاولة - - مرات تشغيل + + مقطع - - مكتملة + + حلقة بودكاست - - آخر تشغيل + + كتاب صوتي - - تشغيل المقطع + + فيلم - - إضافة إلى قائمة التشغيل + + حلقة تلفزيونية + + + كتاب + + + صورة + + + فيديو س @@ -69,4 +198,4 @@ ث - + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.de-DE.resx index 000d7b76..0bad0952 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.de-DE.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.de-DE.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -15,58 +15,187 @@ Statistik - - Gesamte Hörzeit + + Gesamte konsumierte Zeit - - Wiedergaben + + Gezählte Sitzungen - - Abgeschlossene Wiedergaben + + Abgeschlossene Sitzungen Abschlussrate - - Zuletzt gehört + + Nach Medienart - - Meistgehört + + Medienart - - Es gibt noch keine gezählten Wiedergaben. + + Zeit + + + Gestoppt + + + Gezählt + + + Abgeschlossen + + + Genres + + + Tags + + + Keine Genre-Daten für diese Filter. + + + Keine Tag-Daten für diese Filter. + + + Elemente + + + Kürzlich konsumiert + + + Meistkonsumiert + + + Keine kürzlich konsumierten Elemente. + + + Keine meistkonsumierten Elemente. + + + Zuletzt konsumiert - Dieser Titel ist nicht mehr verfügbar. + Dieses Element ist nicht mehr verfügbar. + + + Aus dem Verlauf löschen + + + Alle aufgezeichneten Sitzungen dieses Elements aus dem Verlauf löschen? + + + Der Verlaufseintrag wurde gelöscht. + + + Verlauf löschen + + + Den gesamten Konsumverlauf des ausgewählten Benutzers löschen? + + + Der Konsumverlauf wurde gelöscht. + + + Aus Weiterschauen entfernen + + + Alle Fortsetzungspunkte des ausgewählten Benutzers entfernen? Der Verlauf bleibt erhalten. + + + Die Fortsetzungspunkte wurden entfernt. + + + Filter + + + Bibliothek + + + Alle Bibliotheken + + + Alle Medienarten + + + Von + + + Bis + + + Anwenden + + + Zurücksetzen + + + Das Startdatum darf nicht nach dem Enddatum liegen. + + + Benutzer + + + Alle Benutzer + + + Ich + + + Der Verlauf und die Tag-Aufschlüsselung sind pro Benutzer verfügbar. Wählen Sie einen Benutzer aus, um sie zu sehen. + + + Pro Benutzer + + + Keine Benutzer haben Konsumstatistiken für diese Filter. + + + Keine Medienart-Daten für diese Filter. + + + Es gibt keinen Konsumverlauf für diese Filter. + + + Wird geladen... Die Statistik konnte nicht geladen werden. - Wiederholen + Erneut versuchen - - Wiedergaben + + Titel - - abgeschlossen + + Podcast-Episode - - Zuletzt gehört + + Hörbuch - - Titel abspielen + + Film - - Zu Wiedergabeliste hinzufügen + + TV-Episode + + + Buch + + + Foto + + + Video - h + Std. - m + Min. - s + Sek. - + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.en-US.resx index 61fbbf25..ea2d7993 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.en-US.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.en-US.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -15,29 +15,149 @@ Statistics - - Total listening time + + Total consumed time - - Plays + + Counted sessions - - Completed plays + + Completed sessions Completion rate - - Recently played + + By media kind - - Most played + + Media kind - - There are no counted plays yet. + + Time + + + Stopped + + + Counted + + + Completed + + + Genres + + + Tags + + + No genre data for these filters. + + + No tag data for these filters. + + + items + + + Recently consumed + + + Most consumed + + + No recently consumed items. + + + No most consumed items. + + + Last consumed - This track is no longer available. + This item is no longer available. + + + Delete from history + + + Delete every recorded session of this item from the history? + + + The history entry was deleted. + + + Clear history + + + Delete the entire consumption history of the selected user? + + + The consumption history was cleared. + + + Remove from continue watching + + + Remove every resume point of the selected user? The history is kept. + + + The resume points were removed. + + + Filters + + + Library + + + All libraries + + + All media kinds + + + From + + + To + + + Apply + + + Reset + + + The start date must not be after the end date. + + + User + + + All users + + + Me + + + The history and the tag breakdown are available per user. Select a user to see them. + + + Per user + + + No users have consumption statistics for these filters. + + + No media kind data for these filters. + + + There is no consumption history for these filters. + + + Loading... The statistics could not be loaded. @@ -45,20 +165,29 @@ Retry - - plays + + Track - - completed + + Podcast episode - - Last played + + Audiobook - - Play track + + Movie - - Add to playlist + + TV episode + + + Book + + + Photo + + + Video h @@ -69,4 +198,4 @@ s - + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.es-ES.resx index e3620f3e..78562d59 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.es-ES.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.es-ES.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -15,29 +15,149 @@ Estadísticas - - Tiempo total de escucha + + Tiempo total consumido - - Reproducciones + + Sesiones contabilizadas - - Reproducciones completadas + + Sesiones completadas Tasa de finalización - - Reproducido recientemente + + Por tipo de medio - - Más reproducido + + Tipo de medio - - Aún no hay reproducciones contabilizadas. + + Tiempo + + + Detenidas + + + Contabilizadas + + + Completadas + + + Géneros + + + Etiquetas + + + No hay datos de géneros para estos filtros. + + + No hay datos de etiquetas para estos filtros. + + + elementos + + + Consumido recientemente + + + Más consumido + + + No hay elementos consumidos recientemente. + + + No hay elementos más consumidos. + + + Último consumo - Esta pista ya no está disponible. + Este elemento ya no está disponible. + + + Eliminar del historial + + + ¿Eliminar todas las sesiones registradas de este elemento del historial? + + + La entrada del historial fue eliminada. + + + Borrar historial + + + ¿Borrar todo el historial de consumo del usuario seleccionado? + + + El historial de consumo fue borrado. + + + Quitar de continuar viendo + + + ¿Quitar todos los puntos de reanudación del usuario seleccionado? El historial se conserva. + + + Los puntos de reanudación fueron eliminados. + + + Filtros + + + Biblioteca + + + Todas las bibliotecas + + + Todos los tipos de medio + + + Desde + + + Hasta + + + Aplicar + + + Restablecer + + + La fecha de inicio no debe ser posterior a la fecha de fin. + + + Usuario + + + Todos los usuarios + + + Yo + + + El historial y el desglose de etiquetas están disponibles por usuario. Seleccione un usuario para verlos. + + + Por usuario + + + Ningún usuario tiene estadísticas de consumo para estos filtros. + + + No hay datos de tipo de medio para estos filtros. + + + No hay historial de consumo para estos filtros. + + + Cargando... No se pudieron cargar las estadísticas. @@ -45,20 +165,29 @@ Reintentar - - reproducciones + + Pista - - completadas + + Episodio de podcast - - Última reproducción + + Audiolibro - - Reproducir pista + + Película - - Añadir a la lista de reproducción + + Episodio de TV + + + Libro + + + Foto + + + Vídeo h @@ -69,4 +198,4 @@ s - + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.fr-FR.resx index fc41adf6..b19b3418 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.fr-FR.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.fr-FR.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -15,29 +15,149 @@ Statistiques - - Temps d'écoute total + + Temps total consommé - - Écoutes + + Sessions comptabilisées - - Écoutes terminées + + Sessions terminées Taux d'achèvement - - Écoutés récemment + + Par type de média - - Les plus écoutés + + Type de média - - Aucune écoute comptabilisée pour le moment. + + Temps + + + Arrêtées + + + Comptabilisées + + + Terminées + + + Genres + + + Étiquettes + + + Aucune donnée de genre pour ces filtres. + + + Aucune donnée d'étiquette pour ces filtres. + + + éléments + + + Consommé récemment + + + Le plus consommé + + + Aucun élément consommé récemment. + + + Aucun élément le plus consommé. + + + Dernière consommation - Ce morceau n'est plus disponible. + Cet élément n'est plus disponible. + + + Supprimer de l'historique + + + Supprimer toutes les sessions enregistrées de cet élément de l'historique ? + + + L'entrée de l'historique a été supprimée. + + + Effacer l'historique + + + Effacer tout l'historique de consommation de l'utilisateur sélectionné ? + + + L'historique de consommation a été effacé. + + + Retirer de la reprise + + + Retirer tous les points de reprise de l'utilisateur sélectionné ? L'historique est conservé. + + + Les points de reprise ont été retirés. + + + Filtres + + + Bibliothèque + + + Toutes les bibliothèques + + + Tous les types de média + + + Du + + + Au + + + Appliquer + + + Réinitialiser + + + La date de début ne doit pas être postérieure à la date de fin. + + + Utilisateur + + + Tous les utilisateurs + + + Moi + + + L'historique et la répartition des étiquettes sont disponibles par utilisateur. Sélectionnez un utilisateur pour les voir. + + + Par utilisateur + + + Aucun utilisateur n'a de statistiques de consommation pour ces filtres. + + + Aucune donnée de type de média pour ces filtres. + + + Aucun historique de consommation pour ces filtres. + + + Chargement... Les statistiques n'ont pas pu être chargées. @@ -45,20 +165,29 @@ Réessayer - - écoutes + + Piste - - terminées + + Épisode de podcast - - Dernière écoute + + Livre audio - - Lire le morceau + + Film - - Ajouter à la playlist + + Épisode TV + + + Livre + + + Photo + + + Vidéo h @@ -69,4 +198,4 @@ s - + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.it-IT.resx index e39347b3..151393ae 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.it-IT.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.it-IT.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -15,29 +15,149 @@ Statistiche - - Tempo di ascolto totale + + Tempo totale consumato - - Riproduzioni + + Sessioni conteggiate - - Riproduzioni completate + + Sessioni completate Tasso di completamento - - Riprodotti di recente + + Per tipo di contenuto - - Più riprodotti + + Tipo di contenuto - - Non ci sono ancora riproduzioni conteggiate. + + Tempo + + + Interrotte + + + Conteggiate + + + Completate + + + Generi + + + Tag + + + Nessun dato sui generi per questi filtri. + + + Nessun dato sui tag per questi filtri. + + + elementi + + + Consumati di recente + + + Più consumati + + + Nessun elemento consumato di recente. + + + Nessun elemento più consumato. + + + Ultimo consumo - Questo brano non è più disponibile. + Questo elemento non è più disponibile. + + + Elimina dalla cronologia + + + Eliminare dalla cronologia tutte le sessioni registrate di questo elemento? + + + La voce della cronologia è stata eliminata. + + + Cancella cronologia + + + Cancellare l'intera cronologia di consumo dell'utente selezionato? + + + La cronologia di consumo è stata cancellata. + + + Rimuovi da continua a guardare + + + Rimuovere tutti i punti di ripresa dell'utente selezionato? La cronologia viene mantenuta. + + + I punti di ripresa sono stati rimossi. + + + Filtri + + + Libreria + + + Tutte le librerie + + + Tutti i tipi di contenuto + + + Da + + + A + + + Applica + + + Reimposta + + + La data di inizio non deve essere successiva alla data di fine. + + + Utente + + + Tutti gli utenti + + + Io + + + La cronologia e la suddivisione dei tag sono disponibili per utente. Seleziona un utente per visualizzarle. + + + Per utente + + + Nessun utente ha statistiche di consumo per questi filtri. + + + Nessun dato sul tipo di contenuto per questi filtri. + + + Nessuna cronologia di consumo per questi filtri. + + + Caricamento... Impossibile caricare le statistiche. @@ -45,20 +165,29 @@ Riprova - - riproduzioni + + Brano - - completate + + Episodio di podcast - - Ultima riproduzione + + Audiolibro - - Riproduci brano + + Film - - Aggiungi alla playlist + + Episodio TV + + + Libro + + + Foto + + + Video h @@ -69,4 +198,4 @@ s - + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ja-JP.resx index 2ab3089d..41f9e201 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ja-JP.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ja-JP.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -15,29 +15,149 @@ 統計 - - 合計再生時間 + + 総消費時間 - - 再生回数 + + 集計対象セッション - - 最後まで再生した回数 + + 完了セッション 完了率 - - 最近再生した曲 + + メディア種別ごと - - よく再生する曲 + + メディア種別 - - 集計対象の再生はまだありません。 + + 時間 + + + 停止 + + + 集計対象 + + + 完了 + + + ジャンル + + + タグ + + + このフィルターのジャンルデータはありません。 + + + このフィルターのタグデータはありません。 + + + 件 + + + 最近消費したもの + + + 最も消費したもの + + + 最近消費したものはありません。 + + + 最も消費したものはありません。 + + + 最終消費 - この曲はもう利用できません。 + このアイテムはもう利用できません。 + + + 履歴から削除 + + + このアイテムの記録されたすべてのセッションを履歴から削除しますか? + + + 履歴の項目を削除しました。 + + + 履歴を消去 + + + 選択したユーザーの消費履歴をすべて削除しますか? + + + 消費履歴を消去しました。 + + + 続きを見るから削除 + + + 選択したユーザーの再開ポイントをすべて削除しますか? 履歴は保持されます。 + + + 再開ポイントを削除しました。 + + + フィルター + + + ライブラリ + + + すべてのライブラリ + + + すべてのメディア種別 + + + 開始 + + + 終了 + + + 適用 + + + リセット + + + 開始日は終了日より後にできません。 + + + ユーザー + + + すべてのユーザー + + + 自分 + + + 履歴とタグの内訳はユーザーごとに表示されます。表示するユーザーを選択してください。 + + + ユーザーごと + + + このフィルターの消費統計を持つユーザーはいません。 + + + このフィルターのメディア種別データはありません。 + + + このフィルターの消費履歴はありません。 + + + 読み込み中... 統計を読み込めませんでした。 @@ -45,20 +165,29 @@ 再試行 - - 回 + + トラック - - 回完了 + + ポッドキャストエピソード - - 最終再生 + + オーディオブック - - 曲を再生 + + 映画 - - プレイリストに追加 + + TVエピソード + + + 本 + + + 写真 + + + 動画 時間 @@ -69,4 +198,4 @@ 秒 - + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.resx index 61fbbf25..ea2d7993 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -15,29 +15,149 @@ Statistics - - Total listening time + + Total consumed time - - Plays + + Counted sessions - - Completed plays + + Completed sessions Completion rate - - Recently played + + By media kind - - Most played + + Media kind - - There are no counted plays yet. + + Time + + + Stopped + + + Counted + + + Completed + + + Genres + + + Tags + + + No genre data for these filters. + + + No tag data for these filters. + + + items + + + Recently consumed + + + Most consumed + + + No recently consumed items. + + + No most consumed items. + + + Last consumed - This track is no longer available. + This item is no longer available. + + + Delete from history + + + Delete every recorded session of this item from the history? + + + The history entry was deleted. + + + Clear history + + + Delete the entire consumption history of the selected user? + + + The consumption history was cleared. + + + Remove from continue watching + + + Remove every resume point of the selected user? The history is kept. + + + The resume points were removed. + + + Filters + + + Library + + + All libraries + + + All media kinds + + + From + + + To + + + Apply + + + Reset + + + The start date must not be after the end date. + + + User + + + All users + + + Me + + + The history and the tag breakdown are available per user. Select a user to see them. + + + Per user + + + No users have consumption statistics for these filters. + + + No media kind data for these filters. + + + There is no consumption history for these filters. + + + Loading... The statistics could not be loaded. @@ -45,20 +165,29 @@ Retry - - plays + + Track - - completed + + Podcast episode - - Last played + + Audiobook - - Play track + + Movie - - Add to playlist + + TV episode + + + Book + + + Photo + + + Video h @@ -69,4 +198,4 @@ s - + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ro-RO.resx index 4fa6fe4b..f4e9cdaf 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ro-RO.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ro-RO.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -15,29 +15,149 @@ Statistici - - Timp total de ascultare + + Timp total consumat - - Redări + + Sesiuni contorizate - - Redări finalizate + + Sesiuni finalizate Rată de finalizare - - Ascultate recent + + După tipul de conținut - - Cele mai ascultate + + Tip de conținut - - Nu există încă redări contorizate. + + Timp + + + Oprite + + + Contorizate + + + Finalizate + + + Genuri + + + Etichete + + + Nu există date despre genuri pentru aceste filtre. + + + Nu există date despre etichete pentru aceste filtre. + + + elemente + + + Consumate recent + + + Cele mai consumate + + + Nu există elemente consumate recent. + + + Nu există elemente cele mai consumate. + + + Ultima consumare - Această piesă nu mai este disponibilă. + Acest element nu mai este disponibil. + + + Șterge din istoric + + + Ștergi toate sesiunile înregistrate ale acestui element din istoric? + + + Intrarea din istoric a fost ștearsă. + + + Golește istoricul + + + Ștergi întregul istoric de consum al utilizatorului selectat? + + + Istoricul de consum a fost golit. + + + Elimină din continuă vizionarea + + + Elimini toate punctele de reluare ale utilizatorului selectat? Istoricul este păstrat. + + + Punctele de reluare au fost eliminate. + + + Filtre + + + Bibliotecă + + + Toate bibliotecile + + + Toate tipurile de conținut + + + De la + + + Până la + + + Aplică + + + Resetează + + + Data de început nu trebuie să fie după data de sfârșit. + + + Utilizator + + + Toți utilizatorii + + + Eu + + + Istoricul și defalcarea etichetelor sunt disponibile pentru fiecare utilizator. Selectează un utilizator pentru a le vedea. + + + Per utilizator + + + Niciun utilizator nu are statistici de consum pentru aceste filtre. + + + Nu există date despre tipul de conținut pentru aceste filtre. + + + Nu există istoric de consum pentru aceste filtre. + + + Se încarcă... Statisticile nu au putut fi încărcate. @@ -45,20 +165,29 @@ Reîncearcă - - redări + + Pistă - - finalizate + + Episod de podcast - - Ultima redare + + Carte audio - - Redă piesa + + Film - - Adaugă la playlist + + Episod TV + + + Carte + + + Fotografie + + + Videoclip h @@ -69,4 +198,4 @@ s - + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.uk-UA.resx index 566abeae..f4293c6b 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.uk-UA.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.uk-UA.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -15,29 +15,149 @@ Статистика - - Загальний час прослуховування + + Загальний спожитий час - - Відтворення + + Зараховані сеанси - - Завершені відтворення + + Завершені сеанси Відсоток завершення - - Нещодавно відтворені + + За типом медіа - - Найчастіше відтворювані + + Тип медіа - - Ще немає зарахованих відтворень. + + Час + + + Зупинені + + + Зараховані + + + Завершені + + + Жанри + + + Теги + + + Немає даних про жанри для цих фільтрів. + + + Немає даних про теги для цих фільтрів. + + + елементів + + + Нещодавно спожиті + + + Найбільш спожиті + + + Немає нещодавно спожитих елементів. + + + Немає найбільш спожитих елементів. + + + Останнє споживання - Цей трек більше недоступний. + Цей елемент більше недоступний. + + + Видалити з історії + + + Видалити з історії всі записані сеанси цього елемента? + + + Запис історії видалено. + + + Очистити історію + + + Видалити всю історію споживання вибраного користувача? + + + Історію споживання очищено. + + + Видалити з продовження перегляду + + + Видалити всі точки продовження вибраного користувача? Історія зберігається. + + + Точки продовження видалено. + + + Фільтри + + + Бібліотека + + + Усі бібліотеки + + + Усі типи медіа + + + Від + + + До + + + Застосувати + + + Скинути + + + Дата початку не може бути пізніше дати завершення. + + + Користувач + + + Усі користувачі + + + Я + + + Історія та розподіл тегів доступні для кожного користувача. Виберіть користувача, щоб переглянути їх. + + + Для кожного користувача + + + Жоден користувач не має статистики споживання для цих фільтрів. + + + Немає даних про тип медіа для цих фільтрів. + + + Немає історії споживання для цих фільтрів. + + + Завантаження... Не вдалося завантажити статистику. @@ -45,20 +165,29 @@ Повторити - - відтворень + + Трек - - завершено + + Епізод подкасту - - Останнє відтворення + + Аудіокнига - - Відтворити трек + + Фільм - - Додати до плейлиста + + Епізод телесеріалу + + + Книга + + + Фото + + + Відео год @@ -69,4 +198,4 @@ с - + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.zh-CN.resx index c3d0fdcc..fa14bd14 100644 --- a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.zh-CN.resx +++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.zh-CN.resx @@ -1,4 +1,4 @@ - + text/microsoft-resx @@ -15,29 +15,149 @@ 统计 - - 总收听时间 + + 总消费时长 - - 播放次数 + + 计入的会话 - - 完整播放次数 + + 已完成的会话 完成率 - - 最近播放 + + 按媒体类型 - - 最常播放 + + 媒体类型 - - 还没有计入的播放。 + + 时长 + + + 已停止 + + + 已计入 + + + 已完成 + + + 类型 + + + 标签 + + + 这些筛选条件下没有类型数据。 + + + 这些筛选条件下没有标签数据。 + + + 项 + + + 最近消费 + + + 最常消费 + + + 没有最近消费的项目。 + + + 没有最常消费的项目。 + + + 最近消费时间 - 此曲目已不可用。 + 此项目已不可用。 + + + 从历史记录中删除 + + + 要从历史记录中删除此项目的所有已记录会话吗? + + + 历史记录项已删除。 + + + 清除历史记录 + + + 要删除所选用户的全部消费历史记录吗? + + + 消费历史记录已清除。 + + + 从继续观看中移除 + + + 要移除所选用户的全部继续播放点吗?历史记录会保留。 + + + 继续播放点已移除。 + + + 筛选 + + + 媒体库 + + + 所有媒体库 + + + 所有媒体类型 + + + 从 + + + 到 + + + 应用 + + + 重置 + + + 开始日期不能晚于结束日期。 + + + 用户 + + + 所有用户 + + + 我 + + + 历史记录和标签明细按用户提供。请选择用户以查看。 + + + 按用户 + + + 没有用户在这些筛选条件下有消费统计。 + + + 这些筛选条件下没有媒体类型数据。 + + + 这些筛选条件下没有消费历史记录。 + + + 正在加载... 无法加载统计。 @@ -45,28 +165,37 @@ 重试 - - 次播放 + + 曲目 - - 次完整播放 + + 播客单集 - - 上次播放 + + 有声书 - - 播放曲目 + + 电影 - - 添加到播放列表 + + 电视单集 + + + 书籍 + + + 照片 + + + 视频 小时 - 分钟 + 分 秒 - + \ No newline at end of file diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/Statistics/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/Statistics/Index.cshtml index 52ed0f07..3af27ec9 100644 --- a/src/Lumina.Presentation.Web/Core/Views/Library/Statistics/Index.cshtml +++ b/src/Lumina.Presentation.Web/Core/Views/Library/Statistics/Index.cshtml @@ -4,55 +4,83 @@ This view is the application fallback of the statistics page, rendered when the active theme provides no template for the page or its template cannot be loaded. It keeps the DOM contract and the client script a theme template would mirror. - The page summarizes the plays of the current user: the total listening time, the counted plays, the completed plays and the - completion rate, followed by the recently played tracks and the most played tracks. A play counts when it completed or when the - listened duration reached 30 seconds, which the server applies. The script loads the three sections in parallel and renders a row per - track, with a play trigger, a favorite heart and an add to playlist action, so the page behaves like the other track lists. + The page shows the consumption statistics of the selected user, across every media kind: the total consumed duration, the + counted sessions, the completed sessions, the completion rate, the per media kind breakdown, the tags and genres, and the + recently consumed and most consumed media items. An administrator can select another user or all users; a regular user sees + only their own statistics. The filter bar restricts every section by library, media kind, and date range. The history actions + delete one row, clear the history, or remove the resume points, after a confirmation. - The element hooks the script needs are statistics-total-listening-time, statistics-total-plays, statistics-completed-plays, - statistics-completion-rate, recently-played-list, most-played-list, statistics-empty-state, statistics-load-failed and - retry-statistics-button. + The element hooks the script needs are statistics-user-filter, statistics-user-filter-toggle, + statistics-user-filter-dropdown, statistics-library-filter, statistics-library-filter-toggle, + statistics-library-filter-dropdown, statistics-kind-filter, statistics-kind-filter-toggle, statistics-from-date, + statistics-to-date, statistics-apply-filters, statistics-reset-filters, statistics-loading, statistics-load-failed, + retry-statistics-button, statistics-content, statistics-total-duration, statistics-counted-sessions, + statistics-completed-sessions, statistics-completion-rate, statistics-media-kind-breakdown, statistics-no-media-kind, + statistics-users-section, statistics-users-table, statistics-no-users, statistics-terms, statistics-genres, + statistics-tags, statistics-no-genres, statistics-no-tags, statistics-history-section, statistics-clear-history, + statistics-clear-resume-points, statistics-recently-consumed, statistics-no-recently-consumed, statistics-most-consumed, + statistics-no-most-consumed, statistics-all-users-note and statistics-empty-state. - To restyle the page, edit the theme files. This fallback is intentionally plain, so that a broken theme is obvious to the user while the page still functions. + To restyle the page, edit the theme files. This fallback is intentionally plain, so that a broken theme is obvious to the user + while the page still functions. /library/statistics *@ +@model Lumina.Presentation.Web.Common.DTO.MediaConsumption.StatisticsPageDto + +@using Lumina.Presentation.Web.Common.Enums.MediaConsumption @using Lumina.Presentation.Web.Common.Services @using Microsoft.AspNetCore.Mvc.Localization @using System @using System.Collections.Generic -@using System.Globalization +@using System.Linq @using System.Text.Json @using System.Text.Json.Serialization @inject IViewLocalizer _localizer -@inject IUrlService _urlService @{ // Generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler. var scriptId = ScriptIdentifierHelper.GenerateScriptId(); + MediaKind[] mediaKinds = [.. Enum.GetValues().Where(mediaKind => mediaKind != MediaKind.None)]; var strings = new Dictionary { - ["title"] = _localizer["Title"].Value, - ["totalListeningTime"] = _localizer["TotalListeningTime"].Value, - ["totalPlays"] = _localizer["TotalPlays"].Value, - ["completedPlays"] = _localizer["CompletedPlays"].Value, - ["completionRate"] = _localizer["CompletionRate"].Value, - ["recentlyPlayed"] = _localizer["RecentlyPlayed"].Value, - ["mostPlayed"] = _localizer["MostPlayed"].Value, - ["noPlaysYet"] = _localizer["NoPlaysYet"].Value, - ["unavailable"] = _localizer["Unavailable"].Value, - ["loadFailed"] = _localizer["LoadFailed"].Value, - ["retry"] = _localizer["Retry"].Value, - ["plays"] = _localizer["Plays"].Value, - ["completed"] = _localizer["Completed"].Value, - ["lastPlayed"] = _localizer["LastPlayed"].Value, - ["playTrack"] = _localizer["PlayTrack"].Value, - ["addToPlaylist"] = _localizer["AddToPlaylist"].Value, ["hoursShort"] = _localizer["HoursShort"].Value, ["minutesShort"] = _localizer["MinutesShort"].Value, - ["secondsShort"] = _localizer["SecondsShort"].Value + ["secondsShort"] = _localizer["SecondsShort"].Value, + ["invalidDateRange"] = _localizer["InvalidDateRange"].Value, + ["mediaKind"] = _localizer["MediaKind"].Value, + ["duration"] = _localizer["Duration"].Value, + ["countedSessions"] = _localizer["CountedSessions"].Value, + ["completedSessions"] = _localizer["CompletedSessions"].Value, + ["stopped"] = _localizer["Stopped"].Value, + ["completionRate"] = _localizer["CompletionRate"].Value, + ["user"] = _localizer["User"].Value, + ["items"] = _localizer["Items"].Value, + ["unavailable"] = _localizer["Unavailable"].Value, + ["lastConsumed"] = _localizer["LastConsumed"].Value, + ["counted"] = _localizer["Counted"].Value, + ["completed"] = _localizer["Completed"].Value, + ["deleteFromHistory"] = _localizer["DeleteFromHistory"].Value, + ["deleteFromHistoryConfirm"] = _localizer["DeleteFromHistoryConfirm"].Value, + ["historyEntryDeleted"] = _localizer["HistoryEntryDeleted"].Value, + ["clearHistoryConfirm"] = _localizer["ClearHistoryConfirm"].Value, + ["historyCleared"] = _localizer["HistoryCleared"].Value, + ["clearResumePointsConfirm"] = _localizer["ClearResumePointsConfirm"].Value, + ["resumePointsCleared"] = _localizer["ResumePointsCleared"].Value, + ["allLibraries"] = _localizer["AllLibraries"].Value, + ["allMediaKinds"] = _localizer["AllMediaKinds"].Value, + ["allUsers"] = _localizer["AllUsers"].Value, + ["me"] = _localizer["Me"].Value, + ["kindMusicTrack"] = _localizer["KindMusicTrack"].Value, + ["kindPodcastEpisode"] = _localizer["KindPodcastEpisode"].Value, + ["kindAudiobook"] = _localizer["KindAudiobook"].Value, + ["kindMovie"] = _localizer["KindMovie"].Value, + ["kindTvEpisode"] = _localizer["KindTvEpisode"].Value, + ["kindBook"] = _localizer["KindBook"].Value, + ["kindPhoto"] = _localizer["KindPhoto"].Value, + ["kindVideo"] = _localizer["KindVideo"].Value }; var jsonOptions = new JsonSerializerOptions { @@ -61,43 +89,152 @@ }; } +@Html.AntiForgeryToken() +
-
-
-
-
-

@_localizer["Title"]

+
+
+

@_localizer["Title"]

+
+ + @if (Model.IsAdmin) + { +
+
+ @_localizer["User"] +
+
+ + +
+
+
@_localizer["AllUsers"]
+
+
+
- -
+ } + +
+
+ @_localizer["Library"] +
+
+ + +
+
+
@_localizer["AllLibraries"]
+
+
+
+ +
+ @_localizer["MediaKind"] +
+
+ + +
+
+
@_localizer["AllMediaKinds"]
+ @for (int index = 0; index < mediaKinds.Length; index++) + { +
@_localizer["Kind" + mediaKinds[index]]
+ } +
+
+
+ + + + + +
+ + +
+
+ +

@_localizer["Loading"]

+ +
+ +
+ +
@@ -106,42 +243,79 @@