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.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;
}