diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayStatisticsDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayStatisticsDto.cs
new file mode 100644
index 00000000..d3a2a618
--- /dev/null
+++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayStatisticsDto.cs
@@ -0,0 +1,22 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+
+///
+/// Data transfer object for the listening statistics of the current user.
+///
+/// The total duration the user listened to, over every recorded play, in milliseconds.
+/// 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(
+ long TotalListeningDurationMilliseconds,
+ int TotalPlayCount,
+ int CompletedPlayCount,
+ int StoppedPlayCount,
+ double CompletionRate
+);
diff --git a/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/PlayedTrackDto.cs b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/PlayedTrackDto.cs
new file mode 100644
index 00000000..1ba82882
--- /dev/null
+++ b/src/Lumina.Application/Common/DTO/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/PlayedTrackDto.cs
@@ -0,0 +1,37 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Common.DTO.MediaLibrary.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 milliseconds.
+[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,
+ long ListenedDurationMilliseconds
+);
diff --git a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicPlayRecordRepository.cs b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicPlayRecordRepository.cs
index 584d1f42..47b1eecc 100644
--- a/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicPlayRecordRepository.cs
+++ b/src/Lumina.Application/Common/DataAccess/Repositories/MusicLibrary/IMusicPlayRecordRepository.cs
@@ -4,6 +4,7 @@ using Lumina.Application.Common.DataAccess.Repositories.Common.Actions;
using Lumina.Application.Common.DataAccess.Repositories.Common.Base;
using Lumina.Domain.Common.Primitives;
using System;
+using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -14,7 +15,7 @@ namespace Lumina.Application.Common.DataAccess.Repositories.MusicLibrary;
/// Interface for the repository for recorded music plays.
///
public interface IMusicPlayRecordRepository : IRepository,
- IInsertRepositoryAction
+ IInsertRepositoryAction
{
///
/// Gets the play record identified by when it belongs to the user identified by , if it exists.
@@ -29,6 +30,14 @@ public interface IMusicPlayRecordRepository : IRepository
///
Task> GetByIdForUserAsync(Guid id, Guid userId, bool shouldTrackEntities = true, CancellationToken cancellationToken = default);
+ ///
+ /// Gets the play records of the user identified by .
+ ///
+ /// The Id of the user whose play records are retrieved.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the play records of the user, or an error.
+ Task>> GetForUserAsync(Guid userId, CancellationToken cancellationToken);
+
///
/// Updates the play record of the user identified by , when the record belongs to that user and still holds the
/// version it was read with.
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayedRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayedRequestMapping.cs
new file mode 100644
index 00000000..4b40666e
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayedRequestMapping.cs
@@ -0,0 +1,31 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.Pagination;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetMostPlayed;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+
+///
+/// Extension methods for converting .
+///
+public static class GetMostPlayedRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted query.
+ public static GetMostPlayedQuery ToQuery(this GetMostPlayedRequest request)
+ {
+ PaginationDataDto? paginationData = null;
+ if (request.CurrentPage is not null || request.PerPage is not null)
+ paginationData = new PaginationDataDto
+ {
+ CurrentPage = request.CurrentPage ?? 1,
+ PerPage = request.PerPage ?? 50
+ };
+
+ return new GetMostPlayedQuery(paginationData);
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayedRequestMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayedRequestMapping.cs
new file mode 100644
index 00000000..dfd96ce4
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayedRequestMapping.cs
@@ -0,0 +1,31 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.Pagination;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetRecentlyPlayed;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+
+///
+/// Extension methods for converting .
+///
+public static class GetRecentlyPlayedRequestMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The request to be converted.
+ /// The converted query.
+ public static GetRecentlyPlayedQuery ToQuery(this GetRecentlyPlayedRequest request)
+ {
+ PaginationDataDto? paginationData = null;
+ if (request.CurrentPage is not null || request.PerPage is not null)
+ paginationData = new PaginationDataDto
+ {
+ CurrentPage = request.CurrentPage ?? 1,
+ PerPage = request.PerPage ?? 50
+ };
+
+ return new GetRecentlyPlayedQuery(paginationData);
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayRecordEntityMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayRecordEntityMapping.cs
index 8e8c84d7..5cb47d47 100644
--- a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayRecordEntityMapping.cs
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayRecordEntityMapping.cs
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.Utilities;
using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
using Lumina.Domain.Common.Primitives;
using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.ExternalIdentifiers.AudioLibraryBoundedContext.MusicLibraryAggregate;
@@ -34,8 +35,8 @@ public static class MusicPlayRecordEntityMapping
AlbumId.Create(repositoryEntity.AlbumId),
ArtistId.Create(repositoryEntity.ArtistId),
repositoryEntity.Status,
- MusicPlayPosition.Create(TimeSpan.FromMilliseconds(repositoryEntity.LastPositionMilliseconds)),
- TimeSpan.FromMilliseconds(repositoryEntity.ListenedDurationMilliseconds),
+ MusicPlayPosition.Create(repositoryEntity.LastPositionMilliseconds.ToClampedTimeSpan()),
+ repositoryEntity.ListenedDurationMilliseconds.ToClampedTimeSpan(),
Optional.FromNullable(repositoryEntity.EndedOnUtc),
repositoryEntity.CreatedOnUtc,
Optional.FromNullable(repositoryEntity.UpdatedOnUtc)
@@ -56,8 +57,8 @@ public static class MusicPlayRecordEntityMapping
repositoryEntity.AlbumId,
repositoryEntity.ArtistId,
repositoryEntity.Status,
- TimeSpan.FromMilliseconds(repositoryEntity.LastPositionMilliseconds).TotalSeconds,
- TimeSpan.FromMilliseconds(repositoryEntity.ListenedDurationMilliseconds).TotalSeconds,
+ repositoryEntity.LastPositionMilliseconds.ToClampedTimeSpan().TotalSeconds,
+ repositoryEntity.ListenedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds,
repositoryEntity.CreatedOnUtc,
repositoryEntity.EndedOnUtc,
repositoryEntity.UpdatedOnUtc
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayStatisticsDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayStatisticsDtoMapping.cs
new file mode 100644
index 00000000..0c659a52
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayStatisticsDtoMapping.cs
@@ -0,0 +1,29 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Application.Common.Utilities;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+
+///
+/// Extension methods for converting .
+///
+public static class MusicPlayStatisticsDtoMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The listening statistics data to be converted.
+ /// The converted response.
+ public static MusicPlayStatisticsResponse ToResponse(this MusicPlayStatisticsDto data)
+ {
+ return new MusicPlayStatisticsResponse(
+ data.TotalListeningDurationMilliseconds.ToClampedTimeSpan().TotalSeconds,
+ data.TotalPlayCount,
+ data.CompletedPlayCount,
+ data.StoppedPlayCount,
+ data.CompletionRate
+ );
+ }
+}
diff --git a/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/PlayedTrackDtoMapping.cs b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/PlayedTrackDtoMapping.cs
new file mode 100644
index 00000000..26d10553
--- /dev/null
+++ b/src/Lumina.Application/Common/Mapping/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/PlayedTrackDtoMapping.cs
@@ -0,0 +1,59 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Application.Common.DTO.Pagination;
+using Lumina.Application.Common.Utilities;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using System;
+using System.Linq;
+#endregion
+
+namespace Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+
+///
+/// Extension methods for converting .
+///
+public static class PlayedTrackDtoMapping
+{
+ ///
+ /// Converts to .
+ ///
+ /// The played track data to be converted.
+ /// The converted response.
+ public static PlayedTrackResponse ToResponse(this PlayedTrackDto data)
+ {
+ return new PlayedTrackResponse(
+ data.TrackId,
+ data.LibraryId,
+ data.AlbumId,
+ data.ArtistId,
+ data.Title,
+ data.AlbumTitle,
+ data.ArtistName,
+ data.CoverPath,
+ // The repository reads the stored play time through SQLite, which returns it as an unspecified kind, and the JSON response must not
+ // present a UTC wall clock as a local time. The value is UTC when it was stored, so it is marked as such before it is serialized.
+ DateTime.SpecifyKind(data.LastPlayedOnUtc, DateTimeKind.Utc),
+ data.PlayCount,
+ data.CompletedPlayCount,
+ data.ListenedDurationMilliseconds.ToClampedTimeSpan().TotalSeconds
+ );
+ }
+
+ ///
+ /// Converts to a paginated collection of .
+ ///
+ /// The paginated played track data to be converted.
+ /// The converted paginated responses.
+ public static PaginatedResponse ToResponses(this PaginatedResultDto data)
+ {
+ return new PaginatedResponse
+ {
+ Data = [.. data.Data.Select(track => track.ToResponse())],
+ CurrentPage = data.CurrentPage,
+ PerPage = data.PerPage,
+ Count = data.Count,
+ NumberOfPages = data.NumberOfPages
+ };
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetMostPlayed/GetMostPlayedQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetMostPlayed/GetMostPlayedQuery.cs
new file mode 100644
index 00000000..75ce8a99
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetMostPlayed/GetMostPlayedQuery.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DTO.Pagination;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetMostPlayed;
+
+///
+/// Query for getting the most played tracks of the current user, from the most played.
+///
+/// The object containing the requested pagination data, or to return every matching track.
+[DebuggerDisplay("PaginationData: {PaginationData}")]
+public record GetMostPlayedQuery(
+ PaginationDataDto? PaginationData
+) : IQuery;
diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetMostPlayed/GetMostPlayedQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetMostPlayed/GetMostPlayedQueryHandler.cs
new file mode 100644
index 00000000..0ae316a6
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetMostPlayed/GetMostPlayedQueryHandler.cs
@@ -0,0 +1,256 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Application.Common.DTO.Pagination;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
+using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Application.Common.Utilities;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.Playback;
+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.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetMostPlayed;
+
+///
+/// Handler for the query to get the most played tracks of the current user.
+///
+public class GetMostPlayedQueryHandler : IQueryHandler>>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+
+ ///
+ /// 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.
+ public GetMostPlayedQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IAuthorizationService authorizationService)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ }
+
+ ///
+ /// Handles the query to get the most played tracks of the current user.
+ ///
+ /// The query to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the requested page of most played tracks, or an error message.
+ ///
+ public async Task>> HandleAsync(GetMostPlayedQuery query, CancellationToken cancellationToken)
+ {
+ // 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;
+
+ Result> getRecordsResult = await _unitOfWork.MusicPlayRecordRepository.GetForUserAsync(userId, cancellationToken).ConfigureAwait(false);
+ if (getRecordsResult.IsFailure)
+ return getRecordsResult.Errors;
+
+ // Only the plays that count as plays are aggregated. The last activity of a track is the end of its most recent play, or the last
+ // progress update while that play is still in progress.
+ List aggregates = [.. getRecordsResult.Value
+ .Where(record => MusicPlayRecord.DoesCountAsPlay(record.Status, record.ListenedDurationMilliseconds.ToClampedTimeSpan()))
+ .GroupBy(record => new { record.TrackId, record.LibraryId, record.AlbumId, record.ArtistId })
+ .Select(group => new PlayedTrackAggregate(
+ group.Key.TrackId,
+ group.Key.LibraryId,
+ group.Key.AlbumId,
+ group.Key.ArtistId,
+ group.Max(record => record.EndedOnUtc ?? record.UpdatedOnUtc ?? record.CreatedOnUtc),
+ group.Count(),
+ group.Count(record => record.Status == PlaybackRecordStatus.Completed),
+ group.Sum(record => record.ListenedDurationMilliseconds)))
+ .OrderByDescending(aggregate => aggregate.PlayCount)
+ .ThenByDescending(aggregate => aggregate.ListenedDurationMilliseconds)
+ .ThenByDescending(aggregate => aggregate.LastActivityOnUtc)
+ .ThenBy(aggregate => aggregate.TrackId)];
+
+ return await ToResponsePageAsync(aggregates, query.PaginationData, userId, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Pages the aggregated tracks, resolves their display data, and converts them to the response of the query.
+ ///
+ /// The aggregated tracks, already ordered for this query.
+ /// The requested pagination data, or for every matching track.
+ /// The Id of the user whose tracks are retrieved.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the requested page of played tracks, or an error.
+ private async Task>> ToResponsePageAsync(
+ List aggregates, PaginationDataDto? paginationData, Guid userId, CancellationToken cancellationToken)
+ {
+ PaginatedResultDto page = Paginate(aggregates, paginationData);
+ Result> getDtosResult = await ToPlayedTrackDtosAsync(page.Data, userId, cancellationToken).ConfigureAwait(false);
+ if (getDtosResult.IsFailure)
+ return getDtosResult.Errors;
+
+ return Result.From(new PaginatedResultDto
+ {
+ Data = getDtosResult.Value,
+ CurrentPage = page.CurrentPage,
+ PerPage = page.PerPage,
+ Count = page.Count,
+ NumberOfPages = page.NumberOfPages
+ }.ToResponses());
+ }
+
+ ///
+ /// Applies the requested pagination to the ordered aggregated tracks.
+ ///
+ /// The ordered aggregated tracks.
+ /// The requested pagination data, or for every matching track.
+ /// The requested page of aggregated tracks.
+ private static PaginatedResultDto Paginate(List aggregates, PaginationDataDto? paginationData)
+ {
+ if (paginationData is null)
+ return new PaginatedResultDto
+ {
+ Data = aggregates,
+ CurrentPage = 1,
+ PerPage = aggregates.Count,
+ Count = aggregates.Count,
+ NumberOfPages = 1
+ };
+
+ int count = aggregates.Count;
+ int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
+ int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages));
+ List page = [.. aggregates
+ .Skip((currentPage - 1) * paginationData.PerPage)
+ .Take(paginationData.PerPage)];
+ return new PaginatedResultDto
+ {
+ Data = page,
+ CurrentPage = currentPage,
+ PerPage = paginationData.PerPage,
+ Count = count,
+ NumberOfPages = numberOfPages
+ };
+ }
+
+ ///
+ /// Resolves the display data of the tracks of for the libraries the user can access, and builds their DTOs.
+ ///
+ /// The aggregated tracks of the requested page.
+ /// The Id of the user whose tracks are retrieved.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the played tracks, with blank display data for missing or inaccessible tracks, or an error.
+ private async Task>> ToPlayedTrackDtosAsync(IReadOnlyList aggregates, Guid userId, CancellationToken cancellationToken)
+ {
+ if (aggregates.Count == 0)
+ return new List();
+
+ // The access decision only needs the library Id that the play record already carries, so it is made once per distinct library before any
+ // track or artwork is loaded. Display data from a library the user cannot access is never read.
+ Dictionary libraryAccess = [];
+ foreach (Guid libraryId in aggregates.Select(aggregate => aggregate.LibraryId).Distinct())
+ libraryAccess[libraryId] = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
+
+ List accessibleTrackIds = [.. aggregates
+ .Where(aggregate => libraryAccess[aggregate.LibraryId])
+ .Select(aggregate => aggregate.TrackId)
+ .Distinct()];
+ Dictionary tracks = [];
+ if (accessibleTrackIds.Count > 0)
+ {
+ Result> getTracksResult = await _unitOfWork.TrackRepository.GetByIdsAsync(accessibleTrackIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false);
+ if (getTracksResult.IsFailure)
+ return getTracksResult.Errors;
+ tracks = getTracksResult.Value.ToDictionary(track => track.Id);
+ }
+
+ List albumIds = [.. tracks.Values.Select(track => track.AlbumId).Distinct()];
+ Dictionary albumCovers = [];
+ if (albumIds.Count > 0)
+ {
+ Result> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnersAsync(MusicArtworkOwnerType.Album, albumIds, cancellationToken).ConfigureAwait(false);
+ if (getArtworkResult.IsFailure)
+ return getArtworkResult.Errors;
+ albumCovers = getArtworkResult.Value
+ .Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
+ .GroupBy(artwork => artwork.OwnerId)
+ .ToDictionary(
+ group => group.Key,
+ group => group.OrderBy(artwork => artwork.Ordinal).Select(artwork => artwork.FileName).FirstOrDefault());
+ }
+
+ List playedTracks = [];
+ foreach (PlayedTrackAggregate aggregate in aggregates)
+ {
+ if (libraryAccess[aggregate.LibraryId] && tracks.TryGetValue(aggregate.TrackId, out TrackEntity? foundTrack) && foundTrack.LibraryId == aggregate.LibraryId)
+ playedTracks.Add(new PlayedTrackDto(
+ aggregate.TrackId,
+ aggregate.LibraryId,
+ aggregate.AlbumId,
+ aggregate.ArtistId,
+ foundTrack.Title,
+ foundTrack.Album?.Title,
+ foundTrack.Album?.Artist?.Name,
+ albumCovers.TryGetValue(foundTrack.AlbumId, out string? coverFileName) ? coverFileName : null,
+ aggregate.LastActivityOnUtc,
+ aggregate.PlayCount,
+ aggregate.CompletedPlayCount,
+ aggregate.ListenedDurationMilliseconds));
+ else // Keep the row so the play counts stay accurate, but blank the display data of a missing or inaccessible track.
+ playedTracks.Add(new PlayedTrackDto(
+ aggregate.TrackId,
+ aggregate.LibraryId,
+ aggregate.AlbumId,
+ aggregate.ArtistId,
+ null,
+ null,
+ null,
+ null,
+ aggregate.LastActivityOnUtc,
+ aggregate.PlayCount,
+ aggregate.CompletedPlayCount,
+ aggregate.ListenedDurationMilliseconds));
+ }
+ return playedTracks;
+ }
+
+ ///
+ /// The aggregated counted plays of one track in one library.
+ ///
+ /// 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 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 milliseconds.
+ private sealed record PlayedTrackAggregate(
+ Guid TrackId,
+ Guid LibraryId,
+ Guid AlbumId,
+ Guid ArtistId,
+ DateTime LastActivityOnUtc,
+ int PlayCount,
+ int CompletedPlayCount,
+ long ListenedDurationMilliseconds
+ );
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetMusicPlayStatistics/GetMusicPlayStatisticsQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetMusicPlayStatistics/GetMusicPlayStatisticsQuery.cs
new file mode 100644
index 00000000..d5e6f1b5
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetMusicPlayStatistics/GetMusicPlayStatisticsQuery.cs
@@ -0,0 +1,12 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetMusicPlayStatistics;
+
+///
+/// Query for getting the listening statistics of the current user.
+///
+[DebuggerDisplay("Music play statistics")]
+public record GetMusicPlayStatisticsQuery() : IQuery;
diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetMusicPlayStatistics/GetMusicPlayStatisticsQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetMusicPlayStatistics/GetMusicPlayStatisticsQueryHandler.cs
new file mode 100644
index 00000000..dc27a4e9
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetMusicPlayStatistics/GetMusicPlayStatisticsQueryHandler.cs
@@ -0,0 +1,79 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Application.Common.Utilities;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
+using Lumina.Domain.SharedKernel.Common.Enums.Playback;
+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.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetMusicPlayStatistics;
+
+///
+/// Handler for the query to get the listening statistics of the current user.
+///
+public class GetMusicPlayStatisticsQueryHandler : IQueryHandler>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+
+ ///
+ /// 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.
+ public GetMusicPlayStatisticsQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ }
+
+ ///
+ /// Handles the query to get the listening statistics of the current user.
+ ///
+ /// The query to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the listening statistics of the current user, or an error message.
+ ///
+ public async Task> HandleAsync(GetMusicPlayStatisticsQuery query, CancellationToken cancellationToken)
+ {
+ // 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;
+
+ Result> getRecordsResult = await _unitOfWork.MusicPlayRecordRepository.GetForUserAsync(userId, cancellationToken).ConfigureAwait(false);
+ if (getRecordsResult.IsFailure)
+ return getRecordsResult.Errors;
+
+ IReadOnlyList records = getRecordsResult.Value;
+ // The total listening time includes the listened duration of every recorded play, including the plays that do not count.
+ long totalListeningDurationMilliseconds = records.Sum(record => record.ListenedDurationMilliseconds);
+ // A play counts when it completed or when it reached the threshold. An in-progress play that already reached the threshold is counted,
+ // so the counted total need not equal the completed and stopped plays together.
+ int totalPlayCount = records.Count(record => MusicPlayRecord.DoesCountAsPlay(record.Status, record.ListenedDurationMilliseconds.ToClampedTimeSpan()));
+ int completedPlayCount = records.Count(record => record.Status == PlaybackRecordStatus.Completed);
+ int stoppedPlayCount = records.Count(record => record.Status == PlaybackRecordStatus.Stopped && MusicPlayRecord.DoesCountAsPlay(record.Status, record.ListenedDurationMilliseconds.ToClampedTimeSpan()));
+ double completionRate = totalPlayCount == 0 ? 0 : (double)completedPlayCount / totalPlayCount;
+
+ return new MusicPlayStatisticsDto(
+ totalListeningDurationMilliseconds,
+ totalPlayCount,
+ completedPlayCount,
+ stoppedPlayCount,
+ completionRate).ToResponse();
+ }
+}
diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetRecentlyPlayed/GetRecentlyPlayedQuery.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetRecentlyPlayed/GetRecentlyPlayedQuery.cs
new file mode 100644
index 00000000..79ce53ae
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetRecentlyPlayed/GetRecentlyPlayedQuery.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DTO.Pagination;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetRecentlyPlayed;
+
+///
+/// Query for getting the recently played tracks of the current user, from the most recently played.
+///
+/// The object containing the requested pagination data, or to return every matching track.
+[DebuggerDisplay("PaginationData: {PaginationData}")]
+public record GetRecentlyPlayedQuery(
+ PaginationDataDto? PaginationData
+) : IQuery;
diff --git a/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetRecentlyPlayed/GetRecentlyPlayedQueryHandler.cs b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetRecentlyPlayed/GetRecentlyPlayedQueryHandler.cs
new file mode 100644
index 00000000..c71a3a2b
--- /dev/null
+++ b/src/Lumina.Application/Core/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/Queries/GetRecentlyPlayed/GetRecentlyPlayedQueryHandler.cs
@@ -0,0 +1,254 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.DataAccess.Entities.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Application.Common.DataAccess.UoW;
+using Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Application.Common.DTO.Pagination;
+using Lumina.Application.Common.Infrastructure.Authentication;
+using Lumina.Application.Common.Infrastructure.Authorization;
+using Lumina.Application.Common.Infrastructure.Authorization.Policies.LibraryOwnership;
+using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Application.Common.Utilities;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.MusicPlayRecordAggregate;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.Playback;
+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.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetRecentlyPlayed;
+
+///
+/// Handler for the query to get the recently played tracks of the current user.
+///
+public class GetRecentlyPlayedQueryHandler : IQueryHandler>>
+{
+ private readonly IUnitOfWork _unitOfWork;
+ private readonly ICurrentUserService _currentUserService;
+ private readonly IAuthorizationService _authorizationService;
+
+ ///
+ /// 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.
+ public GetRecentlyPlayedQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IAuthorizationService authorizationService)
+ {
+ _unitOfWork = unitOfWork;
+ _currentUserService = currentUserService;
+ _authorizationService = authorizationService;
+ }
+
+ ///
+ /// Handles the query to get the recently played tracks of the current user.
+ ///
+ /// The query to be handled.
+ /// Cancellation token that can be used to stop the execution.
+ ///
+ /// An containing either the requested page of recently played tracks, or an error message.
+ ///
+ public async Task>> HandleAsync(GetRecentlyPlayedQuery query, CancellationToken cancellationToken)
+ {
+ // 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;
+
+ Result> getRecordsResult = await _unitOfWork.MusicPlayRecordRepository.GetForUserAsync(userId, cancellationToken).ConfigureAwait(false);
+ if (getRecordsResult.IsFailure)
+ return getRecordsResult.Errors;
+
+ // Only the plays that count as plays are aggregated. The last activity of a track is the end of its most recent play, or the last
+ // progress update while that play is still in progress.
+ List aggregates = [.. getRecordsResult.Value
+ .Where(record => MusicPlayRecord.DoesCountAsPlay(record.Status, record.ListenedDurationMilliseconds.ToClampedTimeSpan()))
+ .GroupBy(record => new { record.TrackId, record.LibraryId, record.AlbumId, record.ArtistId })
+ .Select(group => new PlayedTrackAggregate(
+ group.Key.TrackId,
+ group.Key.LibraryId,
+ group.Key.AlbumId,
+ group.Key.ArtistId,
+ group.Max(record => record.EndedOnUtc ?? record.UpdatedOnUtc ?? record.CreatedOnUtc),
+ group.Count(),
+ group.Count(record => record.Status == PlaybackRecordStatus.Completed),
+ group.Sum(record => record.ListenedDurationMilliseconds)))
+ .OrderByDescending(aggregate => aggregate.LastActivityOnUtc)
+ .ThenBy(aggregate => aggregate.TrackId)];
+
+ return await ToResponsePageAsync(aggregates, query.PaginationData, userId, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Pages the aggregated tracks, resolves their display data, and converts them to the response of the query.
+ ///
+ /// The aggregated tracks, already ordered for this query.
+ /// The requested pagination data, or for every matching track.
+ /// The Id of the user whose tracks are retrieved.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the requested page of played tracks, or an error.
+ private async Task>> ToResponsePageAsync(
+ List aggregates, PaginationDataDto? paginationData, Guid userId, CancellationToken cancellationToken)
+ {
+ PaginatedResultDto page = Paginate(aggregates, paginationData);
+ Result> getDtosResult = await ToPlayedTrackDtosAsync(page.Data, userId, cancellationToken).ConfigureAwait(false);
+ if (getDtosResult.IsFailure)
+ return getDtosResult.Errors;
+
+ return Result.From(new PaginatedResultDto
+ {
+ Data = getDtosResult.Value,
+ CurrentPage = page.CurrentPage,
+ PerPage = page.PerPage,
+ Count = page.Count,
+ NumberOfPages = page.NumberOfPages
+ }.ToResponses());
+ }
+
+ ///
+ /// Applies the requested pagination to the ordered aggregated tracks.
+ ///
+ /// The ordered aggregated tracks.
+ /// The requested pagination data, or for every matching track.
+ /// The requested page of aggregated tracks.
+ private static PaginatedResultDto Paginate(List aggregates, PaginationDataDto? paginationData)
+ {
+ if (paginationData is null)
+ return new PaginatedResultDto
+ {
+ Data = aggregates,
+ CurrentPage = 1,
+ PerPage = aggregates.Count,
+ Count = aggregates.Count,
+ NumberOfPages = 1
+ };
+
+ int count = aggregates.Count;
+ int numberOfPages = (int)Math.Ceiling((double)count / paginationData.PerPage);
+ int currentPage = Math.Min(paginationData.CurrentPage, Math.Max(1, numberOfPages));
+ List page = [.. aggregates
+ .Skip((currentPage - 1) * paginationData.PerPage)
+ .Take(paginationData.PerPage)];
+ return new PaginatedResultDto
+ {
+ Data = page,
+ CurrentPage = currentPage,
+ PerPage = paginationData.PerPage,
+ Count = count,
+ NumberOfPages = numberOfPages
+ };
+ }
+
+ ///
+ /// Resolves the display data of the tracks of for the libraries the user can access, and builds their DTOs.
+ ///
+ /// The aggregated tracks of the requested page.
+ /// The Id of the user whose tracks are retrieved.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the played tracks, with blank display data for missing or inaccessible tracks, or an error.
+ private async Task>> ToPlayedTrackDtosAsync(IReadOnlyList aggregates, Guid userId, CancellationToken cancellationToken)
+ {
+ if (aggregates.Count == 0)
+ return new List();
+
+ // The access decision only needs the library Id that the play record already carries, so it is made once per distinct library before any
+ // track or artwork is loaded. Display data from a library the user cannot access is never read.
+ Dictionary libraryAccess = [];
+ foreach (Guid libraryId in aggregates.Select(aggregate => aggregate.LibraryId).Distinct())
+ libraryAccess[libraryId] = await _authorizationService.EvaluatePolicyAsync(
+ userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
+
+ List accessibleTrackIds = [.. aggregates
+ .Where(aggregate => libraryAccess[aggregate.LibraryId])
+ .Select(aggregate => aggregate.TrackId)
+ .Distinct()];
+ Dictionary tracks = [];
+ if (accessibleTrackIds.Count > 0)
+ {
+ Result> getTracksResult = await _unitOfWork.TrackRepository.GetByIdsAsync(accessibleTrackIds, shouldIncludeNavigationProperties: true, cancellationToken).ConfigureAwait(false);
+ if (getTracksResult.IsFailure)
+ return getTracksResult.Errors;
+ tracks = getTracksResult.Value.ToDictionary(track => track.Id);
+ }
+
+ List albumIds = [.. tracks.Values.Select(track => track.AlbumId).Distinct()];
+ Dictionary albumCovers = [];
+ if (albumIds.Count > 0)
+ {
+ Result> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnersAsync(MusicArtworkOwnerType.Album, albumIds, cancellationToken).ConfigureAwait(false);
+ if (getArtworkResult.IsFailure)
+ return getArtworkResult.Errors;
+ albumCovers = getArtworkResult.Value
+ .Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
+ .GroupBy(artwork => artwork.OwnerId)
+ .ToDictionary(
+ group => group.Key,
+ group => group.OrderBy(artwork => artwork.Ordinal).Select(artwork => artwork.FileName).FirstOrDefault());
+ }
+
+ List playedTracks = [];
+ foreach (PlayedTrackAggregate aggregate in aggregates)
+ {
+ if (libraryAccess[aggregate.LibraryId] && tracks.TryGetValue(aggregate.TrackId, out TrackEntity? foundTrack) && foundTrack.LibraryId == aggregate.LibraryId)
+ playedTracks.Add(new PlayedTrackDto(
+ aggregate.TrackId,
+ aggregate.LibraryId,
+ aggregate.AlbumId,
+ aggregate.ArtistId,
+ foundTrack.Title,
+ foundTrack.Album?.Title,
+ foundTrack.Album?.Artist?.Name,
+ albumCovers.TryGetValue(foundTrack.AlbumId, out string? coverFileName) ? coverFileName : null,
+ aggregate.LastActivityOnUtc,
+ aggregate.PlayCount,
+ aggregate.CompletedPlayCount,
+ aggregate.ListenedDurationMilliseconds));
+ else // Keep the row so the play counts stay accurate, but blank the display data of a missing or inaccessible track.
+ playedTracks.Add(new PlayedTrackDto(
+ aggregate.TrackId,
+ aggregate.LibraryId,
+ aggregate.AlbumId,
+ aggregate.ArtistId,
+ null,
+ null,
+ null,
+ null,
+ aggregate.LastActivityOnUtc,
+ aggregate.PlayCount,
+ aggregate.CompletedPlayCount,
+ aggregate.ListenedDurationMilliseconds));
+ }
+ return playedTracks;
+ }
+
+ ///
+ /// The aggregated counted plays of one track in one library.
+ ///
+ /// 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 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 milliseconds.
+ private sealed record PlayedTrackAggregate(
+ Guid TrackId,
+ Guid LibraryId,
+ Guid AlbumId,
+ Guid ArtistId,
+ DateTime LastActivityOnUtc,
+ int PlayCount,
+ int CompletedPlayCount,
+ long ListenedDurationMilliseconds
+ );
+}
diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayedRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayedRequest.cs
new file mode 100644
index 00000000..7c8effb6
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayedRequest.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+
+///
+/// Represents a request for getting a window of the most played tracks of the current user.
+///
+/// The one based page of tracks to return. Optional; defaults to 1 when a page size is provided.
+/// The number of tracks per page. Optional; defaults to 50 when a page is provided. When both pagination parameters are omitted, every matching track is returned.
+[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
+public record GetMostPlayedRequest(
+ int? CurrentPage,
+ int? PerPage
+);
diff --git a/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayedRequest.cs b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayedRequest.cs
new file mode 100644
index 00000000..c1945e47
--- /dev/null
+++ b/src/Lumina.Contracts/Requests/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayedRequest.cs
@@ -0,0 +1,16 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+
+///
+/// Represents a request for getting a window of the recently played tracks of the current user.
+///
+/// The one based page of tracks to return. Optional; defaults to 1 when a page size is provided.
+/// The number of tracks per page. Optional; defaults to 50 when a page is provided. When both pagination parameters are omitted, every matching track is returned.
+[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
+public record GetRecentlyPlayedRequest(
+ int? CurrentPage,
+ int? PerPage
+);
diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayStatisticsResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayStatisticsResponse.cs
new file mode 100644
index 00000000..3b11212e
--- /dev/null
+++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayStatisticsResponse.cs
@@ -0,0 +1,22 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+
+///
+/// Represents 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 MusicPlayStatisticsResponse(
+ double TotalListeningDurationInSeconds,
+ int TotalPlayCount,
+ int CompletedPlayCount,
+ int StoppedPlayCount,
+ double CompletionRate
+);
diff --git a/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/PlayedTrackResponse.cs b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/PlayedTrackResponse.cs
new file mode 100644
index 00000000..6de92848
--- /dev/null
+++ b/src/Lumina.Contracts/Responses/MediaLibrary/AudioLibrary/MusicLibrary/PlayHistory/PlayedTrackResponse.cs
@@ -0,0 +1,37 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+
+///
+/// Represents 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 PlayedTrackResponse(
+ 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.DataAccess/Core/Repositories/MusicLibrary/MusicPlayRecordRepository.cs b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicPlayRecordRepository.cs
index e982f70b..7b98192e 100644
--- a/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicPlayRecordRepository.cs
+++ b/src/Lumina.DataAccess/Core/Repositories/MusicLibrary/MusicPlayRecordRepository.cs
@@ -6,6 +6,7 @@ using Lumina.DataAccess.Core.UoW;
using Lumina.Domain.Common.Primitives;
using Microsoft.EntityFrameworkCore;
using System;
+using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -52,6 +53,22 @@ internal sealed class MusicPlayRecordRepository : IMusicPlayRecordRepository
return await query.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false);
}
+ ///
+ /// Gets the play records of the user identified by .
+ ///
+ /// The Id of the user whose play records are retrieved.
+ /// Cancellation token that can be used to stop the execution.
+ /// An containing either the play records of the user, or an error.
+ public async Task>> GetForUserAsync(Guid userId, CancellationToken cancellationToken)
+ {
+ // The user is part of the query, so the storage medium never returns the plays of another user.
+ List playRecords = await _luminaDbContext.MusicPlayRecords
+ .AsNoTracking()
+ .Where(playRecord => playRecord.UserId == userId)
+ .ToListAsync(cancellationToken).ConfigureAwait(false);
+ return Result.From>(playRecords);
+ }
+
///
/// Adds a new play record.
///
diff --git a/src/Lumina.Domain/Core/BoundedContexts/MusicPlayHistoryBoundedContext/MusicPlayRecordAggregate/MusicPlayRecord.cs b/src/Lumina.Domain/Core/BoundedContexts/MusicPlayHistoryBoundedContext/MusicPlayRecordAggregate/MusicPlayRecord.cs
index e7c57da8..145f83de 100644
--- a/src/Lumina.Domain/Core/BoundedContexts/MusicPlayHistoryBoundedContext/MusicPlayRecordAggregate/MusicPlayRecord.cs
+++ b/src/Lumina.Domain/Core/BoundedContexts/MusicPlayHistoryBoundedContext/MusicPlayRecordAggregate/MusicPlayRecord.cs
@@ -25,6 +25,11 @@ namespace Lumina.Domain.Core.BoundedContexts.MusicPlayHistoryBoundedContext.Musi
[DebuggerDisplay("Id: {Id.Value}; TrackId: {TrackId.Value}; Status: {Status}")]
public sealed class MusicPlayRecord : AggregateRoot
{
+ ///
+ /// The minimum number of seconds a user must listen to a track for the play to count, unless the play completed first.
+ ///
+ private const int MINIMUM_COUNTED_LISTENED_DURATION_SECONDS = 30;
+
///
/// Gets the object representing the unique identifier of the user that started the play.
///
@@ -208,6 +213,17 @@ public sealed class MusicPlayRecord : AggregateRoot
updatedOnUtc);
}
+ ///
+ /// Determines whether a play with the provided and counts as a play for the listening statistics.
+ ///
+ /// The state of the recorded play.
+ /// The duration that the user has listened to.
+ /// when the play counts, otherwise.
+ public static bool DoesCountAsPlay(PlaybackRecordStatus status, TimeSpan listenedDuration)
+ {
+ return status == PlaybackRecordStatus.Completed || listenedDuration.TotalSeconds >= MINIMUM_COUNTED_LISTENED_DURATION_SECONDS;
+ }
+
///
/// Updates the last reported position and the listened duration of an in-progress play.
///
diff --git a/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.PlayStatistics.cs b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.PlayStatistics.cs
new file mode 100644
index 00000000..5c398ae8
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Common/Routes/Library/AudioLibrary/MusicLibrary/ApiRoutes.PlayStatistics.cs
@@ -0,0 +1,17 @@
+namespace Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
+
+///
+/// Class for the collection of the music play statistics routes of the API.
+///
+public static partial class ApiRoutes
+{
+ ///
+ /// Routes for the music play statistics of the current user.
+ ///
+ 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.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayed/GetMostPlayedEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayed/GetMostPlayedEndpoint.cs
new file mode 100644
index 00000000..a85c56e3
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayed/GetMostPlayedEndpoint.cs
@@ -0,0 +1,63 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetMostPlayed;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
+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.AudioLibrary.MusicLibrary.PlayHistory.GetMostPlayed;
+
+///
+/// API endpoint for the /users/me/music-play-history/most-played route.
+///
+///
+/// Uses "me" because it is always for the currently authenticated user.
+///
+public class GetMostPlayedEndpoint : BaseEndpoint
+{
+ private readonly IQueryHandler>> _getMostPlayedQueryHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling get most played queries.
+ public GetMostPlayedEndpoint(IQueryHandler>> getMostPlayedQueryHandler)
+ {
+ _getMostPlayedQueryHandler = getMostPlayedQueryHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(Http.GET);
+ Routes(ApiRoutes.PlayStatistics.GET_MOST_PLAYED);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Gets the most played tracks of the current user.
+ ///
+ /// The request containing the optional page bounds.
+ /// 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 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["Vary"] = "Authorization";
+ Result> result = await _getMostPlayedQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayed/GetMostPlayedEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayed/GetMostPlayedEndpointSummary.cs
new file mode 100644
index 00000000..2e44e5c6
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayed/GetMostPlayedEndpointSummary.cs
@@ -0,0 +1,116 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using System;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.GetMostPlayed;
+
+///
+/// Class used for providing a textual description for the API 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 = "Gets the tracks the current user played the most, from the most played. Only the plays that count as plays are included: a play counts when it completed or when the listened duration reached 30 seconds. Each track is returned once, with its counted plays, its completed plays, the duration the user listened to it and its last activity time. A track deleted from its library keeps its row, without display data. The response is private to the authenticated user.";
+
+ ExampleRequest = new GetMostPlayedRequest(CurrentPage: 1, PerPage: 50);
+ 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 50. When both pagination parameters are omitted, every matching track is returned.");
+
+ 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 PaginatedResponse
+ {
+ Data =
+ [
+ new PlayedTrackResponse(
+ 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 = 50,
+ Count = 1,
+ NumberOfPages = 1
+ }
+ );
+
+ 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/music-play-history/most-played"
+ },
+ 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/music-play-history/most-played"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token is invalid",
+ instance = "/api/v1/users/me/music-play-history/most-played"
+ }
+ }
+ );
+
+ 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/music-play-history/most-played",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMusicPlayStatistics/GetMusicPlayStatisticsEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMusicPlayStatistics/GetMusicPlayStatisticsEndpoint.cs
new file mode 100644
index 00000000..c0b1a37f
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMusicPlayStatistics/GetMusicPlayStatisticsEndpoint.cs
@@ -0,0 +1,60 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetMusicPlayStatistics;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
+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.AudioLibrary.MusicLibrary.PlayHistory.GetMusicPlayStatistics;
+
+///
+/// API endpoint for the /users/me/music-play-history/statistics route.
+///
+///
+/// Uses "me" because it is always for the currently authenticated user.
+///
+public class GetMusicPlayStatisticsEndpoint : BaseEndpoint
+{
+ private readonly IQueryHandler> _getMusicPlayStatisticsQueryHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling get music play statistics queries.
+ public GetMusicPlayStatisticsEndpoint(IQueryHandler> getMusicPlayStatisticsQueryHandler)
+ {
+ _getMusicPlayStatisticsQueryHandler = getMusicPlayStatisticsQueryHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(Http.GET);
+ Routes(ApiRoutes.PlayStatistics.GET_MUSIC_PLAY_STATISTICS);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Gets the listening statistics of the current user.
+ ///
+ /// 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 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["Vary"] = "Authorization";
+ Result result = await _getMusicPlayStatisticsQueryHandler.HandleAsync(new GetMusicPlayStatisticsQuery(), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMusicPlayStatistics/GetMusicPlayStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMusicPlayStatistics/GetMusicPlayStatisticsEndpointSummary.cs
new file mode 100644
index 00000000..be947cdb
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMusicPlayStatistics/GetMusicPlayStatisticsEndpointSummary.cs
@@ -0,0 +1,80 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.GetMusicPlayStatistics;
+
+///
+/// Class used for providing a textual description for the API 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 = "Gets the total listening time, the number of plays that count as plays, the number of completed plays, the number of stopped plays that count and the completion rate of the current user. A play counts when it completed or when the listened duration reached 30 seconds, and the total listening time includes the listened duration of every recorded play. 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. The statistics are aggregated over the plays of the authenticated user, so the response is private to that user.";
+
+ 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 MusicPlayStatisticsResponse(
+ TotalListeningDurationInSeconds: 93840.5,
+ TotalPlayCount: 512,
+ CompletedPlayCount: 388,
+ StoppedPlayCount: 124,
+ CompletionRate: 0.7578125)
+ );
+
+ 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/music-play-history/statistics"
+ },
+ 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/music-play-history/statistics"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token is invalid",
+ instance = "/api/v1/users/me/music-play-history/statistics"
+ }
+ }
+ );
+
+ 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/music-play-history/statistics",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayed/GetRecentlyPlayedEndpoint.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayed/GetRecentlyPlayedEndpoint.cs
new file mode 100644
index 00000000..d4494435
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayed/GetRecentlyPlayedEndpoint.cs
@@ -0,0 +1,63 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Application.Common.CQRS;
+using Lumina.Application.Common.Mapping.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Application.Core.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory.Queries.GetRecentlyPlayed;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Domain.Common.Primitives;
+using Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
+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.AudioLibrary.MusicLibrary.PlayHistory.GetRecentlyPlayed;
+
+///
+/// API endpoint for the /users/me/music-play-history/recently-played route.
+///
+///
+/// Uses "me" because it is always for the currently authenticated user.
+///
+public class GetRecentlyPlayedEndpoint : BaseEndpoint
+{
+ private readonly IQueryHandler>> _getRecentlyPlayedQueryHandler;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for handling get recently played queries.
+ public GetRecentlyPlayedEndpoint(IQueryHandler>> getRecentlyPlayedQueryHandler)
+ {
+ _getRecentlyPlayedQueryHandler = getRecentlyPlayedQueryHandler;
+ }
+
+ ///
+ /// Configures the API endpoint.
+ ///
+ public override void Configure()
+ {
+ Verbs(Http.GET);
+ Routes(ApiRoutes.PlayStatistics.GET_RECENTLY_PLAYED);
+ Version(1);
+ DontCatchExceptions();
+ }
+
+ ///
+ /// Gets the recently played tracks of the current user.
+ ///
+ /// The request containing the optional page bounds.
+ /// 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 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["Vary"] = "Authorization";
+ Result> result = await _getRecentlyPlayedQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
+ return result.Match(success => TypedResults.Ok(success), Problem);
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayed/GetRecentlyPlayedEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayed/GetRecentlyPlayedEndpointSummary.cs
new file mode 100644
index 00000000..c335be2e
--- /dev/null
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayed/GetRecentlyPlayedEndpointSummary.cs
@@ -0,0 +1,116 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Contracts.Responses.Common;
+using Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
+using System;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Api.Core.Endpoints.Library.AudioLibrary.MusicLibrary.PlayHistory.GetRecentlyPlayed;
+
+///
+/// Class used for providing a textual description for the API 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 = "Gets the tracks the current user played recently, from the most recently played. Only the plays that count as plays are included: a play counts when it completed or when the listened duration reached 30 seconds. Each track is returned once, with its last activity time, its counted plays, its completed plays and the duration the user listened to it. A track deleted from its library keeps its row, without display data. The response is private to the authenticated user.";
+
+ ExampleRequest = new GetRecentlyPlayedRequest(CurrentPage: 1, PerPage: 50);
+ 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 50. When both pagination parameters are omitted, every matching track is returned.");
+
+ 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 PaginatedResponse
+ {
+ Data =
+ [
+ new PlayedTrackResponse(
+ 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 = 50,
+ Count = 1,
+ NumberOfPages = 1
+ }
+ );
+
+ 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/music-play-history/recently-played"
+ },
+ 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/music-play-history/recently-played"
+ },
+ new
+ {
+ type = "https://tools.ietf.org/html/rfc7235#section-3.1",
+ status = 401,
+ title = "Unauthorized",
+ detail = "The token is invalid",
+ instance = "/api/v1/users/me/music-play-history/recently-played"
+ }
+ }
+ );
+
+ 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/music-play-history/recently-played",
+ traceId = "00-a712bbf99ca8ab485f86a762ae5ae74d-b3a2eb78813b0a5d-00"
+ }
+ );
+ }
+}
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs
index e080174a..66586588 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetAllUsersConsumptionStatistics/GetAllUsersConsumptionStatisticsEndpointSummary.cs
@@ -44,6 +44,19 @@ public class GetAllUsersConsumptionStatisticsEndpointSummary : Summary(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.");
+ 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.");
Response(statusCode: 200, description: "The consumption statistics of every user are returned.", contentType: "application/json",
example: new AllUsersConsumptionStatisticsResponse(
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs
index 18bb140c..cb64c0ee 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetConsumptionStatisticsEndpointSummary.cs
@@ -42,7 +42,13 @@ public class GetConsumptionStatisticsEndpointSummary : Summary(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. Each entry carries the media kind, the consumed duration, the counted, completed and stopped session counts, and the completion rate of that kind.");
+ 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.");
Response(statusCode: 200, description: "The consumption statistics of the current user are returned.", contentType: "application/json",
example: new ConsumptionSummaryResponse(
diff --git a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointSummary.cs b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointSummary.cs
index 0afceca6..7d41eff3 100644
--- a/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointSummary.cs
+++ b/src/Lumina.Presentation.Api/Core/Endpoints/Library/Statistics/GetConsumptionStatistics/GetUserConsumptionStatisticsEndpointSummary.cs
@@ -43,7 +43,13 @@ public class GetUserConsumptionStatisticsEndpointSummary : Summary(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. Each entry carries the media kind, the consumed duration, the counted, completed and stopped session counts, and the completion rate of that kind.");
+ 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.");
Response(statusCode: 200, description: "The consumption statistics of the user are returned.", contentType: "application/json",
example: new ConsumptionSummaryResponse(
diff --git a/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayStatisticsDto.cs b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayStatisticsDto.cs
new file mode 100644
index 00000000..4cef0fee
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlayHistory/MusicPlayStatisticsDto.cs
@@ -0,0 +1,22 @@
+#region ========================================================================= USING =====================================================================================
+using System.Diagnostics;
+#endregion
+
+namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary.PlayHistory;
+
+///
+/// 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
new file mode 100644
index 00000000..36ed80a0
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/DTO/AudioLibrary/MusicLibrary/PlayHistory/PlayedTrackDto.cs
@@ -0,0 +1,37 @@
+#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/Requests/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayedRequest.cs b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayedRequest.cs
new file mode 100644
index 00000000..4dc4add5
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/PlayHistory/GetMostPlayedRequest.cs
@@ -0,0 +1,16 @@
+#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
new file mode 100644
index 00000000..5a5c0244
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Requests/Library/AudioLibrary/MusicLibrary/PlayHistory/GetRecentlyPlayedRequest.cs
@@ -0,0 +1,16 @@
+#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/Routes/ApiRoutes.PlayStatistics.cs b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.PlayStatistics.cs
new file mode 100644
index 00000000..744299fd
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Routes/ApiRoutes.PlayStatistics.cs
@@ -0,0 +1,17 @@
+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
new file mode 100644
index 00000000..e0099360
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Common/Routes/WebRoutes.LibraryStatistics.cs
@@ -0,0 +1,18 @@
+namespace Lumina.Presentation.Web.Common.Routes;
+
+///
+/// Class for the collection of routes defined in the Web application.
+///
+public static partial class WebRoutes
+{
+ ///
+ /// Routes for the library statistics pages.
+ ///
+ 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";
+ }
+}
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
new file mode 100644
index 00000000..d4e01ba9
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostPlayed/GetMostPlayedEndpoint.cs
@@ -0,0 +1,64 @@
+#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
new file mode 100644
index 00000000..84184375
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMostPlayed/GetMostPlayedEndpointSummary.cs
@@ -0,0 +1,73 @@
+#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/GetMusicPlayStatisticsEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMusicPlayStatistics/GetMusicPlayStatisticsEndpoint.cs
new file mode 100644
index 00000000..8dcec382
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMusicPlayStatistics/GetMusicPlayStatisticsEndpoint.cs
@@ -0,0 +1,55 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.Api;
+using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary.PlayHistory;
+using Lumina.Presentation.Web.Common.Routes;
+using Lumina.Presentation.Web.Core.Endpoints.Common;
+using Microsoft.AspNetCore.Http;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.GetMusicPlayStatistics;
+
+///
+/// API endpoint for the /{culture}/library/statistics/api-get-music-play-statistics route.
+///
+public class GetMusicPlayStatisticsEndpoint : BaseEndpoint
+{
+ private readonly IApiHttpClient _apiHttpClient;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Injected service for interactions with the API.
+ public GetMusicPlayStatisticsEndpoint(IApiHttpClient apiHttpClient)
+ {
+ _apiHttpClient = apiHttpClient;
+ }
+
+ ///
+ /// Configures the endpoint.
+ ///
+ public override void Configure()
+ {
+ base.Configure();
+ Verbs(Http.GET);
+ Routes(WebRoutes.LibraryStatistics.GET_MUSIC_PLAY_STATISTICS);
+ DontAutoTag();
+ Options(options => options.WithTags("Statistics"));
+ }
+
+ ///
+ /// Retrieves the listening statistics of the current user.
+ ///
+ /// 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.
+ 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);
+ }
+}
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
new file mode 100644
index 00000000..17b9f695
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetMusicPlayStatistics/GetMusicPlayStatisticsEndpointSummary.cs
@@ -0,0 +1,40 @@
+#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/GetRecentlyPlayed/GetRecentlyPlayedEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyPlayed/GetRecentlyPlayedEndpoint.cs
new file mode 100644
index 00000000..955b3873
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyPlayed/GetRecentlyPlayedEndpoint.cs
@@ -0,0 +1,64 @@
+#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
new file mode 100644
index 00000000..31996a35
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/GetRecentlyPlayed/GetRecentlyPlayedEndpointSummary.cs
@@ -0,0 +1,73 @@
+#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/Index/StatisticsIndexViewEndpoint.cs b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpoint.cs
new file mode 100644
index 00000000..a0199b22
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpoint.cs
@@ -0,0 +1,95 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using Lumina.Presentation.Web.Common.DTO.Themes;
+using Lumina.Presentation.Web.Common.Primitives;
+using Lumina.Presentation.Web.Common.Routes;
+using Lumina.Presentation.Web.Common.Services;
+using Lumina.Presentation.Web.Core.Endpoints.Common;
+using Lumina.Presentation.Web.Core.Themes;
+using Microsoft.AspNetCore.Http;
+using Microsoft.Extensions.Localization;
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.Index;
+
+///
+/// API endpoint for the /{culture}/library/statistics route.
+///
+public class StatisticsIndexViewEndpoint : BaseEndpoint
+{
+ // The resource base name deliberately excludes the "Core.Resources" segment: the localization factory re-roots it with the configured ResourcesPath.
+ private const string VIEW_RESOURCE_BASE_NAME = "Lumina.Presentation.Web.Views.Library.Statistics.Index";
+ private const string VIEW_RESOURCE_LOCATION = "Lumina.Presentation.Web";
+ // The page key mirrors the path of the Razor view under Core/Views, so that theme templates can override it at the page, section or default scope.
+ private const string VIEW_PAGE_KEY = "library/statistics/index";
+
+ private readonly IUrlService _urlService;
+ private readonly ThemePageRenderer _themePageRenderer;
+ private readonly IStringLocalizer _localizer;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// 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)
+ {
+ _urlService = urlService;
+ _themePageRenderer = themePageRenderer;
+ _localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION);
+ }
+
+ ///
+ /// Configures the endpoint.
+ ///
+ public override void Configure()
+ {
+ base.Configure();
+ Verbs(Http.GET);
+ Routes(WebRoutes.LibraryStatistics.INDEX);
+ DontAutoTag();
+ Options(options => options.WithTags("Statistics"));
+ }
+
+ ///
+ /// Displays the statistics of the current user, 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.
+ public override async Task ExecuteAsync(EmptyRequest request, CancellationToken cancellationToken)
+ {
+ // The page shows the statistics of the authenticated 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";
+ string title = _localizer["Title"].Value;
+
+ // 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,
+ Title = title,
+ 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,
+ ["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/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
new file mode 100644
index 00000000..be24f999
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Endpoints/Library/Statistics/Index/StatisticsIndexViewEndpointSummary.cs
@@ -0,0 +1,24 @@
+#region ========================================================================= USING =====================================================================================
+using FastEndpoints;
+using System.Diagnostics.CodeAnalysis;
+#endregion
+
+namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.Index;
+
+///
+/// Class used for providing a textual description for the endpoint, for OpenAPI.
+///
+[ExcludeFromCodeCoverage]
+public class StatisticsIndexViewEndpointSummary : Summary
+{
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ public StatisticsIndexViewEndpointSummary()
+ {
+ Summary = "Renders the statistics page.";
+ Description = "Renders the page that shows the statistics of the current user: the total listening time, the counted plays, the completed plays, the completion rate, and the recently played and most played tracks.";
+
+ Response(200, "The statistics page is rendered.");
+ }
+}
diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ar-SA.resx
new file mode 100644
index 00000000..669ecb52
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ar-SA.resx
@@ -0,0 +1,72 @@
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ الإحصائيات
+
+
+ إجمالي وقت الاستماع
+
+
+ مرات التشغيل
+
+
+ مرات التشغيل المكتملة
+
+
+ معدل الإكمال
+
+
+ شُغّل مؤخراً
+
+
+ الأكثر تشغيلاً
+
+
+ لا توجد مرات تشغيل محتسبة بعد.
+
+
+ هذا المقطع لم يعد متاحاً.
+
+
+ تعذر تحميل الإحصائيات.
+
+
+ إعادة المحاولة
+
+
+ مرات تشغيل
+
+
+ مكتملة
+
+
+ آخر تشغيل
+
+
+ تشغيل المقطع
+
+
+ إضافة إلى قائمة التشغيل
+
+
+ س
+
+
+ د
+
+
+ ث
+
+
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
new file mode 100644
index 00000000..000d7b76
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.de-DE.resx
@@ -0,0 +1,72 @@
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ Statistik
+
+
+ Gesamte Hörzeit
+
+
+ Wiedergaben
+
+
+ Abgeschlossene Wiedergaben
+
+
+ Abschlussrate
+
+
+ Zuletzt gehört
+
+
+ Meistgehört
+
+
+ Es gibt noch keine gezählten Wiedergaben.
+
+
+ Dieser Titel ist nicht mehr verfügbar.
+
+
+ Die Statistik konnte nicht geladen werden.
+
+
+ Wiederholen
+
+
+ Wiedergaben
+
+
+ abgeschlossen
+
+
+ Zuletzt gehört
+
+
+ Titel abspielen
+
+
+ Zu Wiedergabeliste hinzufügen
+
+
+ h
+
+
+ m
+
+
+ s
+
+
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
new file mode 100644
index 00000000..61fbbf25
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.en-US.resx
@@ -0,0 +1,72 @@
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ Statistics
+
+
+ Total listening time
+
+
+ Plays
+
+
+ Completed plays
+
+
+ Completion rate
+
+
+ Recently played
+
+
+ Most played
+
+
+ There are no counted plays yet.
+
+
+ This track is no longer available.
+
+
+ The statistics could not be loaded.
+
+
+ Retry
+
+
+ plays
+
+
+ completed
+
+
+ Last played
+
+
+ Play track
+
+
+ Add to playlist
+
+
+ h
+
+
+ m
+
+
+ s
+
+
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
new file mode 100644
index 00000000..e3620f3e
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.es-ES.resx
@@ -0,0 +1,72 @@
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ Estadísticas
+
+
+ Tiempo total de escucha
+
+
+ Reproducciones
+
+
+ Reproducciones completadas
+
+
+ Tasa de finalización
+
+
+ Reproducido recientemente
+
+
+ Más reproducido
+
+
+ Aún no hay reproducciones contabilizadas.
+
+
+ Esta pista ya no está disponible.
+
+
+ No se pudieron cargar las estadísticas.
+
+
+ Reintentar
+
+
+ reproducciones
+
+
+ completadas
+
+
+ Última reproducción
+
+
+ Reproducir pista
+
+
+ Añadir a la lista de reproducción
+
+
+ h
+
+
+ min
+
+
+ s
+
+
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
new file mode 100644
index 00000000..fc41adf6
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.fr-FR.resx
@@ -0,0 +1,72 @@
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ Statistiques
+
+
+ Temps d'écoute total
+
+
+ Écoutes
+
+
+ Écoutes terminées
+
+
+ Taux d'achèvement
+
+
+ Écoutés récemment
+
+
+ Les plus écoutés
+
+
+ Aucune écoute comptabilisée pour le moment.
+
+
+ Ce morceau n'est plus disponible.
+
+
+ Les statistiques n'ont pas pu être chargées.
+
+
+ Réessayer
+
+
+ écoutes
+
+
+ terminées
+
+
+ Dernière écoute
+
+
+ Lire le morceau
+
+
+ Ajouter à la playlist
+
+
+ h
+
+
+ min
+
+
+ s
+
+
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
new file mode 100644
index 00000000..e39347b3
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.it-IT.resx
@@ -0,0 +1,72 @@
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ Statistiche
+
+
+ Tempo di ascolto totale
+
+
+ Riproduzioni
+
+
+ Riproduzioni completate
+
+
+ Tasso di completamento
+
+
+ Riprodotti di recente
+
+
+ Più riprodotti
+
+
+ Non ci sono ancora riproduzioni conteggiate.
+
+
+ Questo brano non è più disponibile.
+
+
+ Impossibile caricare le statistiche.
+
+
+ Riprova
+
+
+ riproduzioni
+
+
+ completate
+
+
+ Ultima riproduzione
+
+
+ Riproduci brano
+
+
+ Aggiungi alla playlist
+
+
+ h
+
+
+ min
+
+
+ s
+
+
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
new file mode 100644
index 00000000..2ab3089d
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ja-JP.resx
@@ -0,0 +1,72 @@
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ 統計
+
+
+ 合計再生時間
+
+
+ 再生回数
+
+
+ 最後まで再生した回数
+
+
+ 完了率
+
+
+ 最近再生した曲
+
+
+ よく再生する曲
+
+
+ 集計対象の再生はまだありません。
+
+
+ この曲はもう利用できません。
+
+
+ 統計を読み込めませんでした。
+
+
+ 再試行
+
+
+ 回
+
+
+ 回完了
+
+
+ 最終再生
+
+
+ 曲を再生
+
+
+ プレイリストに追加
+
+
+ 時間
+
+
+ 分
+
+
+ 秒
+
+
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
new file mode 100644
index 00000000..61fbbf25
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.resx
@@ -0,0 +1,72 @@
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ Statistics
+
+
+ Total listening time
+
+
+ Plays
+
+
+ Completed plays
+
+
+ Completion rate
+
+
+ Recently played
+
+
+ Most played
+
+
+ There are no counted plays yet.
+
+
+ This track is no longer available.
+
+
+ The statistics could not be loaded.
+
+
+ Retry
+
+
+ plays
+
+
+ completed
+
+
+ Last played
+
+
+ Play track
+
+
+ Add to playlist
+
+
+ h
+
+
+ m
+
+
+ s
+
+
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
new file mode 100644
index 00000000..4fa6fe4b
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.ro-RO.resx
@@ -0,0 +1,72 @@
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ Statistici
+
+
+ Timp total de ascultare
+
+
+ Redări
+
+
+ Redări finalizate
+
+
+ Rată de finalizare
+
+
+ Ascultate recent
+
+
+ Cele mai ascultate
+
+
+ Nu există încă redări contorizate.
+
+
+ Această piesă nu mai este disponibilă.
+
+
+ Statisticile nu au putut fi încărcate.
+
+
+ Reîncearcă
+
+
+ redări
+
+
+ finalizate
+
+
+ Ultima redare
+
+
+ Redă piesa
+
+
+ Adaugă la playlist
+
+
+ h
+
+
+ min
+
+
+ s
+
+
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
new file mode 100644
index 00000000..566abeae
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.uk-UA.resx
@@ -0,0 +1,72 @@
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ Статистика
+
+
+ Загальний час прослуховування
+
+
+ Відтворення
+
+
+ Завершені відтворення
+
+
+ Відсоток завершення
+
+
+ Нещодавно відтворені
+
+
+ Найчастіше відтворювані
+
+
+ Ще немає зарахованих відтворень.
+
+
+ Цей трек більше недоступний.
+
+
+ Не вдалося завантажити статистику.
+
+
+ Повторити
+
+
+ відтворень
+
+
+ завершено
+
+
+ Останнє відтворення
+
+
+ Відтворити трек
+
+
+ Додати до плейлиста
+
+
+ год
+
+
+ хв
+
+
+ с
+
+
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
new file mode 100644
index 00000000..c3d0fdcc
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Library/Statistics/Index.zh-CN.resx
@@ -0,0 +1,72 @@
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ 统计
+
+
+ 总收听时间
+
+
+ 播放次数
+
+
+ 完整播放次数
+
+
+ 完成率
+
+
+ 最近播放
+
+
+ 最常播放
+
+
+ 还没有计入的播放。
+
+
+ 此曲目已不可用。
+
+
+ 无法加载统计。
+
+
+ 重试
+
+
+ 次播放
+
+
+ 次完整播放
+
+
+ 上次播放
+
+
+ 播放曲目
+
+
+ 添加到播放列表
+
+
+ 小时
+
+
+ 分钟
+
+
+ 秒
+
+
diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx
index 81c36666..21a6e6bc 100644
--- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ar-SA.resx
@@ -225,4 +225,7 @@
المفضلة
+
+ الإحصائيات
+
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx
index 6cdfb7f4..c2969e29 100644
--- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.de-DE.resx
@@ -225,4 +225,7 @@
Favoriten
+
+ Statistik
+
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx
index 810eb0e5..2d111347 100644
--- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.en-US.resx
@@ -225,4 +225,7 @@
Favorites
+
+ Statistics
+
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx
index 10beb8e4..5d867caa 100644
--- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.es-ES.resx
@@ -225,4 +225,7 @@
Favoritos
+
+ Estadísticas
+
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx
index 9bae909c..4b3ed8bb 100644
--- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.fr-FR.resx
@@ -225,4 +225,7 @@
Favoris
+
+ Statistiques
+
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx
index 5425e91b..1a1d7088 100644
--- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.it-IT.resx
@@ -225,4 +225,7 @@
Preferiti
+
+ Statistiche
+
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx
index 45b75ddc..5fd79cf5 100644
--- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ja-JP.resx
@@ -225,4 +225,7 @@
お気に入り
+
+ 統計
+
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx
index 810eb0e5..2d111347 100644
--- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.resx
@@ -225,4 +225,7 @@
Favorites
+
+ Statistics
+
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx
index 93a29ca1..2dc127f8 100644
--- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.ro-RO.resx
@@ -225,4 +225,7 @@
Favorite
+
+ Statistici
+
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.uk-UA.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.uk-UA.resx
index 5d49bea2..54ba03bd 100644
--- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.uk-UA.resx
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.uk-UA.resx
@@ -225,4 +225,7 @@
Улюблене
+
+ Статистика
+
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx
index 36e4b023..930087ea 100644
--- a/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx
+++ b/src/Lumina.Presentation.Web/Core/Resources/Views/Shared/_NavMenu.zh-CN.resx
@@ -225,4 +225,7 @@
收藏夹
+
+ 统计
+
\ No newline at end of file
diff --git a/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs b/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs
index 4424234d..c731f703 100644
--- a/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs
+++ b/src/Lumina.Presentation.Web/Core/Themes/ThemeNavBuilder.cs
@@ -153,6 +153,7 @@ public sealed class ThemeNavBuilder
if (canCreateLibraries)
items.Add(new ThemeNavEntryDto(Localize("AddNewLibrary"), _urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.ADD_LIBRARY), "nav-link", []));
items.Add(new ThemeNavEntryDto(Localize("Favorites"), _urlService.GetAbsoluteUrl(WebRoutes.Favorites.INDEX), "nav-link", []));
+ items.Add(new ThemeNavEntryDto(Localize("Statistics"), _urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.INDEX), "nav-link", []));
// The written content and audio entries open the home page filtered to the libraries of their category, so that browsing starts
// from the libraries the user owns (or from every library, for administrators), instead of from a single library picked upfront.
string librariesCatalogUrl = _urlService.GetAbsoluteUrl(WebRoutes.Home.INDEX_CULTURED) ?? string.Empty;
diff --git a/src/Lumina.Presentation.Web/Core/Views/Library/Statistics/Index.cshtml b/src/Lumina.Presentation.Web/Core/Views/Library/Statistics/Index.cshtml
new file mode 100644
index 00000000..52ed0f07
--- /dev/null
+++ b/src/Lumina.Presentation.Web/Core/Views/Library/Statistics/Index.cshtml
@@ -0,0 +1,398 @@
+@*
+ FALLBACK STATISTICS PAGE - READ BEFORE EDITING
+
+ 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 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.
+
+ 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
+*@
+
+@using Lumina.Presentation.Web.Common.Services
+@using Microsoft.AspNetCore.Mvc.Localization
+@using System
+@using System.Collections.Generic
+@using System.Globalization
+@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();
+ 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
+ };
+ var jsonOptions = new JsonSerializerOptions
+ {
+ PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
+ Converters = { new JsonStringEnumConverter() }
+ };
+}
+
+
+
+
+
+
+
@_localizer["Title"]
+
+
+
+
+ @_localizer["TotalListeningTime"]
+ -
+
+
+ @_localizer["TotalPlays"]
+ -
+
+
+ @_localizer["CompletedPlays"]
+ -
+
+
+ @_localizer["CompletionRate"]
+ -
+
+
+
+
@_localizer["RecentlyPlayed"]
+
+
+
@_localizer["MostPlayed"]
+
+
@_localizer["NoPlaysYet"]
+
@_localizer["LoadFailed"]
+
+
+
+
+
+
+
+@section Scripts {
+
+
+}
diff --git a/src/Lumina.Presentation.Web/wwwroot/css/site.css b/src/Lumina.Presentation.Web/wwwroot/css/site.css
index 10452e75..67719193 100644
--- a/src/Lumina.Presentation.Web/wwwroot/css/site.css
+++ b/src/Lumina.Presentation.Web/wwwroot/css/site.css
@@ -2254,3 +2254,49 @@ html.audio-player-initializing .audio-player-container {
color: #9AA7B0;
font-size: 12px;
}
+
+/* The statistics page: summary tiles, and the track rows of the recently played and most played lists. A row is a
+ track list, so its favorite heart is an inline action and never takes the place of a card heart. */
+.statistics-summary-tile {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 12px;
+ border: 1px solid #777777;
+ border-bottom-color: #000000;
+ border-right-color: #000000;
+ background: linear-gradient(to bottom, #505050 0%, #464646 35%, #404040 55%, #363636 100%);
+}
+
+.statistics-track-list {
+ margin-bottom: 1.5rem;
+}
+
+.statistics-track-list:empty {
+ display: none;
+}
+
+/* The play counts and the last played time of a statistics row are separate lines, so the two values never run together. */
+.statistics-track-metrics {
+ display: flex;
+ flex: 0 0 auto;
+ flex-direction: column;
+ align-items: flex-end;
+ gap: 2px;
+ text-align: right;
+}
+
+.statistics-track-actions .card-favorite-toggle {
+ position: static;
+ display: flex;
+ flex: 0 0 auto;
+ margin: 0;
+}
+
+.statistics-action-button {
+ width: 28px;
+ min-width: 28px;
+ height: 28px;
+ padding: 0;
+ line-height: 1;
+}