Adds the music play statistics endpoints and moves the Web statistics page under the library

This commit is contained in:
BinaryAlley committed 2026-10-25 13:19:24 +02:00
1 parent dfd979ec1e
commit a61fbf407c
69 files changed
+3407 -7

No files matched your search

@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Data transfer object for the listening statistics of the current user.
/// </summary>
/// <param name="TotalListeningDurationMilliseconds">The total duration the user listened to, over every recorded play, in milliseconds.</param>
/// <param name="TotalPlayCount">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.</param>
/// <param name="CompletedPlayCount">The number of recorded plays that completed.</param>
/// <param name="StoppedPlayCount">The number of recorded plays that stopped before the track completed and count as plays.</param>
/// <param name="CompletionRate">The fraction of the plays that count as plays that completed, between 0 and 1, or 0 when there is no counted play.</param>
[DebuggerDisplay("TotalPlayCount: {TotalPlayCount}; CompletedPlayCount: {CompletedPlayCount}")]
public sealed record MusicPlayStatisticsDto(
long TotalListeningDurationMilliseconds,
int TotalPlayCount,
int CompletedPlayCount,
int StoppedPlayCount,
double CompletionRate
);
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Application.Common.DTO.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Data transfer object for a track of the listening statistics of the current user, together with its aggregated play counts.
/// </summary>
/// <param name="TrackId">The Id of the track.</param>
/// <param name="LibraryId">The Id of the media library that contains the track.</param>
/// <param name="AlbumId">The Id of the album that contains the track.</param>
/// <param name="ArtistId">The Id of the artist that produced the track.</param>
/// <param name="Title">The title of the track, if it still exists and the user can access its library.</param>
/// <param name="AlbumTitle">The title of the album that contains the track, if it still exists and the user can access its library.</param>
/// <param name="ArtistName">The name of the artist that produced the track, if it still exists and the user can access its library.</param>
/// <param name="CoverPath">The path of the cover art of the album, if available.</param>
/// <param name="LastPlayedOnUtc">The date and time of the last recorded activity of the track's most recent play.</param>
/// <param name="PlayCount">The number of plays of the track that count as plays.</param>
/// <param name="CompletedPlayCount">The number of plays of the track that completed.</param>
/// <param name="ListenedDurationMilliseconds">The duration the user listened to the track, over all of its counted plays, in milliseconds.</param>
[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
);
@@ -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.
/// </summary>
public interface IMusicPlayRecordRepository : IRepository<MusicPlayRecordEntity>,
IInsertRepositoryAction<MusicPlayRecordEntity>
IInsertRepositoryAction<MusicPlayRecordEntity>
{
/// <summary>
/// Gets the play record identified by <paramref name="id"/> when it belongs to the user identified by <paramref name="userId"/>, if it exists.
@@ -29,6 +30,14 @@ public interface IMusicPlayRecordRepository : IRepository<MusicPlayRecordEntity>
/// </returns>
Task<Result<MusicPlayRecordEntity?>> GetByIdForUserAsync(Guid id, Guid userId, bool shouldTrackEntities = true, CancellationToken cancellationToken = default);
/// <summary>
/// Gets the play records of the user identified by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user whose play records are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the play records of the user, or an error.</returns>
Task<Result<IReadOnlyList<MusicPlayRecordEntity>>> GetForUserAsync(Guid userId, CancellationToken cancellationToken);
/// <summary>
/// Updates the play record of the user identified by <paramref name="userId"/>, when the record belongs to that user and still holds the
/// version it was read with.
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="GetMostPlayedRequest"/>.
/// </summary>
public static class GetMostPlayedRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetMostPlayedQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
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);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="GetRecentlyPlayedRequest"/>.
/// </summary>
public static class GetRecentlyPlayedRequestMapping
{
/// <summary>
/// Converts <paramref name="request"/> to <see cref="GetRecentlyPlayedQuery"/>.
/// </summary>
/// <param name="request">The request to be converted.</param>
/// <returns>The converted query.</returns>
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);
}
}
@@ -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<DateTime>.FromNullable(repositoryEntity.EndedOnUtc),
repositoryEntity.CreatedOnUtc,
Optional<DateTime>.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
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="MusicPlayStatisticsDto"/>.
/// </summary>
public static class MusicPlayStatisticsDtoMapping
{
/// <summary>
/// Converts <paramref name="data"/> to <see cref="MusicPlayStatisticsResponse"/>.
/// </summary>
/// <param name="data">The listening statistics data to be converted.</param>
/// <returns>The converted response.</returns>
public static MusicPlayStatisticsResponse ToResponse(this MusicPlayStatisticsDto data)
{
return new MusicPlayStatisticsResponse(
data.TotalListeningDurationMilliseconds.ToClampedTimeSpan().TotalSeconds,
data.TotalPlayCount,
data.CompletedPlayCount,
data.StoppedPlayCount,
data.CompletionRate
);
}
}
@@ -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;
/// <summary>
/// Extension methods for converting <see cref="PlayedTrackDto"/>.
/// </summary>
public static class PlayedTrackDtoMapping
{
/// <summary>
/// Converts <paramref name="data"/> to <see cref="PlayedTrackResponse"/>.
/// </summary>
/// <param name="data">The played track data to be converted.</param>
/// <returns>The converted response.</returns>
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
);
}
/// <summary>
/// Converts <paramref name="data"/> to a paginated collection of <see cref="PlayedTrackResponse"/>.
/// </summary>
/// <param name="data">The paginated played track data to be converted.</param>
/// <returns>The converted paginated responses.</returns>
public static PaginatedResponse<PlayedTrackResponse> ToResponses(this PaginatedResultDto<PlayedTrackDto> data)
{
return new PaginatedResponse<PlayedTrackResponse>
{
Data = [.. data.Data.Select(track => track.ToResponse())],
CurrentPage = data.CurrentPage,
PerPage = data.PerPage,
Count = data.Count,
NumberOfPages = data.NumberOfPages
};
}
}
@@ -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;
/// <summary>
/// Query for getting the most played tracks of the current user, from the most played.
/// </summary>
/// <param name="PaginationData">The object containing the requested pagination data, or <see langword="null"/> to return every matching track.</param>
[DebuggerDisplay("PaginationData: {PaginationData}")]
public record GetMostPlayedQuery(
PaginationDataDto? PaginationData
) : IQuery;
@@ -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;
/// <summary>
/// Handler for the query to get the most played tracks of the current user.
/// </summary>
public class GetMostPlayedQueryHandler : IQueryHandler<GetMostPlayedQuery, Result<PaginatedResponse<PlayedTrackResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="GetMostPlayedQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
public GetMostPlayedQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IAuthorizationService authorizationService)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
}
/// <summary>
/// Handles the query to get the most played tracks of the current user.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the requested page of most played tracks, or an error message.
/// </returns>
public async Task<Result<PaginatedResponse<PlayedTrackResponse>>> 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<IReadOnlyList<MusicPlayRecordEntity>> 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<PlayedTrackAggregate> 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);
}
/// <summary>
/// Pages the aggregated tracks, resolves their display data, and converts them to the response of the query.
/// </summary>
/// <param name="aggregates">The aggregated tracks, already ordered for this query.</param>
/// <param name="paginationData">The requested pagination data, or <see langword="null"/> for every matching track.</param>
/// <param name="userId">The Id of the user whose tracks are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the requested page of played tracks, or an error.</returns>
private async Task<Result<PaginatedResponse<PlayedTrackResponse>>> ToResponsePageAsync(
List<PlayedTrackAggregate> aggregates, PaginationDataDto? paginationData, Guid userId, CancellationToken cancellationToken)
{
PaginatedResultDto<PlayedTrackAggregate> page = Paginate(aggregates, paginationData);
Result<List<PlayedTrackDto>> getDtosResult = await ToPlayedTrackDtosAsync(page.Data, userId, cancellationToken).ConfigureAwait(false);
if (getDtosResult.IsFailure)
return getDtosResult.Errors;
return Result.From(new PaginatedResultDto<PlayedTrackDto>
{
Data = getDtosResult.Value,
CurrentPage = page.CurrentPage,
PerPage = page.PerPage,
Count = page.Count,
NumberOfPages = page.NumberOfPages
}.ToResponses());
}
/// <summary>
/// Applies the requested pagination to the ordered aggregated tracks.
/// </summary>
/// <param name="aggregates">The ordered aggregated tracks.</param>
/// <param name="paginationData">The requested pagination data, or <see langword="null"/> for every matching track.</param>
/// <returns>The requested page of aggregated tracks.</returns>
private static PaginatedResultDto<PlayedTrackAggregate> Paginate(List<PlayedTrackAggregate> aggregates, PaginationDataDto? paginationData)
{
if (paginationData is null)
return new PaginatedResultDto<PlayedTrackAggregate>
{
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<PlayedTrackAggregate> page = [.. aggregates
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)];
return new PaginatedResultDto<PlayedTrackAggregate>
{
Data = page,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
/// <summary>
/// Resolves the display data of the tracks of <paramref name="aggregates"/> for the libraries the user can access, and builds their DTOs.
/// </summary>
/// <param name="aggregates">The aggregated tracks of the requested page.</param>
/// <param name="userId">The Id of the user whose tracks are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the played tracks, with blank display data for missing or inaccessible tracks, or an error.</returns>
private async Task<Result<List<PlayedTrackDto>>> ToPlayedTrackDtosAsync(IReadOnlyList<PlayedTrackAggregate> aggregates, Guid userId, CancellationToken cancellationToken)
{
if (aggregates.Count == 0)
return new List<PlayedTrackDto>();
// 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<Guid, bool> libraryAccess = [];
foreach (Guid libraryId in aggregates.Select(aggregate => aggregate.LibraryId).Distinct())
libraryAccess[libraryId] = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
List<Guid> accessibleTrackIds = [.. aggregates
.Where(aggregate => libraryAccess[aggregate.LibraryId])
.Select(aggregate => aggregate.TrackId)
.Distinct()];
Dictionary<Guid, TrackEntity> tracks = [];
if (accessibleTrackIds.Count > 0)
{
Result<IReadOnlyList<TrackEntity>> 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<Guid> albumIds = [.. tracks.Values.Select(track => track.AlbumId).Distinct()];
Dictionary<Guid, string?> albumCovers = [];
if (albumIds.Count > 0)
{
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnersAsync(MusicArtworkOwnerType.Album, albumIds, cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
albumCovers = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.GroupBy(artwork => artwork.OwnerId)
.ToDictionary(
group => group.Key,
group => group.OrderBy(artwork => artwork.Ordinal).Select(artwork => artwork.FileName).FirstOrDefault());
}
List<PlayedTrackDto> 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;
}
/// <summary>
/// The aggregated counted plays of one track in one library.
/// </summary>
/// <param name="TrackId">The Id of the track.</param>
/// <param name="LibraryId">The Id of the media library that contains the track.</param>
/// <param name="AlbumId">The Id of the album that contains the track.</param>
/// <param name="ArtistId">The Id of the artist that produced the track.</param>
/// <param name="LastActivityOnUtc">The date and time of the last recorded activity of the track's most recent play.</param>
/// <param name="PlayCount">The number of plays of the track that count as plays.</param>
/// <param name="CompletedPlayCount">The number of plays of the track that completed.</param>
/// <param name="ListenedDurationMilliseconds">The duration the user listened to the track, over all of its counted plays, in milliseconds.</param>
private sealed record PlayedTrackAggregate(
Guid TrackId,
Guid LibraryId,
Guid AlbumId,
Guid ArtistId,
DateTime LastActivityOnUtc,
int PlayCount,
int CompletedPlayCount,
long ListenedDurationMilliseconds
);
}
@@ -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;
/// <summary>
/// Query for getting the listening statistics of the current user.
/// </summary>
[DebuggerDisplay("Music play statistics")]
public record GetMusicPlayStatisticsQuery() : IQuery;
@@ -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;
/// <summary>
/// Handler for the query to get the listening statistics of the current user.
/// </summary>
public class GetMusicPlayStatisticsQueryHandler : IQueryHandler<GetMusicPlayStatisticsQuery, Result<MusicPlayStatisticsResponse>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
/// <summary>
/// Initializes a new instance of the <see cref="GetMusicPlayStatisticsQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
public GetMusicPlayStatisticsQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
}
/// <summary>
/// Handles the query to get the listening statistics of the current user.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the listening statistics of the current user, or an error message.
/// </returns>
public async Task<Result<MusicPlayStatisticsResponse>> 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<IReadOnlyList<MusicPlayRecordEntity>> getRecordsResult = await _unitOfWork.MusicPlayRecordRepository.GetForUserAsync(userId, cancellationToken).ConfigureAwait(false);
if (getRecordsResult.IsFailure)
return getRecordsResult.Errors;
IReadOnlyList<MusicPlayRecordEntity> 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();
}
}
@@ -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;
/// <summary>
/// Query for getting the recently played tracks of the current user, from the most recently played.
/// </summary>
/// <param name="PaginationData">The object containing the requested pagination data, or <see langword="null"/> to return every matching track.</param>
[DebuggerDisplay("PaginationData: {PaginationData}")]
public record GetRecentlyPlayedQuery(
PaginationDataDto? PaginationData
) : IQuery;
@@ -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;
/// <summary>
/// Handler for the query to get the recently played tracks of the current user.
/// </summary>
public class GetRecentlyPlayedQueryHandler : IQueryHandler<GetRecentlyPlayedQuery, Result<PaginatedResponse<PlayedTrackResponse>>>
{
private readonly IUnitOfWork _unitOfWork;
private readonly ICurrentUserService _currentUserService;
private readonly IAuthorizationService _authorizationService;
/// <summary>
/// Initializes a new instance of the <see cref="GetRecentlyPlayedQueryHandler"/> class.
/// </summary>
/// <param name="unitOfWork">Injected unit of work for interacting with the data access layer repositories.</param>
/// <param name="currentUserService">Injected service to retrieve the current user information.</param>
/// <param name="authorizationService">Injected service for authorization related functionality.</param>
public GetRecentlyPlayedQueryHandler(IUnitOfWork unitOfWork, ICurrentUserService currentUserService, IAuthorizationService authorizationService)
{
_unitOfWork = unitOfWork;
_currentUserService = currentUserService;
_authorizationService = authorizationService;
}
/// <summary>
/// Handles the query to get the recently played tracks of the current user.
/// </summary>
/// <param name="query">The query to be handled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>
/// An <see cref="Result{TValue}"/> containing either the requested page of recently played tracks, or an error message.
/// </returns>
public async Task<Result<PaginatedResponse<PlayedTrackResponse>>> 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<IReadOnlyList<MusicPlayRecordEntity>> 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<PlayedTrackAggregate> 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);
}
/// <summary>
/// Pages the aggregated tracks, resolves their display data, and converts them to the response of the query.
/// </summary>
/// <param name="aggregates">The aggregated tracks, already ordered for this query.</param>
/// <param name="paginationData">The requested pagination data, or <see langword="null"/> for every matching track.</param>
/// <param name="userId">The Id of the user whose tracks are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the requested page of played tracks, or an error.</returns>
private async Task<Result<PaginatedResponse<PlayedTrackResponse>>> ToResponsePageAsync(
List<PlayedTrackAggregate> aggregates, PaginationDataDto? paginationData, Guid userId, CancellationToken cancellationToken)
{
PaginatedResultDto<PlayedTrackAggregate> page = Paginate(aggregates, paginationData);
Result<List<PlayedTrackDto>> getDtosResult = await ToPlayedTrackDtosAsync(page.Data, userId, cancellationToken).ConfigureAwait(false);
if (getDtosResult.IsFailure)
return getDtosResult.Errors;
return Result.From(new PaginatedResultDto<PlayedTrackDto>
{
Data = getDtosResult.Value,
CurrentPage = page.CurrentPage,
PerPage = page.PerPage,
Count = page.Count,
NumberOfPages = page.NumberOfPages
}.ToResponses());
}
/// <summary>
/// Applies the requested pagination to the ordered aggregated tracks.
/// </summary>
/// <param name="aggregates">The ordered aggregated tracks.</param>
/// <param name="paginationData">The requested pagination data, or <see langword="null"/> for every matching track.</param>
/// <returns>The requested page of aggregated tracks.</returns>
private static PaginatedResultDto<PlayedTrackAggregate> Paginate(List<PlayedTrackAggregate> aggregates, PaginationDataDto? paginationData)
{
if (paginationData is null)
return new PaginatedResultDto<PlayedTrackAggregate>
{
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<PlayedTrackAggregate> page = [.. aggregates
.Skip((currentPage - 1) * paginationData.PerPage)
.Take(paginationData.PerPage)];
return new PaginatedResultDto<PlayedTrackAggregate>
{
Data = page,
CurrentPage = currentPage,
PerPage = paginationData.PerPage,
Count = count,
NumberOfPages = numberOfPages
};
}
/// <summary>
/// Resolves the display data of the tracks of <paramref name="aggregates"/> for the libraries the user can access, and builds their DTOs.
/// </summary>
/// <param name="aggregates">The aggregated tracks of the requested page.</param>
/// <param name="userId">The Id of the user whose tracks are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the played tracks, with blank display data for missing or inaccessible tracks, or an error.</returns>
private async Task<Result<List<PlayedTrackDto>>> ToPlayedTrackDtosAsync(IReadOnlyList<PlayedTrackAggregate> aggregates, Guid userId, CancellationToken cancellationToken)
{
if (aggregates.Count == 0)
return new List<PlayedTrackDto>();
// 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<Guid, bool> libraryAccess = [];
foreach (Guid libraryId in aggregates.Select(aggregate => aggregate.LibraryId).Distinct())
libraryAccess[libraryId] = await _authorizationService.EvaluatePolicyAsync<ILibraryOwnershipPolicy>(
userId, new LibraryOwnershipPolicyContext(libraryId), cancellationToken).ConfigureAwait(false);
List<Guid> accessibleTrackIds = [.. aggregates
.Where(aggregate => libraryAccess[aggregate.LibraryId])
.Select(aggregate => aggregate.TrackId)
.Distinct()];
Dictionary<Guid, TrackEntity> tracks = [];
if (accessibleTrackIds.Count > 0)
{
Result<IReadOnlyList<TrackEntity>> 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<Guid> albumIds = [.. tracks.Values.Select(track => track.AlbumId).Distinct()];
Dictionary<Guid, string?> albumCovers = [];
if (albumIds.Count > 0)
{
Result<IReadOnlyList<MusicArtworkEntity>> getArtworkResult = await _unitOfWork.MusicArtworkRepository.GetByOwnersAsync(MusicArtworkOwnerType.Album, albumIds, cancellationToken).ConfigureAwait(false);
if (getArtworkResult.IsFailure)
return getArtworkResult.Errors;
albumCovers = getArtworkResult.Value
.Where(artwork => artwork.ArtworkType == ArtworkType.Cover)
.GroupBy(artwork => artwork.OwnerId)
.ToDictionary(
group => group.Key,
group => group.OrderBy(artwork => artwork.Ordinal).Select(artwork => artwork.FileName).FirstOrDefault());
}
List<PlayedTrackDto> 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;
}
/// <summary>
/// The aggregated counted plays of one track in one library.
/// </summary>
/// <param name="TrackId">The Id of the track.</param>
/// <param name="LibraryId">The Id of the media library that contains the track.</param>
/// <param name="AlbumId">The Id of the album that contains the track.</param>
/// <param name="ArtistId">The Id of the artist that produced the track.</param>
/// <param name="LastActivityOnUtc">The date and time of the last recorded activity of the track's most recent play.</param>
/// <param name="PlayCount">The number of plays of the track that count as plays.</param>
/// <param name="CompletedPlayCount">The number of plays of the track that completed.</param>
/// <param name="ListenedDurationMilliseconds">The duration the user listened to the track, over all of its counted plays, in milliseconds.</param>
private sealed record PlayedTrackAggregate(
Guid TrackId,
Guid LibraryId,
Guid AlbumId,
Guid ArtistId,
DateTime LastActivityOnUtc,
int PlayCount,
int CompletedPlayCount,
long ListenedDurationMilliseconds
);
}
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Represents a request for getting a window of the most played tracks of the current user.
/// </summary>
/// <param name="CurrentPage">The one based page of tracks to return. Optional; defaults to 1 when a page size is provided.</param>
/// <param name="PerPage">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.</param>
[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
public record GetMostPlayedRequest(
int? CurrentPage,
int? PerPage
);
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Requests.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Represents a request for getting a window of the recently played tracks of the current user.
/// </summary>
/// <param name="CurrentPage">The one based page of tracks to return. Optional; defaults to 1 when a page size is provided.</param>
/// <param name="PerPage">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.</param>
[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
public record GetRecentlyPlayedRequest(
int? CurrentPage,
int? PerPage
);
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Represents the listening statistics of the current user.
/// </summary>
/// <param name="TotalListeningDurationInSeconds">The total duration the user listened to, over every recorded play, in seconds.</param>
/// <param name="TotalPlayCount">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.</param>
/// <param name="CompletedPlayCount">The number of recorded plays that completed.</param>
/// <param name="StoppedPlayCount">The number of recorded plays that stopped before the track completed and count as plays.</param>
/// <param name="CompletionRate">The fraction of the plays that count as plays that completed, between 0 and 1, or 0 when there is no counted play.</param>
[DebuggerDisplay("TotalPlayCount: {TotalPlayCount}; CompletedPlayCount: {CompletedPlayCount}")]
public sealed record MusicPlayStatisticsResponse(
double TotalListeningDurationInSeconds,
int TotalPlayCount,
int CompletedPlayCount,
int StoppedPlayCount,
double CompletionRate
);
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Contracts.Responses.MediaLibrary.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Represents a track of the listening statistics of the current user, together with its aggregated play counts.
/// </summary>
/// <param name="TrackId">The Id of the track.</param>
/// <param name="LibraryId">The Id of the media library that contains the track.</param>
/// <param name="AlbumId">The Id of the album that contains the track.</param>
/// <param name="ArtistId">The Id of the artist that produced the track.</param>
/// <param name="Title">The title of the track, if it still exists and the user can access its library.</param>
/// <param name="AlbumTitle">The title of the album that contains the track, if it still exists and the user can access its library.</param>
/// <param name="ArtistName">The name of the artist that produced the track, if it still exists and the user can access its library.</param>
/// <param name="CoverPath">The path of the cover art of the album, if available.</param>
/// <param name="LastPlayedOnUtc">The date and time of the last recorded activity of the track's most recent play.</param>
/// <param name="PlayCount">The number of plays of the track that count as plays.</param>
/// <param name="CompletedPlayCount">The number of plays of the track that completed.</param>
/// <param name="ListenedDurationInSeconds">The duration the user listened to the track, over all of its counted plays, in seconds.</param>
[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
);
@@ -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);
}
/// <summary>
/// Gets the play records of the user identified by <paramref name="userId"/>.
/// </summary>
/// <param name="userId">The Id of the user whose play records are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>An <see cref="Result{TValue}"/> containing either the play records of the user, or an error.</returns>
public async Task<Result<IReadOnlyList<MusicPlayRecordEntity>>> GetForUserAsync(Guid userId, CancellationToken cancellationToken)
{
// The user is part of the query, so the storage medium never returns the plays of another user.
List<MusicPlayRecordEntity> playRecords = await _luminaDbContext.MusicPlayRecords
.AsNoTracking()
.Where(playRecord => playRecord.UserId == userId)
.ToListAsync(cancellationToken).ConfigureAwait(false);
return Result.From<IReadOnlyList<MusicPlayRecordEntity>>(playRecords);
}
/// <summary>
/// Adds a new play record.
/// </summary>
@@ -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<MusicPlayRecordId>
{
/// <summary>
/// The minimum number of seconds a user must listen to a track for the play to count, unless the play completed first.
/// </summary>
private const int MINIMUM_COUNTED_LISTENED_DURATION_SECONDS = 30;
/// <summary>
/// Gets the object representing the unique identifier of the user that started the play.
/// </summary>
@@ -208,6 +213,17 @@ public sealed class MusicPlayRecord : AggregateRoot<MusicPlayRecordId>
updatedOnUtc);
}
/// <summary>
/// Determines whether a play with the provided <paramref name="status"/> and <paramref name="listenedDuration"/> counts as a play for the listening statistics.
/// </summary>
/// <param name="status">The state of the recorded play.</param>
/// <param name="listenedDuration">The duration that the user has listened to.</param>
/// <returns><see langword="true"/> when the play counts, <see langword="false"/> otherwise.</returns>
public static bool DoesCountAsPlay(PlaybackRecordStatus status, TimeSpan listenedDuration)
{
return status == PlaybackRecordStatus.Completed || listenedDuration.TotalSeconds >= MINIMUM_COUNTED_LISTENED_DURATION_SECONDS;
}
/// <summary>
/// Updates the last reported position and the listened duration of an in-progress play.
/// </summary>
@@ -0,0 +1,17 @@
namespace Lumina.Presentation.Api.Common.Routes.Library.AudioLibrary.MusicLibrary;
/// <summary>
/// Class for the collection of the music play statistics routes of the API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the music play statistics of the current user.
/// </summary>
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";
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/users/me/music-play-history/most-played</c> route.
/// </summary>
/// <remarks>
/// Uses "me" because it is always for the currently authenticated user.
/// </remarks>
public class GetMostPlayedEndpoint : BaseEndpoint<GetMostPlayedRequest, IResult>
{
private readonly IQueryHandler<GetMostPlayedQuery, Result<PaginatedResponse<PlayedTrackResponse>>> _getMostPlayedQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetMostPlayedEndpoint"/> class.
/// </summary>
/// <param name="getMostPlayedQueryHandler">Injected service for handling get most played queries.</param>
public GetMostPlayedEndpoint(IQueryHandler<GetMostPlayedQuery, Result<PaginatedResponse<PlayedTrackResponse>>> getMostPlayedQueryHandler)
{
_getMostPlayedQueryHandler = getMostPlayedQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.PlayStatistics.GET_MOST_PLAYED);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the most played tracks of the current user.
/// </summary>
/// <param name="request">The request containing the optional page bounds.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<PaginatedResponse<PlayedTrackResponse>> result = await _getMostPlayedQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetMostPlayedEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetMostPlayedEndpointSummary : Summary<GetMostPlayedEndpoint, GetMostPlayedRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetMostPlayedEndpointSummary"/> class.
/// </summary>
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<PaginatedResponse<PlayedTrackResponse>>(response => response.Data, "The most played tracks of the requested page, ordered by counted plays, listened duration, last activity, and track Id.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.CurrentPage, "The current page number.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.PerPage, "The number of tracks retrieved per page.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.Count, "The total number of tracks that match the filters.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.NumberOfPages, "The total number of pages.");
ResponseParam<PlayedTrackResponse>(response => response.TrackId, "The Id of the track.");
ResponseParam<PlayedTrackResponse>(response => response.LibraryId, "The Id of the media library that contains the track.");
ResponseParam<PlayedTrackResponse>(response => response.AlbumId, "The Id of the album that contains the track.");
ResponseParam<PlayedTrackResponse>(response => response.ArtistId, "The Id of the artist that produced the track.");
ResponseParam<PlayedTrackResponse>(response => response.Title, "The title of the track, if it still exists and the user can access its library.");
ResponseParam<PlayedTrackResponse>(response => response.AlbumTitle, "The title of the album that contains the track, if available.");
ResponseParam<PlayedTrackResponse>(response => response.ArtistName, "The name of the artist that produced the track, if available.");
ResponseParam<PlayedTrackResponse>(response => response.CoverPath, "The path of the cover art of the album, if available.");
ResponseParam<PlayedTrackResponse>(response => response.LastPlayedOnUtc, "The date and time of the last recorded activity of the track's most recent play.");
ResponseParam<PlayedTrackResponse>(response => response.PlayCount, "The number of plays of the track that count as plays.");
ResponseParam<PlayedTrackResponse>(response => response.CompletedPlayCount, "The number of plays of the track that completed.");
ResponseParam<PlayedTrackResponse>(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<PlayedTrackResponse>
{
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"
}
);
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/users/me/music-play-history/statistics</c> route.
/// </summary>
/// <remarks>
/// Uses "me" because it is always for the currently authenticated user.
/// </remarks>
public class GetMusicPlayStatisticsEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IQueryHandler<GetMusicPlayStatisticsQuery, Result<MusicPlayStatisticsResponse>> _getMusicPlayStatisticsQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetMusicPlayStatisticsEndpoint"/> class.
/// </summary>
/// <param name="getMusicPlayStatisticsQueryHandler">Injected service for handling get music play statistics queries.</param>
public GetMusicPlayStatisticsEndpoint(IQueryHandler<GetMusicPlayStatisticsQuery, Result<MusicPlayStatisticsResponse>> getMusicPlayStatisticsQueryHandler)
{
_getMusicPlayStatisticsQueryHandler = getMusicPlayStatisticsQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.PlayStatistics.GET_MUSIC_PLAY_STATISTICS);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the listening statistics of the current user.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<MusicPlayStatisticsResponse> result = await _getMusicPlayStatisticsQueryHandler.HandleAsync(new GetMusicPlayStatisticsQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetMusicPlayStatisticsEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetMusicPlayStatisticsEndpointSummary : Summary<GetMusicPlayStatisticsEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetMusicPlayStatisticsEndpointSummary"/> class.
/// </summary>
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<MusicPlayStatisticsResponse>(response => response.TotalListeningDurationInSeconds, "The total duration the user listened to, over every recorded play, in seconds.");
ResponseParam<MusicPlayStatisticsResponse>(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<MusicPlayStatisticsResponse>(response => response.CompletedPlayCount, "The number of recorded plays that completed.");
ResponseParam<MusicPlayStatisticsResponse>(response => response.StoppedPlayCount, "The number of recorded plays that stopped before the track completed and count as plays.");
ResponseParam<MusicPlayStatisticsResponse>(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"
}
);
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/users/me/music-play-history/recently-played</c> route.
/// </summary>
/// <remarks>
/// Uses "me" because it is always for the currently authenticated user.
/// </remarks>
public class GetRecentlyPlayedEndpoint : BaseEndpoint<GetRecentlyPlayedRequest, IResult>
{
private readonly IQueryHandler<GetRecentlyPlayedQuery, Result<PaginatedResponse<PlayedTrackResponse>>> _getRecentlyPlayedQueryHandler;
/// <summary>
/// Initializes a new instance of the <see cref="GetRecentlyPlayedEndpoint"/> class.
/// </summary>
/// <param name="getRecentlyPlayedQueryHandler">Injected service for handling get recently played queries.</param>
public GetRecentlyPlayedEndpoint(IQueryHandler<GetRecentlyPlayedQuery, Result<PaginatedResponse<PlayedTrackResponse>>> getRecentlyPlayedQueryHandler)
{
_getRecentlyPlayedQueryHandler = getRecentlyPlayedQueryHandler;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.PlayStatistics.GET_RECENTLY_PLAYED);
Version(1);
DontCatchExceptions();
}
/// <summary>
/// Gets the recently played tracks of the current user.
/// </summary>
/// <param name="request">The request containing the optional page bounds.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<PaginatedResponse<PlayedTrackResponse>> result = await _getRecentlyPlayedQueryHandler.HandleAsync(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetRecentlyPlayedEndpoint"/> API endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetRecentlyPlayedEndpointSummary : Summary<GetRecentlyPlayedEndpoint, GetRecentlyPlayedRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetRecentlyPlayedEndpointSummary"/> class.
/// </summary>
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<PaginatedResponse<PlayedTrackResponse>>(response => response.Data, "The recently played tracks of the requested page, from the most recently played.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.CurrentPage, "The current page number.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.PerPage, "The number of tracks retrieved per page.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.Count, "The total number of tracks that match the filters.");
ResponseParam<PaginatedResponse<PlayedTrackResponse>>(response => response.NumberOfPages, "The total number of pages.");
ResponseParam<PlayedTrackResponse>(response => response.TrackId, "The Id of the track.");
ResponseParam<PlayedTrackResponse>(response => response.LibraryId, "The Id of the media library that contains the track.");
ResponseParam<PlayedTrackResponse>(response => response.AlbumId, "The Id of the album that contains the track.");
ResponseParam<PlayedTrackResponse>(response => response.ArtistId, "The Id of the artist that produced the track.");
ResponseParam<PlayedTrackResponse>(response => response.Title, "The title of the track, if it still exists and the user can access its library.");
ResponseParam<PlayedTrackResponse>(response => response.AlbumTitle, "The title of the album that contains the track, if available.");
ResponseParam<PlayedTrackResponse>(response => response.ArtistName, "The name of the artist that produced the track, if available.");
ResponseParam<PlayedTrackResponse>(response => response.CoverPath, "The path of the cover art of the album, if available.");
ResponseParam<PlayedTrackResponse>(response => response.LastPlayedOnUtc, "The date and time of the last recorded activity of the track's most recent play.");
ResponseParam<PlayedTrackResponse>(response => response.PlayCount, "The number of plays of the track that count as plays.");
ResponseParam<PlayedTrackResponse>(response => response.CompletedPlayCount, "The number of plays of the track that completed.");
ResponseParam<PlayedTrackResponse>(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<PlayedTrackResponse>
{
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"
}
);
}
}
@@ -44,6 +44,19 @@ public class GetAllUsersConsumptionStatisticsEndpointSummary : Summary<GetAllUse
ResponseParam<ConsumptionTotalsResponse>(response => response.StoppedSessionCount, "The number of recorded sessions of every user that stopped before they completed and count towards statistics.");
ResponseParam<ConsumptionTotalsResponse>(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<ConsumptionTotalsResponse>(response => response.MediaKindSummaries, "The combined consumption statistics broken down by media kind.");
ResponseParam<ConsumptionSummaryResponse>(response => response.UserId, "The Id of the user the summary belongs to.");
ResponseParam<ConsumptionSummaryResponse>(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of the user, in seconds.");
ResponseParam<ConsumptionSummaryResponse>(response => response.CountedSessionCount, "The number of recorded sessions of the user that count towards statistics.");
ResponseParam<ConsumptionSummaryResponse>(response => response.CompletedSessionCount, "The number of recorded sessions of the user that completed.");
ResponseParam<ConsumptionSummaryResponse>(response => response.StoppedSessionCount, "The number of recorded sessions of the user that stopped before they completed and count towards statistics.");
ResponseParam<ConsumptionSummaryResponse>(response => response.CompletionRate, "The fraction of the counted sessions of the user that completed, between 0 and 1.");
ResponseParam<ConsumptionSummaryResponse>(response => response.MediaKindSummaries, "The consumption statistics of the user broken down by media kind.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.MediaKind, "The kind of media the breakdown entry belongs to.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of the media kind, in seconds.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.CountedSessionCount, "The number of recorded sessions of the media kind that count towards statistics.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.CompletedSessionCount, "The number of recorded sessions of the media kind that completed.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.StoppedSessionCount, "The number of recorded sessions of the media kind that stopped before they completed and count towards statistics.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.CompletionRate, "The fraction of the counted sessions of the media kind that completed, between 0 and 1.");
Response<AllUsersConsumptionStatisticsResponse>(statusCode: 200, description: "The consumption statistics of every user are returned.", contentType: "application/json",
example: new AllUsersConsumptionStatisticsResponse(
@@ -42,7 +42,13 @@ public class GetConsumptionStatisticsEndpointSummary : Summary<GetConsumptionSta
ResponseParam<ConsumptionSummaryResponse>(response => response.CompletedSessionCount, "The number of recorded sessions that completed.");
ResponseParam<ConsumptionSummaryResponse>(response => response.StoppedSessionCount, "The number of recorded sessions that stopped before they completed and count towards statistics.");
ResponseParam<ConsumptionSummaryResponse>(response => response.CompletionRate, "The fraction of the counted sessions that completed, between 0 and 1, or 0 when there is no counted session.");
ResponseParam<ConsumptionSummaryResponse>(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<ConsumptionSummaryResponse>(response => response.MediaKindSummaries, "The consumption statistics broken down by media kind.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.MediaKind, "The kind of media the breakdown entry belongs to.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of the media kind, in seconds.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.CountedSessionCount, "The number of recorded sessions of the media kind that count towards statistics.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.CompletedSessionCount, "The number of recorded sessions of the media kind that completed.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.StoppedSessionCount, "The number of recorded sessions of the media kind that stopped before they completed and count towards statistics.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.CompletionRate, "The fraction of the counted sessions of the media kind that completed, between 0 and 1.");
Response<ConsumptionSummaryResponse>(statusCode: 200, description: "The consumption statistics of the current user are returned.", contentType: "application/json",
example: new ConsumptionSummaryResponse(
@@ -43,7 +43,13 @@ public class GetUserConsumptionStatisticsEndpointSummary : Summary<GetUserConsum
ResponseParam<ConsumptionSummaryResponse>(response => response.CompletedSessionCount, "The number of recorded sessions that completed.");
ResponseParam<ConsumptionSummaryResponse>(response => response.StoppedSessionCount, "The number of recorded sessions that stopped before they completed and count towards statistics.");
ResponseParam<ConsumptionSummaryResponse>(response => response.CompletionRate, "The fraction of the counted sessions that completed, between 0 and 1, or 0 when there is no counted session.");
ResponseParam<ConsumptionSummaryResponse>(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<ConsumptionSummaryResponse>(response => response.MediaKindSummaries, "The consumption statistics broken down by media kind.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.MediaKind, "The kind of media the breakdown entry belongs to.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.TotalConsumedDurationInSeconds, "The total duration consumed over every recorded session of the media kind, in seconds.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.CountedSessionCount, "The number of recorded sessions of the media kind that count towards statistics.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.CompletedSessionCount, "The number of recorded sessions of the media kind that completed.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.StoppedSessionCount, "The number of recorded sessions of the media kind that stopped before they completed and count towards statistics.");
ResponseParam<MediaKindConsumptionSummaryResponse>(response => response.CompletionRate, "The fraction of the counted sessions of the media kind that completed, between 0 and 1.");
Response<ConsumptionSummaryResponse>(statusCode: 200, description: "The consumption statistics of the user are returned.", contentType: "application/json",
example: new ConsumptionSummaryResponse(
@@ -0,0 +1,22 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Data transfer object for the listening statistics of the current user.
/// </summary>
/// <param name="TotalListeningDurationInSeconds">The total duration the user listened to, over every recorded play, in seconds.</param>
/// <param name="TotalPlayCount">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.</param>
/// <param name="CompletedPlayCount">The number of recorded plays that completed.</param>
/// <param name="StoppedPlayCount">The number of recorded plays that stopped before the track completed and count as plays.</param>
/// <param name="CompletionRate">The fraction of the plays that count as plays that completed, between 0 and 1, or 0 when there is no counted play.</param>
[DebuggerDisplay("TotalPlayCount: {TotalPlayCount}; CompletedPlayCount: {CompletedPlayCount}")]
public sealed record MusicPlayStatisticsDto(
double TotalListeningDurationInSeconds,
int TotalPlayCount,
int CompletedPlayCount,
int StoppedPlayCount,
double CompletionRate
);
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Data transfer object for a track of the listening statistics of the current user, together with its aggregated play counts.
/// </summary>
/// <param name="TrackId">The Id of the track.</param>
/// <param name="LibraryId">The Id of the media library that contains the track.</param>
/// <param name="AlbumId">The Id of the album that contains the track.</param>
/// <param name="ArtistId">The Id of the artist that produced the track.</param>
/// <param name="Title">The title of the track, if it still exists and the user can access its library.</param>
/// <param name="AlbumTitle">The title of the album that contains the track, if it still exists and the user can access its library.</param>
/// <param name="ArtistName">The name of the artist that produced the track, if it still exists and the user can access its library.</param>
/// <param name="CoverPath">The path of the cover art of the album, if available.</param>
/// <param name="LastPlayedOnUtc">The date and time of the last recorded activity of the track's most recent play.</param>
/// <param name="PlayCount">The number of plays of the track that count as plays.</param>
/// <param name="CompletedPlayCount">The number of plays of the track that completed.</param>
/// <param name="ListenedDurationInSeconds">The duration the user listened to the track, over all of its counted plays, in seconds.</param>
[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
);
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Represents a request for getting a page of the most played tracks of the current user.
/// </summary>
/// <param name="CurrentPage">The one based page of tracks to return. Optional. Defaults to 1.</param>
/// <param name="PerPage">The number of tracks per page. Optional. Defaults to 10.</param>
[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
public record GetMostPlayedRequest(
int? CurrentPage,
int? PerPage
);
@@ -0,0 +1,16 @@
#region ========================================================================= USING =====================================================================================
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.PlayHistory;
/// <summary>
/// Represents a request for getting a page of the recently played tracks of the current user.
/// </summary>
/// <param name="CurrentPage">The one based page of tracks to return. Optional. Defaults to 1.</param>
/// <param name="PerPage">The number of tracks per page. Optional. Defaults to 10.</param>
[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
public record GetRecentlyPlayedRequest(
int? CurrentPage,
int? PerPage
);
@@ -0,0 +1,17 @@
namespace Lumina.Presentation.Web.Common.Routes;
/// <summary>
/// Class for the collection of remote API routes called by this Web application.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the music play statistics endpoints of the remote API.
/// </summary>
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";
}
}
@@ -0,0 +1,18 @@
namespace Lumina.Presentation.Web.Common.Routes;
/// <summary>
/// Class for the collection of routes defined in the Web application.
/// </summary>
public static partial class WebRoutes
{
/// <summary>
/// Routes for the library statistics pages.
/// </summary>
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";
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/{culture}/library/statistics/api-get-most-played</c> route.
/// </summary>
public class GetMostPlayedEndpoint : BaseEndpoint<GetMostPlayedRequest, IResult>
{
private const int DEFAULT_PAGE_SIZE = 10;
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="GetMostPlayedEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public GetMostPlayedEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.LibraryStatistics.GET_MOST_PLAYED);
DontAutoTag();
Options(options => options.WithTags("Statistics"));
}
/// <summary>
/// Retrieves a page of the most played tracks of the current user.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<PlayedTrackDto> mostPlayed = await _apiHttpClient.GetAsync<PaginatedDto<PlayedTrackDto>>(url, cancellationToken).ConfigureAwait(false);
return JsonSuccess(mostPlayed);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetMostPlayedEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetMostPlayedEndpointSummary : Summary<GetMostPlayedEndpoint, GetMostPlayedRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetMostPlayedEndpointSummary"/> class.
/// </summary>
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<SuccessResponse<PaginatedDto<PlayedTrackDto>>>(response => response.IsSuccess, "Whether the operation succeeded.");
ResponseParam<PaginatedDto<PlayedTrackDto>>(response => response.Data, "The most played tracks of the requested page, ordered by counted plays, listened duration, last activity, and track Id.");
ResponseParam<PaginatedDto<PlayedTrackDto>>(response => response.CurrentPage, "The current page number.");
ResponseParam<PaginatedDto<PlayedTrackDto>>(response => response.PerPage, "The number of tracks retrieved per page.");
ResponseParam<PaginatedDto<PlayedTrackDto>>(response => response.Count, "The total number of tracks that match the filters.");
ResponseParam<PaginatedDto<PlayedTrackDto>>(response => response.NumberOfPages, "The total number of pages.");
ResponseParam<PlayedTrackDto>(response => response.TrackId, "The Id of the track.");
ResponseParam<PlayedTrackDto>(response => response.LibraryId, "The Id of the media library that contains the track.");
ResponseParam<PlayedTrackDto>(response => response.AlbumId, "The Id of the album that contains the track.");
ResponseParam<PlayedTrackDto>(response => response.ArtistId, "The Id of the artist that produced the track.");
ResponseParam<PlayedTrackDto>(response => response.Title, "The title of the track, if it still exists and the user can access its library.");
ResponseParam<PlayedTrackDto>(response => response.AlbumTitle, "The title of the album that contains the track, if available.");
ResponseParam<PlayedTrackDto>(response => response.ArtistName, "The name of the artist that produced the track, if available.");
ResponseParam<PlayedTrackDto>(response => response.CoverPath, "The path of the cover art of the album, if available.");
ResponseParam<PlayedTrackDto>(response => response.LastPlayedOnUtc, "The date and time of the last recorded activity of the track's most recent play.");
ResponseParam<PlayedTrackDto>(response => response.PlayCount, "The number of plays of the track that count as plays.");
ResponseParam<PlayedTrackDto>(response => response.CompletedPlayCount, "The number of plays of the track that completed.");
ResponseParam<PlayedTrackDto>(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<PaginatedDto<PlayedTrackDto>>(true, new PaginatedDto<PlayedTrackDto>(
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))
);
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/{culture}/library/statistics/api-get-music-play-statistics</c> route.
/// </summary>
public class GetMusicPlayStatisticsEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="GetMusicPlayStatisticsEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public GetMusicPlayStatisticsEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.LibraryStatistics.GET_MUSIC_PLAY_STATISTICS);
DontAutoTag();
Options(options => options.WithTags("Statistics"));
}
/// <summary>
/// Retrieves the listening statistics of the current user.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<MusicPlayStatisticsDto>(ApiRoutes.PlayStatistics.GET_MUSIC_PLAY_STATISTICS, cancellationToken).ConfigureAwait(false);
return JsonSuccess(statistics);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetMusicPlayStatisticsEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetMusicPlayStatisticsEndpointSummary : Summary<GetMusicPlayStatisticsEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetMusicPlayStatisticsEndpointSummary"/> class.
/// </summary>
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<SuccessResponse<MusicPlayStatisticsDto>>(response => response.IsSuccess, "Whether the operation succeeded.");
ResponseParam<MusicPlayStatisticsDto>(response => response.TotalListeningDurationInSeconds, "The total duration the user listened to, over every recorded play, in seconds.");
ResponseParam<MusicPlayStatisticsDto>(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<MusicPlayStatisticsDto>(response => response.CompletedPlayCount, "The number of recorded plays that completed.");
ResponseParam<MusicPlayStatisticsDto>(response => response.StoppedPlayCount, "The number of recorded plays that stopped before the track completed and count as plays.");
ResponseParam<MusicPlayStatisticsDto>(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<MusicPlayStatisticsDto>(true, new MusicPlayStatisticsDto(
TotalListeningDurationInSeconds: 93840.5,
TotalPlayCount: 512,
CompletedPlayCount: 388,
StoppedPlayCount: 124,
CompletionRate: 0.7578125))
);
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/{culture}/library/statistics/api-get-recently-played</c> route.
/// </summary>
public class GetRecentlyPlayedEndpoint : BaseEndpoint<GetRecentlyPlayedRequest, IResult>
{
private const int DEFAULT_PAGE_SIZE = 10;
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="GetRecentlyPlayedEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public GetRecentlyPlayedEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.LibraryStatistics.GET_RECENTLY_PLAYED);
DontAutoTag();
Options(options => options.WithTags("Statistics"));
}
/// <summary>
/// Retrieves a page of the recently played tracks of the current user.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<PlayedTrackDto> recentlyPlayed = await _apiHttpClient.GetAsync<PaginatedDto<PlayedTrackDto>>(url, cancellationToken).ConfigureAwait(false);
return JsonSuccess(recentlyPlayed);
}
}
@@ -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;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetRecentlyPlayedEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetRecentlyPlayedEndpointSummary : Summary<GetRecentlyPlayedEndpoint, GetRecentlyPlayedRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetRecentlyPlayedEndpointSummary"/> class.
/// </summary>
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<SuccessResponse<PaginatedDto<PlayedTrackDto>>>(response => response.IsSuccess, "Whether the operation succeeded.");
ResponseParam<PaginatedDto<PlayedTrackDto>>(response => response.Data, "The recently played tracks of the requested page, from the most recently played.");
ResponseParam<PaginatedDto<PlayedTrackDto>>(response => response.CurrentPage, "The current page number.");
ResponseParam<PaginatedDto<PlayedTrackDto>>(response => response.PerPage, "The number of tracks retrieved per page.");
ResponseParam<PaginatedDto<PlayedTrackDto>>(response => response.Count, "The total number of tracks that match the filters.");
ResponseParam<PaginatedDto<PlayedTrackDto>>(response => response.NumberOfPages, "The total number of pages.");
ResponseParam<PlayedTrackDto>(response => response.TrackId, "The Id of the track.");
ResponseParam<PlayedTrackDto>(response => response.LibraryId, "The Id of the media library that contains the track.");
ResponseParam<PlayedTrackDto>(response => response.AlbumId, "The Id of the album that contains the track.");
ResponseParam<PlayedTrackDto>(response => response.ArtistId, "The Id of the artist that produced the track.");
ResponseParam<PlayedTrackDto>(response => response.Title, "The title of the track, if it still exists and the user can access its library.");
ResponseParam<PlayedTrackDto>(response => response.AlbumTitle, "The title of the album that contains the track, if available.");
ResponseParam<PlayedTrackDto>(response => response.ArtistName, "The name of the artist that produced the track, if available.");
ResponseParam<PlayedTrackDto>(response => response.CoverPath, "The path of the cover art of the album, if available.");
ResponseParam<PlayedTrackDto>(response => response.LastPlayedOnUtc, "The date and time of the last recorded activity of the track's most recent play.");
ResponseParam<PlayedTrackDto>(response => response.PlayCount, "The number of plays of the track that count as plays.");
ResponseParam<PlayedTrackDto>(response => response.CompletedPlayCount, "The number of plays of the track that completed.");
ResponseParam<PlayedTrackDto>(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<PaginatedDto<PlayedTrackDto>>(true, new PaginatedDto<PlayedTrackDto>(
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))
);
}
}
@@ -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;
/// <summary>
/// API endpoint for the <c>/{culture}/library/statistics</c> route.
/// </summary>
public class StatisticsIndexViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
// 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;
/// <summary>
/// Initializes a new instance of the <see cref="StatisticsIndexViewEndpoint"/> class.
/// </summary>
/// <param name="urlService">Injected service for generating URLs from action and controller names, with localization.</param>
/// <param name="themePageRenderer">Injected service for rendering themed pages.</param>
/// <param name="stringLocalizerFactory">Injected factory used to create the localizer of the view resources.</param>
public StatisticsIndexViewEndpoint(IUrlService urlService, ThemePageRenderer themePageRenderer, IStringLocalizerFactory stringLocalizerFactory)
{
_urlService = urlService;
_themePageRenderer = themePageRenderer;
_localizer = stringLocalizerFactory.Create(VIEW_RESOURCE_BASE_NAME, VIEW_RESOURCE_LOCATION);
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.LibraryStatistics.INDEX);
DontAutoTag();
Options(options => options.WithTags("Statistics"));
}
/// <summary>
/// Displays the statistics of the current user, rendered by the active theme with a fallback to the Razor view.
/// </summary>
/// <param name="request">The request object.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> 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<string, object?>
{
["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<ThemePageRenderResultDto> sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false);
if (sectionResult.IsFailure)
return View("/Core/Views/Library/Statistics/Index.cshtml", viewData: new Dictionary<string, object?> { ["Title"] = title });
return View("/Core/Views/Shared/_ThemedView.cshtml", new ThemeViewDto(sectionResult.Value.Content, sectionResult.Value.Script), new Dictionary<string, object?> { ["Title"] = title });
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Library.Statistics.Index;
/// <summary>
/// Class used for providing a textual description for the <see cref="StatisticsIndexViewEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class StatisticsIndexViewEndpointSummary : Summary<StatisticsIndexViewEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="StatisticsIndexViewEndpointSummary"/> class.
/// </summary>
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.");
}
}
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>الإحصائيات</value>
</data>
<data name="TotalListeningTime" xml:space="preserve">
<value>إجمالي وقت الاستماع</value>
</data>
<data name="TotalPlays" xml:space="preserve">
<value>مرات التشغيل</value>
</data>
<data name="CompletedPlays" xml:space="preserve">
<value>مرات التشغيل المكتملة</value>
</data>
<data name="CompletionRate" xml:space="preserve">
<value>معدل الإكمال</value>
</data>
<data name="RecentlyPlayed" xml:space="preserve">
<value>شُغّل مؤخراً</value>
</data>
<data name="MostPlayed" xml:space="preserve">
<value>الأكثر تشغيلاً</value>
</data>
<data name="NoPlaysYet" xml:space="preserve">
<value>لا توجد مرات تشغيل محتسبة بعد.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>هذا المقطع لم يعد متاحاً.</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>تعذر تحميل الإحصائيات.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>إعادة المحاولة</value>
</data>
<data name="Plays" xml:space="preserve">
<value>مرات تشغيل</value>
</data>
<data name="Completed" xml:space="preserve">
<value>مكتملة</value>
</data>
<data name="LastPlayed" xml:space="preserve">
<value>آخر تشغيل</value>
</data>
<data name="PlayTrack" xml:space="preserve">
<value>تشغيل المقطع</value>
</data>
<data name="AddToPlaylist" xml:space="preserve">
<value>إضافة إلى قائمة التشغيل</value>
</data>
<data name="HoursShort" xml:space="preserve">
<value>س</value>
</data>
<data name="MinutesShort" xml:space="preserve">
<value>د</value>
</data>
<data name="SecondsShort" xml:space="preserve">
<value>ث</value>
</data>
</root>
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Statistik</value>
</data>
<data name="TotalListeningTime" xml:space="preserve">
<value>Gesamte Hörzeit</value>
</data>
<data name="TotalPlays" xml:space="preserve">
<value>Wiedergaben</value>
</data>
<data name="CompletedPlays" xml:space="preserve">
<value>Abgeschlossene Wiedergaben</value>
</data>
<data name="CompletionRate" xml:space="preserve">
<value>Abschlussrate</value>
</data>
<data name="RecentlyPlayed" xml:space="preserve">
<value>Zuletzt gehört</value>
</data>
<data name="MostPlayed" xml:space="preserve">
<value>Meistgehört</value>
</data>
<data name="NoPlaysYet" xml:space="preserve">
<value>Es gibt noch keine gezählten Wiedergaben.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>Dieser Titel ist nicht mehr verfügbar.</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>Die Statistik konnte nicht geladen werden.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Wiederholen</value>
</data>
<data name="Plays" xml:space="preserve">
<value>Wiedergaben</value>
</data>
<data name="Completed" xml:space="preserve">
<value>abgeschlossen</value>
</data>
<data name="LastPlayed" xml:space="preserve">
<value>Zuletzt gehört</value>
</data>
<data name="PlayTrack" xml:space="preserve">
<value>Titel abspielen</value>
</data>
<data name="AddToPlaylist" xml:space="preserve">
<value>Zu Wiedergabeliste hinzufügen</value>
</data>
<data name="HoursShort" xml:space="preserve">
<value>h</value>
</data>
<data name="MinutesShort" xml:space="preserve">
<value>m</value>
</data>
<data name="SecondsShort" xml:space="preserve">
<value>s</value>
</data>
</root>
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Statistics</value>
</data>
<data name="TotalListeningTime" xml:space="preserve">
<value>Total listening time</value>
</data>
<data name="TotalPlays" xml:space="preserve">
<value>Plays</value>
</data>
<data name="CompletedPlays" xml:space="preserve">
<value>Completed plays</value>
</data>
<data name="CompletionRate" xml:space="preserve">
<value>Completion rate</value>
</data>
<data name="RecentlyPlayed" xml:space="preserve">
<value>Recently played</value>
</data>
<data name="MostPlayed" xml:space="preserve">
<value>Most played</value>
</data>
<data name="NoPlaysYet" xml:space="preserve">
<value>There are no counted plays yet.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>This track is no longer available.</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>The statistics could not be loaded.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Retry</value>
</data>
<data name="Plays" xml:space="preserve">
<value>plays</value>
</data>
<data name="Completed" xml:space="preserve">
<value>completed</value>
</data>
<data name="LastPlayed" xml:space="preserve">
<value>Last played</value>
</data>
<data name="PlayTrack" xml:space="preserve">
<value>Play track</value>
</data>
<data name="AddToPlaylist" xml:space="preserve">
<value>Add to playlist</value>
</data>
<data name="HoursShort" xml:space="preserve">
<value>h</value>
</data>
<data name="MinutesShort" xml:space="preserve">
<value>m</value>
</data>
<data name="SecondsShort" xml:space="preserve">
<value>s</value>
</data>
</root>
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Estadísticas</value>
</data>
<data name="TotalListeningTime" xml:space="preserve">
<value>Tiempo total de escucha</value>
</data>
<data name="TotalPlays" xml:space="preserve">
<value>Reproducciones</value>
</data>
<data name="CompletedPlays" xml:space="preserve">
<value>Reproducciones completadas</value>
</data>
<data name="CompletionRate" xml:space="preserve">
<value>Tasa de finalización</value>
</data>
<data name="RecentlyPlayed" xml:space="preserve">
<value>Reproducido recientemente</value>
</data>
<data name="MostPlayed" xml:space="preserve">
<value>Más reproducido</value>
</data>
<data name="NoPlaysYet" xml:space="preserve">
<value>Aún no hay reproducciones contabilizadas.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>Esta pista ya no está disponible.</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>No se pudieron cargar las estadísticas.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Reintentar</value>
</data>
<data name="Plays" xml:space="preserve">
<value>reproducciones</value>
</data>
<data name="Completed" xml:space="preserve">
<value>completadas</value>
</data>
<data name="LastPlayed" xml:space="preserve">
<value>Última reproducción</value>
</data>
<data name="PlayTrack" xml:space="preserve">
<value>Reproducir pista</value>
</data>
<data name="AddToPlaylist" xml:space="preserve">
<value>Añadir a la lista de reproducción</value>
</data>
<data name="HoursShort" xml:space="preserve">
<value>h</value>
</data>
<data name="MinutesShort" xml:space="preserve">
<value>min</value>
</data>
<data name="SecondsShort" xml:space="preserve">
<value>s</value>
</data>
</root>
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Statistiques</value>
</data>
<data name="TotalListeningTime" xml:space="preserve">
<value>Temps d'écoute total</value>
</data>
<data name="TotalPlays" xml:space="preserve">
<value>Écoutes</value>
</data>
<data name="CompletedPlays" xml:space="preserve">
<value>Écoutes terminées</value>
</data>
<data name="CompletionRate" xml:space="preserve">
<value>Taux d'achèvement</value>
</data>
<data name="RecentlyPlayed" xml:space="preserve">
<value>Écoutés récemment</value>
</data>
<data name="MostPlayed" xml:space="preserve">
<value>Les plus écoutés</value>
</data>
<data name="NoPlaysYet" xml:space="preserve">
<value>Aucune écoute comptabilisée pour le moment.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>Ce morceau n'est plus disponible.</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>Les statistiques n'ont pas pu être chargées.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Réessayer</value>
</data>
<data name="Plays" xml:space="preserve">
<value>écoutes</value>
</data>
<data name="Completed" xml:space="preserve">
<value>terminées</value>
</data>
<data name="LastPlayed" xml:space="preserve">
<value>Dernière écoute</value>
</data>
<data name="PlayTrack" xml:space="preserve">
<value>Lire le morceau</value>
</data>
<data name="AddToPlaylist" xml:space="preserve">
<value>Ajouter à la playlist</value>
</data>
<data name="HoursShort" xml:space="preserve">
<value>h</value>
</data>
<data name="MinutesShort" xml:space="preserve">
<value>min</value>
</data>
<data name="SecondsShort" xml:space="preserve">
<value>s</value>
</data>
</root>
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Statistiche</value>
</data>
<data name="TotalListeningTime" xml:space="preserve">
<value>Tempo di ascolto totale</value>
</data>
<data name="TotalPlays" xml:space="preserve">
<value>Riproduzioni</value>
</data>
<data name="CompletedPlays" xml:space="preserve">
<value>Riproduzioni completate</value>
</data>
<data name="CompletionRate" xml:space="preserve">
<value>Tasso di completamento</value>
</data>
<data name="RecentlyPlayed" xml:space="preserve">
<value>Riprodotti di recente</value>
</data>
<data name="MostPlayed" xml:space="preserve">
<value>Più riprodotti</value>
</data>
<data name="NoPlaysYet" xml:space="preserve">
<value>Non ci sono ancora riproduzioni conteggiate.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>Questo brano non è più disponibile.</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>Impossibile caricare le statistiche.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Riprova</value>
</data>
<data name="Plays" xml:space="preserve">
<value>riproduzioni</value>
</data>
<data name="Completed" xml:space="preserve">
<value>completate</value>
</data>
<data name="LastPlayed" xml:space="preserve">
<value>Ultima riproduzione</value>
</data>
<data name="PlayTrack" xml:space="preserve">
<value>Riproduci brano</value>
</data>
<data name="AddToPlaylist" xml:space="preserve">
<value>Aggiungi alla playlist</value>
</data>
<data name="HoursShort" xml:space="preserve">
<value>h</value>
</data>
<data name="MinutesShort" xml:space="preserve">
<value>min</value>
</data>
<data name="SecondsShort" xml:space="preserve">
<value>s</value>
</data>
</root>
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>統計</value>
</data>
<data name="TotalListeningTime" xml:space="preserve">
<value>合計再生時間</value>
</data>
<data name="TotalPlays" xml:space="preserve">
<value>再生回数</value>
</data>
<data name="CompletedPlays" xml:space="preserve">
<value>最後まで再生した回数</value>
</data>
<data name="CompletionRate" xml:space="preserve">
<value>完了率</value>
</data>
<data name="RecentlyPlayed" xml:space="preserve">
<value>最近再生した曲</value>
</data>
<data name="MostPlayed" xml:space="preserve">
<value>よく再生する曲</value>
</data>
<data name="NoPlaysYet" xml:space="preserve">
<value>集計対象の再生はまだありません。</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>この曲はもう利用できません。</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>統計を読み込めませんでした。</value>
</data>
<data name="Retry" xml:space="preserve">
<value>再試行</value>
</data>
<data name="Plays" xml:space="preserve">
<value>回</value>
</data>
<data name="Completed" xml:space="preserve">
<value>回完了</value>
</data>
<data name="LastPlayed" xml:space="preserve">
<value>最終再生</value>
</data>
<data name="PlayTrack" xml:space="preserve">
<value>曲を再生</value>
</data>
<data name="AddToPlaylist" xml:space="preserve">
<value>プレイリストに追加</value>
</data>
<data name="HoursShort" xml:space="preserve">
<value>時間</value>
</data>
<data name="MinutesShort" xml:space="preserve">
<value>分</value>
</data>
<data name="SecondsShort" xml:space="preserve">
<value>秒</value>
</data>
</root>
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Statistics</value>
</data>
<data name="TotalListeningTime" xml:space="preserve">
<value>Total listening time</value>
</data>
<data name="TotalPlays" xml:space="preserve">
<value>Plays</value>
</data>
<data name="CompletedPlays" xml:space="preserve">
<value>Completed plays</value>
</data>
<data name="CompletionRate" xml:space="preserve">
<value>Completion rate</value>
</data>
<data name="RecentlyPlayed" xml:space="preserve">
<value>Recently played</value>
</data>
<data name="MostPlayed" xml:space="preserve">
<value>Most played</value>
</data>
<data name="NoPlaysYet" xml:space="preserve">
<value>There are no counted plays yet.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>This track is no longer available.</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>The statistics could not be loaded.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Retry</value>
</data>
<data name="Plays" xml:space="preserve">
<value>plays</value>
</data>
<data name="Completed" xml:space="preserve">
<value>completed</value>
</data>
<data name="LastPlayed" xml:space="preserve">
<value>Last played</value>
</data>
<data name="PlayTrack" xml:space="preserve">
<value>Play track</value>
</data>
<data name="AddToPlaylist" xml:space="preserve">
<value>Add to playlist</value>
</data>
<data name="HoursShort" xml:space="preserve">
<value>h</value>
</data>
<data name="MinutesShort" xml:space="preserve">
<value>m</value>
</data>
<data name="SecondsShort" xml:space="preserve">
<value>s</value>
</data>
</root>
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Statistici</value>
</data>
<data name="TotalListeningTime" xml:space="preserve">
<value>Timp total de ascultare</value>
</data>
<data name="TotalPlays" xml:space="preserve">
<value>Redări</value>
</data>
<data name="CompletedPlays" xml:space="preserve">
<value>Redări finalizate</value>
</data>
<data name="CompletionRate" xml:space="preserve">
<value>Rată de finalizare</value>
</data>
<data name="RecentlyPlayed" xml:space="preserve">
<value>Ascultate recent</value>
</data>
<data name="MostPlayed" xml:space="preserve">
<value>Cele mai ascultate</value>
</data>
<data name="NoPlaysYet" xml:space="preserve">
<value>Nu există încă redări contorizate.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>Această piesă nu mai este disponibilă.</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>Statisticile nu au putut fi încărcate.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Reîncearcă</value>
</data>
<data name="Plays" xml:space="preserve">
<value>redări</value>
</data>
<data name="Completed" xml:space="preserve">
<value>finalizate</value>
</data>
<data name="LastPlayed" xml:space="preserve">
<value>Ultima redare</value>
</data>
<data name="PlayTrack" xml:space="preserve">
<value>Redă piesa</value>
</data>
<data name="AddToPlaylist" xml:space="preserve">
<value>Adaugă la playlist</value>
</data>
<data name="HoursShort" xml:space="preserve">
<value>h</value>
</data>
<data name="MinutesShort" xml:space="preserve">
<value>min</value>
</data>
<data name="SecondsShort" xml:space="preserve">
<value>s</value>
</data>
</root>
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>Статистика</value>
</data>
<data name="TotalListeningTime" xml:space="preserve">
<value>Загальний час прослуховування</value>
</data>
<data name="TotalPlays" xml:space="preserve">
<value>Відтворення</value>
</data>
<data name="CompletedPlays" xml:space="preserve">
<value>Завершені відтворення</value>
</data>
<data name="CompletionRate" xml:space="preserve">
<value>Відсоток завершення</value>
</data>
<data name="RecentlyPlayed" xml:space="preserve">
<value>Нещодавно відтворені</value>
</data>
<data name="MostPlayed" xml:space="preserve">
<value>Найчастіше відтворювані</value>
</data>
<data name="NoPlaysYet" xml:space="preserve">
<value>Ще немає зарахованих відтворень.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>Цей трек більше недоступний.</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>Не вдалося завантажити статистику.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Повторити</value>
</data>
<data name="Plays" xml:space="preserve">
<value>відтворень</value>
</data>
<data name="Completed" xml:space="preserve">
<value>завершено</value>
</data>
<data name="LastPlayed" xml:space="preserve">
<value>Останнє відтворення</value>
</data>
<data name="PlayTrack" xml:space="preserve">
<value>Відтворити трек</value>
</data>
<data name="AddToPlaylist" xml:space="preserve">
<value>Додати до плейлиста</value>
</data>
<data name="HoursShort" xml:space="preserve">
<value>год</value>
</data>
<data name="MinutesShort" xml:space="preserve">
<value>хв</value>
</data>
<data name="SecondsShort" xml:space="preserve">
<value>с</value>
</data>
</root>
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Title" xml:space="preserve">
<value>统计</value>
</data>
<data name="TotalListeningTime" xml:space="preserve">
<value>总收听时间</value>
</data>
<data name="TotalPlays" xml:space="preserve">
<value>播放次数</value>
</data>
<data name="CompletedPlays" xml:space="preserve">
<value>完整播放次数</value>
</data>
<data name="CompletionRate" xml:space="preserve">
<value>完成率</value>
</data>
<data name="RecentlyPlayed" xml:space="preserve">
<value>最近播放</value>
</data>
<data name="MostPlayed" xml:space="preserve">
<value>最常播放</value>
</data>
<data name="NoPlaysYet" xml:space="preserve">
<value>还没有计入的播放。</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>此曲目已不可用。</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>无法加载统计。</value>
</data>
<data name="Retry" xml:space="preserve">
<value>重试</value>
</data>
<data name="Plays" xml:space="preserve">
<value>次播放</value>
</data>
<data name="Completed" xml:space="preserve">
<value>次完整播放</value>
</data>
<data name="LastPlayed" xml:space="preserve">
<value>上次播放</value>
</data>
<data name="PlayTrack" xml:space="preserve">
<value>播放曲目</value>
</data>
<data name="AddToPlaylist" xml:space="preserve">
<value>添加到播放列表</value>
</data>
<data name="HoursShort" xml:space="preserve">
<value>小时</value>
</data>
<data name="MinutesShort" xml:space="preserve">
<value>分钟</value>
</data>
<data name="SecondsShort" xml:space="preserve">
<value>秒</value>
</data>
</root>
@@ -225,4 +225,7 @@
<data name="Favorites" xml:space="preserve">
<value>المفضلة</value>
</data>
<data name="Statistics" xml:space="preserve">
<value>الإحصائيات</value>
</data>
</root>
@@ -225,4 +225,7 @@
<data name="Favorites" xml:space="preserve">
<value>Favoriten</value>
</data>
<data name="Statistics" xml:space="preserve">
<value>Statistik</value>
</data>
</root>
@@ -225,4 +225,7 @@
<data name="Favorites" xml:space="preserve">
<value>Favorites</value>
</data>
<data name="Statistics" xml:space="preserve">
<value>Statistics</value>
</data>
</root>
@@ -225,4 +225,7 @@
<data name="Favorites" xml:space="preserve">
<value>Favoritos</value>
</data>
<data name="Statistics" xml:space="preserve">
<value>Estadísticas</value>
</data>
</root>
@@ -225,4 +225,7 @@
<data name="Favorites" xml:space="preserve">
<value>Favoris</value>
</data>
<data name="Statistics" xml:space="preserve">
<value>Statistiques</value>
</data>
</root>
@@ -225,4 +225,7 @@
<data name="Favorites" xml:space="preserve">
<value>Preferiti</value>
</data>
<data name="Statistics" xml:space="preserve">
<value>Statistiche</value>
</data>
</root>
@@ -225,4 +225,7 @@
<data name="Favorites" xml:space="preserve">
<value>お気に入り</value>
</data>
<data name="Statistics" xml:space="preserve">
<value>統計</value>
</data>
</root>
@@ -225,4 +225,7 @@
<data name="Favorites" xml:space="preserve">
<value>Favorites</value>
</data>
<data name="Statistics" xml:space="preserve">
<value>Statistics</value>
</data>
</root>
@@ -225,4 +225,7 @@
<data name="Favorites" xml:space="preserve">
<value>Favorite</value>
</data>
<data name="Statistics" xml:space="preserve">
<value>Statistici</value>
</data>
</root>
@@ -225,4 +225,7 @@
<data name="Favorites" xml:space="preserve">
<value>Улюблене</value>
</data>
<data name="Statistics" xml:space="preserve">
<value>Статистика</value>
</data>
</root>
@@ -225,4 +225,7 @@
<data name="Favorites" xml:space="preserve">
<value>收藏夹</value>
</data>
<data name="Statistics" xml:space="preserve">
<value>统计</value>
</data>
</root>
@@ -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;
@@ -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<string, string>
{
["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() }
};
}
<div class="cotton-candy">
<div style="display: grid; grid-template-rows: auto 1fr;">
<div style="min-height: 1rem;"></div>
<div class="pl-10 pr-10 pb-10">
<div class="text-center">
<h1 class="text-light-two engraved-title">@_localizer["Title"]</h1>
</div>
<!-- Summary totals. -->
<div class="statistics-summary" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 1rem; margin: 1.5rem 0;">
<div class="statistics-summary-tile">
<span class="text-disabled form-label">@_localizer["TotalListeningTime"]</span>
<strong id="statistics-total-listening-time" class="text-light-two" aria-live="polite">-</strong>
</div>
<div class="statistics-summary-tile">
<span class="text-disabled form-label">@_localizer["TotalPlays"]</span>
<strong id="statistics-total-plays" class="text-light-two" aria-live="polite">-</strong>
</div>
<div class="statistics-summary-tile">
<span class="text-disabled form-label">@_localizer["CompletedPlays"]</span>
<strong id="statistics-completed-plays" class="text-light-two" aria-live="polite">-</strong>
</div>
<div class="statistics-summary-tile">
<span class="text-disabled form-label">@_localizer["CompletionRate"]</span>
<strong id="statistics-completion-rate" class="text-light-two" aria-live="polite">-</strong>
</div>
</div>
<!-- Recently played tracks. -->
<h2 class="text-light-two">@_localizer["RecentlyPlayed"]</h2>
<div id="recently-played-list" class="statistics-track-list"></div>
<!-- Most played tracks. -->
<h2 class="text-light-two">@_localizer["MostPlayed"]</h2>
<div id="most-played-list" class="statistics-track-list"></div>
<p id="statistics-empty-state" class="hidden text-light-two text-center" aria-live="polite" aria-atomic="true" tabindex="-1">@_localizer["NoPlaysYet"]</p>
<p id="statistics-load-failed" class="hidden text-light-two text-center" aria-live="polite" aria-atomic="true" tabindex="-1">@_localizer["LoadFailed"]</p>
<div class="form-row">
<button id="retry-statistics-button" type="button" class="confirm-button hidden">@_localizer["Retry"]</button>
</div>
</div>
</div>
</div>
@section Scripts {
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls. site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
const strings = @Html.Raw(JsonSerializer.Serialize(strings, jsonOptions));
const getRecentlyPlayedUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_RECENTLY_PLAYED)';
const getMostPlayedUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_MOST_PLAYED)';
const getStatisticsUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryStatistics.GET_MUSIC_PLAY_STATISTICS)';
const trackUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Music.TRACK, new { artistId = default(Guid), albumId = default(Guid), trackId = default(Guid) })';
const culture = '@CultureInfo.CurrentUICulture.Name';
const EMPTY_GUID = '00000000-0000-0000-0000-000000000000';
const totalListeningTimeValue = document.getElementById('statistics-total-listening-time');
const totalPlaysValue = document.getElementById('statistics-total-plays');
const completedPlaysValue = document.getElementById('statistics-completed-plays');
const completionRateValue = document.getElementById('statistics-completion-rate');
const recentlyPlayedList = document.getElementById('recently-played-list');
const mostPlayedList = document.getElementById('most-played-list');
const emptyState = document.getElementById('statistics-empty-state');
const loadFailedMessage = document.getElementById('statistics-load-failed');
const retryButton = document.getElementById('retry-statistics-button');
let isInitialized = false;
let isLoading = false;
let hasLoaded = false;
let hasLoadFailed = false;
let renderedTrackCount = 0;
function isKnownId(id) {
return typeof id === 'string' && id !== '' && id !== EMPTY_GUID;
}
function buildTrackUrl(track) {
if (!track.title || !isKnownId(track.libraryId) || !isKnownId(track.artistId) || !isKnownId(track.albumId) || !isKnownId(track.trackId))
return '';
return trackUrlTemplate
.replace(`/${EMPTY_GUID}`, `/${track.artistId}`)
.replace(`/${EMPTY_GUID}`, `/${track.albumId}`)
.replace(`/${EMPTY_GUID}`, `/${track.trackId}`) + `?libraryId=${encodeURIComponent(track.libraryId)}`;
}
// Formats a duration in seconds as hours and minutes, minutes and seconds, or seconds, using the page's short unit suffixes.
function formatListeningTime(totalSeconds) {
const total = Math.max(0, Math.round(Number(totalSeconds) || 0));
const hours = Math.floor(total / 3600);
const minutes = Math.floor((total % 3600) / 60);
const seconds = total % 60;
if (hours > 0)
return `${hours}${strings.hoursShort} ${minutes}${strings.minutesShort}`;
if (minutes > 0)
return `${minutes}${strings.minutesShort} ${seconds}${strings.secondsShort}`;
return `${seconds}${strings.secondsShort}`;
}
// The API stores the last activity time in UTC, but the persistence medium (SQLite) stores it as plain text, so the JSON the browser
// receives carries no time zone offset (no "Z"). Without an explicit offset, new Date(...) interprets the value as a local time, which
// shifts every value by the local UTC offset. Appending "Z" keeps those values anchored to UTC, where they were recorded.
function parseUtcTimestamp(timestampValue) {
if (!timestampValue)
return null;
const value = String(timestampValue);
const hasOffset = /(?:Z|[+-]\d{2}:\d{2})$/i.test(value);
return new Date(hasOffset ? value : value + 'Z');
}
// Formats a date and time in the language of the page, falling back to the browser's own format when the culture is not available.
function formatDateTime(value) {
const date = parseUtcTimestamp(value);
if (!date || Number.isNaN(date.getTime()))
return '';
try {
return new Intl.DateTimeFormat(culture, { dateStyle: 'medium', timeStyle: 'short' }).format(date);
} catch {
return date.toLocaleString();
}
}
function formatPercentage(value) {
const fraction = Math.max(0, Math.min(1, Number(value) || 0));
try {
return new Intl.NumberFormat(culture, { style: 'percent', maximumFractionDigits: 1 }).format(fraction);
} catch {
return `${Math.round(fraction * 100)}%`;
}
}
function createCover(track) {
const image = document.createElement('img');
image.className = 'statistics-track-cover';
image.src = track.coverPath
? `${globalConfiguration.serverBasePath}${track.coverPath}`
: '/images/ui/music-placeholder.svg';
image.alt = '';
image.style.width = '48px';
image.style.height = '48px';
image.style.objectFit = 'cover';
image.style.borderRadius = '4px';
image.style.flexShrink = '0';
return image;
}
function createPlayButton(track) {
const button = document.createElement('button');
button.type = 'button';
button.className = 'confirm-button statistics-action-button';
button.setAttribute('data-audio-player-play', '');
button.dataset.libraryId = track.libraryId;
button.dataset.trackId = track.trackId;
button.dataset.albumId = track.albumId;
button.dataset.artistId = track.artistId;
button.dataset.title = track.title || '';
button.dataset.albumTitle = track.albumTitle || '';
if (track.coverPath)
button.dataset.coverArtPath = track.coverPath;
// The button carries no visible text, so its accessible name names both the action and the track it plays.
const label = `${strings.playTrack}: ${track.title || ''}`;
button.setAttribute('aria-label', label);
button.title = label;
button.textContent = '\u25B6';
return button;
}
// Creates the heart of a track row. The global favorites script finds it by its data attributes, hydrates its state and handles its click.
function createFavoriteToggle(track) {
const toggle = document.createElement('button');
toggle.type = 'button';
toggle.className = 'card-favorite-toggle statistics-favorite-toggle';
toggle.setAttribute('data-favorite-toggle', '');
toggle.setAttribute('data-favorite-media-kind', 'MusicTrack');
toggle.setAttribute('data-favorite-media-item-id', track.trackId);
return toggle;
}
// Creates the add to playlist action. The global playlists script opens the playlist picker from its data attributes.
function createPlaylistAddButton(track) {
const button = document.createElement('button');
button.type = 'button';
button.className = 'confirm-button statistics-action-button';
button.setAttribute('data-playlist-add', '');
button.dataset.playlistLibraryId = track.libraryId;
button.dataset.playlistTrackId = track.trackId;
button.dataset.playlistTitle = track.title || '';
const label = `${strings.addToPlaylist}: ${track.title || ''}`;
button.setAttribute('aria-label', label);
button.title = label;
button.textContent = '+';
return button;
}
// Builds the cell that describes how the track was played: its counted plays, its completed plays and when it was last active.
function createMetrics(track) {
const metrics = document.createElement('div');
metrics.className = 'statistics-track-metrics';
const counts = document.createElement('span');
counts.className = 'text-light-two';
counts.textContent = `${track.playCount} ${strings.plays} - ${track.completedPlayCount} ${strings.completed}`;
const lastPlayed = document.createElement('span');
lastPlayed.className = 'text-disabled';
lastPlayed.textContent = `${strings.lastPlayed}: ${formatDateTime(track.lastPlayedOnUtc)}`;
metrics.appendChild(counts);
metrics.appendChild(lastPlayed);
return metrics;
}
function createTrackRow(track, rank) {
const row = document.createElement('div');
row.className = 'statistics-track-row';
row.dataset.trackId = track.trackId;
row.style.display = 'flex';
row.style.alignItems = 'center';
row.style.gap = '0.75rem';
row.style.padding = '0.5rem 0';
row.style.borderBottom = '1px solid rgba(255, 255, 255, 0.08)';
if (rank)
{
const rankLabel = document.createElement('span');
rankLabel.className = 'text-disabled';
rankLabel.style.minWidth = '1.5rem';
rankLabel.style.textAlign = 'right';
rankLabel.textContent = rank;
row.appendChild(rankLabel);
}
row.appendChild(createCover(track));
const details = document.createElement('div');
details.style.display = 'flex';
details.style.flexDirection = 'column';
details.style.flexGrow = '1';
details.style.minWidth = '0';
const trackUrl = buildTrackUrl(track);
const title = document.createElement(trackUrl ? 'a' : 'span');
title.className = trackUrl ? 'nav-link text-light-two' : 'text-light-two';
if (trackUrl)
title.href = trackUrl;
title.textContent = track.title || strings.unavailable;
title.title = title.textContent;
title.style.whiteSpace = 'nowrap';
title.style.overflow = 'hidden';
title.style.textOverflow = 'ellipsis';
details.appendChild(title);
const subtitleText = [track.artistName, track.albumTitle].filter(value => value).join(' - ');
if (subtitleText)
{
const subtitle = document.createElement('span');
subtitle.className = 'text-disabled';
subtitle.textContent = subtitleText;
subtitle.style.whiteSpace = 'nowrap';
subtitle.style.overflow = 'hidden';
subtitle.style.textOverflow = 'ellipsis';
details.appendChild(subtitle);
}
row.appendChild(details);
row.appendChild(createMetrics(track));
const actions = document.createElement('div');
actions.className = 'statistics-track-actions';
actions.style.display = 'flex';
actions.style.alignItems = 'center';
actions.style.gap = '0.25rem';
// A track that no longer exists, or whose library the user cannot access, has no display data and no play context left to describe.
if (track.title)
{
actions.appendChild(createPlayButton(track));
actions.appendChild(createFavoriteToggle(track));
actions.appendChild(createPlaylistAddButton(track));
}
row.appendChild(actions);
return row;
}
function renderTracks(container, tracks, isRanked) {
container.innerHTML = '';
tracks.forEach((track, index) => container.appendChild(createTrackRow(track, isRanked ? index + 1 : 0)));
renderedTrackCount += tracks.length;
}
function renderStatistics(statistics) {
totalListeningTimeValue.textContent = formatListeningTime(statistics.totalListeningDurationInSeconds);
totalPlaysValue.textContent = String(statistics.totalPlayCount);
completedPlaysValue.textContent = String(statistics.completedPlayCount);
completionRateValue.textContent = formatPercentage(statistics.completionRate);
}
function updateState() {
// The empty state appears only after a successful load that returned no track at all, so it never flashes while the page is loading.
emptyState.classList.toggle('hidden', !hasLoaded || hasLoadFailed || renderedTrackCount > 0);
loadFailedMessage.classList.toggle('hidden', !hasLoadFailed);
retryButton.classList.toggle('hidden', !hasLoadFailed);
retryButton.disabled = isLoading;
}
async function loadStatisticsAsync() {
if (isLoading)
return;
isLoading = true;
hasLoadFailed = false;
updateState();
const [statistics, recentlyPlayed, mostPlayed] = await Promise.all([
callApiGetAsync(getStatisticsUrl),
callApiGetAsync(`${getRecentlyPlayedUrl}?currentPage=1&perPage=10`),
callApiGetAsync(`${getMostPlayedUrl}?currentPage=1&perPage=10`)
]);
isLoading = false;
if (!statistics || !recentlyPlayed || !Array.isArray(recentlyPlayed.data) || !mostPlayed || !Array.isArray(mostPlayed.data)) {
// The API helper already reported each failure. The page keeps whatever it had rendered and offers a retry.
hasLoadFailed = true;
updateState();
return;
}
renderedTrackCount = 0;
renderStatistics(statistics);
renderTracks(recentlyPlayedList, recentlyPlayed.data, false);
renderTracks(mostPlayedList, mostPlayed.data, true);
hasLoaded = true;
hasLoadFailed = false;
bindNavigationLinks();
updateState();
}
retryButton.addEventListener('click', loadStatisticsAsync);
async function InitializeAsync() {
if (isInitialized)
return;
isInitialized = true;
await loadStatisticsAsync();
}
window.viewCleanups = window.viewCleanups || {};
window.viewCleanups['@scriptId'] = () => {
retryButton.removeEventListener('click', loadStatisticsAsync);
console.log(`Unloaded @scriptId`);
};
console.log(`Loaded @scriptId`);
</script>
}
@@ -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;
}