Adds favorites and aligns playlist and favorite pagination

This commit is contained in:
BinaryAlley committed 2026-10-22 20:27:07 +03:00
1 parent 2e9f7d8496
commit 525ac1348d
193 files changed
+10944 -643

No files matched your search

@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Favorites;
using Lumina.Presentation.Web.Common.Requests.Favorites;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.AddFavorite;
/// <summary>
/// API endpoint for the <c>/{culture}/favorites/api-add-favorite</c> route.
/// </summary>
public class AddFavoriteEndpoint : BaseEndpoint<AddFavoriteRequest, IResult>
{
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="AddFavoriteEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public AddFavoriteEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.POST);
Routes(WebRoutes.Favorites.ADD_FAVORITE);
DontAutoTag();
Options(options => options.WithTags("Favorites"));
EnableAntiforgery();
}
/// <summary>
/// Marks a media item as a favorite of the current user.
/// </summary>
/// <param name="request">The request containing the kind and the Id of the media item to favorite.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(AddFavoriteRequest request, CancellationToken cancellationToken)
{
FavoriteDto favorite = await _apiHttpClient.PostAsync<FavoriteDto, AddFavoriteRequest>(ApiRoutes.Favorites.ADD_FAVORITE, request, cancellationToken).ConfigureAwait(false);
return JsonSuccess(favorite);
}
}
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Favorites;
using Lumina.Presentation.Web.Common.Enums.Favorites;
using Lumina.Presentation.Web.Common.Requests.Favorites;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.AddFavorite;
/// <summary>
/// Class used for providing a textual description for the <see cref="AddFavoriteEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class AddFavoriteEndpointSummary : Summary<AddFavoriteEndpoint, AddFavoriteRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="AddFavoriteEndpointSummary"/> class.
/// </summary>
public AddFavoriteEndpointSummary()
{
Summary = "Marks a media item as a favorite of the current user.";
Description = "Proxies the request that marks a media item as a favorite to the API server. Adding an item that is already a favorite is not an error: the existing favorite is returned.";
ExampleRequest = new AddFavoriteRequest(
MediaKind: FavoriteMediaKind.MusicTrack,
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f")
);
RequestParam(request => request.MediaKind, "The kind of the media item to favorite: MusicArtist, MusicAlbum, MusicTrack or Book. Required.");
RequestParam(request => request.MediaItemId, "The Id of the media item to favorite. Required.");
Response(200, "The media item is a favorite and the favorite is returned.",
example: new SuccessResponse<FavoriteDto>(true, new FavoriteDto(
Id: Guid.Parse("4b7a2c10-5d3e-4f68-9a1b-0c2d3e4f5a6b"),
MediaKind: FavoriteMediaKind.MusicTrack,
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
FavoritedOnUtc: new DateTime(2026, 10, 21, 9, 30, 0, DateTimeKind.Utc)))
);
}
}
@@ -0,0 +1,72 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Favorites;
using Lumina.Presentation.Web.Common.Requests.Favorites;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavoriteStatus;
/// <summary>
/// API endpoint for the <c>/{culture}/favorites/api-get-favorite-status</c> route.
/// </summary>
public class GetFavoriteStatusEndpoint : BaseEndpoint<GetFavoriteStatusRequest, IResult>
{
// The API accepts at most 100 Ids per check, so one more is forwarded to let its validator report an oversized list.
private const int MAXIMUM_FORWARDED_MEDIA_ITEM_COUNT = 101;
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public GetFavoriteStatusEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.Favorites.GET_FAVORITE_STATUS);
DontAutoTag();
Options(options => options.WithTags("Favorites"));
}
/// <summary>
/// Retrieves which of the given media items are favorites of the current user.
/// </summary>
/// <param name="request">The request containing the kind and the Ids of the media items to check.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetFavoriteStatusRequest request, CancellationToken cancellationToken)
{
// The favorites 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.
// A missing kind or Id list is left out, so that the API reports the validation error itself.
List<string> queryParameters = [];
if (request.MediaKind is not null)
queryParameters.Add($"mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}");
// The forwarded list is bounded, so the upstream URL stays bounded too.
foreach (Guid mediaItemId in (request.MediaItemIds ?? []).Take(MAXIMUM_FORWARDED_MEDIA_ITEM_COUNT))
queryParameters.Add($"mediaItemIds={mediaItemId}");
string url = queryParameters.Count == 0 ? ApiRoutes.Favorites.GET_FAVORITE_STATUS : $"{ApiRoutes.Favorites.GET_FAVORITE_STATUS}?{string.Join('&', queryParameters)}";
FavoriteStatusDto status = await _apiHttpClient.GetAsync<FavoriteStatusDto>(url, cancellationToken).ConfigureAwait(false);
return JsonSuccess(status);
}
}
@@ -0,0 +1,43 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Favorites;
using Lumina.Presentation.Web.Common.Enums.Favorites;
using Lumina.Presentation.Web.Common.Requests.Favorites;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavoriteStatus;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetFavoriteStatusEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFavoriteStatusEndpointSummary : Summary<GetFavoriteStatusEndpoint, GetFavoriteStatusRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetFavoriteStatusEndpointSummary"/> class.
/// </summary>
public GetFavoriteStatusEndpointSummary()
{
Summary = "Gets which media items are favorites of the current user.";
Description = "Proxies the request that finds out which of the given media items of one kind are favorites of the current user to the API server. The mediaItemIds query parameter is repeated, once per Id.";
ExampleRequest = new GetFavoriteStatusRequest(
MediaKind: FavoriteMediaKind.MusicTrack,
MediaItemIds:
[
Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
Guid.Parse("5a4b3c2d-1e0f-4a9b-8c7d-6e5f4a3b2c1d")
]
);
RequestParam(request => request.MediaKind, "The kind of the media items to check: MusicArtist, MusicAlbum, MusicTrack or Book. Required.");
RequestParam(request => request.MediaItemIds, "The Ids of the media items to check, from 1 to 100, sent as a repeated mediaItemIds query parameter. Required.");
Response(200, "The Ids, among the checked ones, of the media items that are favorites of the current user are returned.",
example: new SuccessResponse<FavoriteStatusDto>(true, new FavoriteStatusDto(
FavoritedMediaItemIds: [Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f")]))
);
}
}
@@ -0,0 +1,69 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Favorites;
using Lumina.Presentation.Web.Common.Requests.Favorites;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavorites;
/// <summary>
/// API endpoint for the <c>/{culture}/favorites/api-get-favorites</c> route.
/// </summary>
public class GetFavoritesEndpoint : BaseEndpoint<GetFavoritesRequest, IResult>
{
private const int DEFAULT_FAVORITE_PAGE_SIZE = 200;
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="GetFavoritesEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public GetFavoritesEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.Favorites.GET_FAVORITES);
DontAutoTag();
Options(options => options.WithTags("Favorites"));
}
/// <summary>
/// Retrieves a page of the favorites 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(GetFavoritesRequest request, CancellationToken cancellationToken)
{
// The favorites 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.
// The page bounds are normalized by the API pagination data, exactly like every other paginated collection of the application.
int currentPage = request.CurrentPage ?? 1;
int perPage = request.PerPage ?? DEFAULT_FAVORITE_PAGE_SIZE;
string url = ApiRoutes.Favorites.GET_FAVORITES + $"?currentPage={currentPage.ToString(CultureInfo.InvariantCulture)}&perPage={perPage.ToString(CultureInfo.InvariantCulture)}";
if (request.MediaKind is not null)
url += $"&mediaKind={Uri.EscapeDataString(request.MediaKind.Value.ToString())}";
PaginatedDto<FavoriteItemDto> favorites = await _apiHttpClient.GetAsync<PaginatedDto<FavoriteItemDto>>(url, cancellationToken).ConfigureAwait(false);
return JsonSuccess(favorites);
}
}
@@ -0,0 +1,58 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Favorites;
using Lumina.Presentation.Web.Common.Enums.Favorites;
using Lumina.Presentation.Web.Common.Requests.Favorites;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.GetFavorites;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetFavoritesEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetFavoritesEndpointSummary : Summary<GetFavoritesEndpoint, GetFavoritesRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetFavoritesEndpointSummary"/> class.
/// </summary>
public GetFavoritesEndpointSummary()
{
Summary = "Gets the favorites of the current user.";
Description = "Proxies the request that gets a page of the favorites of the current user, from the most recently favorited, to the API server. The currentPage and perPage query parameters select the page, and count reports the total number of favorites that match the filter. Each favorite carries the display details of its media item.";
ExampleRequest = new GetFavoritesRequest(
MediaKind: FavoriteMediaKind.MusicTrack,
CurrentPage: 1,
PerPage: 200
);
RequestParam(request => request.MediaKind, "The kind of media item to restrict the favorites to: MusicArtist, MusicAlbum, MusicTrack or Book. Optional; every kind is returned when omitted.");
RequestParam(request => request.CurrentPage, "The one based page of favorites to return. Optional; defaults to 1.");
RequestParam(request => request.PerPage, "The number of favorites per page. Optional; defaults to 200.");
Response(200, "The requested page of the favorites of the current user is returned.",
example: new SuccessResponse<PaginatedDto<FavoriteItemDto>>(true, new PaginatedDto<FavoriteItemDto>(
Data:
[
new FavoriteItemDto(
MediaKind: FavoriteMediaKind.MusicTrack,
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
IsAvailable: true,
LibraryId: Guid.Parse("1a2b3c4d-5e6f-4a7b-8c9d-0e1f2a3b4c5d"),
Title: "Time",
CollectionId: Guid.Parse("7c6b5a49-3827-4165-9d0e-1f2a3b4c5d6e"),
CollectionTitle: "The Dark Side of the Moon",
CreatorId: Guid.Parse("2d3e4f5a-6b7c-4d8e-9f0a-1b2c3d4e5f6a"),
CreatorName: "Pink Floyd",
CoverPath: "covers/dark-side-of-the-moon.jpg")
],
CurrentPage: 1,
PerPage: 200,
Count: 1,
NumberOfPages: 1))
);
}
}
@@ -0,0 +1,108 @@
#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.Antiforgery;
using Microsoft.AspNetCore.Builder;
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.Favorites.Index;
/// <summary>
/// API endpoint for the <c>/{culture}/favorites</c> route.
/// </summary>
public class FavoritesIndexViewEndpoint : 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.Favorites.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 = "favorites/index";
private readonly IUrlService _urlService;
private readonly ThemePageRenderer _themePageRenderer;
private readonly IAntiforgery _antiforgery;
private readonly IStringLocalizer _localizer;
/// <summary>
/// Initializes a new instance of the <see cref="FavoritesIndexViewEndpoint"/> 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="antiforgery">Injected service for anti-forgery token handling.</param>
/// <param name="stringLocalizerFactory">Injected factory used to create the localizer of the view resources.</param>
public FavoritesIndexViewEndpoint(IUrlService urlService, ThemePageRenderer themePageRenderer, IAntiforgery antiforgery, IStringLocalizerFactory stringLocalizerFactory)
{
_urlService = urlService;
_themePageRenderer = themePageRenderer;
_antiforgery = antiforgery;
_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.Favorites.INDEX);
DontAutoTag();
Options(options => options.WithTags("Favorites"));
}
/// <summary>
/// Displays the favorites of the current user across media kinds, 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 favorites 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";
// The page removes favorites, which submit through the form anti-forgery token, so a fresh token is issued for it.
AntiforgeryTokenSet antiforgeryTokens = _antiforgery.GetAndStoreTokens(HttpContext);
string title = _localizer["Title"].Value;
// The media item link templates carry the all-zero Guid placeholders of their route values, in route order, which the page replaces
// one at a time. The remove template keeps its named mediaKind and mediaItemId route placeholders instead, so those two values do not
// depend on the segment order. The detail pages of the media items expect the Id of their media library in the libraryId query
// parameter, which the page appends to the link from the favorite item.
ThemePageDto pageModel = new()
{
PageKey = VIEW_PAGE_KEY,
Title = title,
Description = string.Empty,
PageData = new Dictionary<string, object?>
{
["getFavoritesUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Favorites.GET_FAVORITES) ?? string.Empty,
["getFavoriteStatusUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Favorites.GET_FAVORITE_STATUS) ?? string.Empty,
["addFavoriteUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Favorites.ADD_FAVORITE) ?? string.Empty,
["removeFavoriteUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Favorites.REMOVE_FAVORITE) ?? string.Empty,
["artistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.ARTIST, new { artistId = default(Guid) }) ?? string.Empty,
["albumUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.ALBUM, new { artistId = default(Guid), albumId = default(Guid) }) ?? string.Empty,
["trackUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Music.TRACK, new { artistId = default(Guid), albumId = default(Guid), trackId = default(Guid) }) ?? string.Empty,
["bookUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Books.EDIT_BOOK, new { bookId = default(Guid) }) ?? string.Empty,
["antiforgeryToken"] = antiforgeryTokens.RequestToken,
["strings"] = ThemePageDataFactory.CreateLocalizedStrings(_localizer)
}
};
Result<ThemePageRenderResultDto> sectionResult = await _themePageRenderer.RenderAsync(pageModel, requestedThemeId: null, cancellationToken).ConfigureAwait(false);
if (sectionResult.IsFailure)
return View("/Core/Views/Favorites/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.Favorites.Index;
/// <summary>
/// Class used for providing a textual description for the <see cref="FavoritesIndexViewEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class FavoritesIndexViewEndpointSummary : Summary<FavoritesIndexViewEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="FavoritesIndexViewEndpointSummary"/> class.
/// </summary>
public FavoritesIndexViewEndpointSummary()
{
Summary = "Renders the favorites page.";
Description = "Renders the page that lists the favorites of the current user across media kinds and removes them.";
Response(200, "The favorites page is rendered.");
}
}
@@ -0,0 +1,71 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Enums.Favorites;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.RemoveFavorite;
/// <summary>
/// API endpoint for the <c>/{culture}/favorites/{mediaKind}/{mediaItemId}/api-remove-favorite</c> route.
/// </summary>
public class RemoveFavoriteEndpoint : BaseEndpoint<FastEndpoints.EmptyRequest, IResult>
{
// A value that is not a name of FavoriteMediaKind, so the API rejects a crafted route value with its own validation error.
private const string INVALID_MEDIA_KIND_PLACEHOLDER = "Invalid";
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public RemoveFavoriteEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.DELETE);
Routes(WebRoutes.Favorites.REMOVE_FAVORITE);
DontAutoTag();
Options(options => options.WithTags("Favorites"));
EnableAntiforgery();
}
/// <summary>
/// Removes a media item from the favorites 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(FastEndpoints.EmptyRequest request, CancellationToken cancellationToken)
{
// The route values are normalized before they are substituted into the upstream URL, so that a crafted value can never escape its URL segment.
// The media kind must be the name of a FavoriteMediaKind member, which also rejects numeric strings and comma separated flag lists, and the Id must be a Guid.
string routeMediaKind = HttpContext.Request.RouteValues["mediaKind"]?.ToString() ?? string.Empty;
string mediaKind = INVALID_MEDIA_KIND_PLACEHOLDER;
foreach (string mediaKindName in Enum.GetNames<FavoriteMediaKind>())
if (string.Equals(mediaKindName, routeMediaKind, StringComparison.OrdinalIgnoreCase))
mediaKind = mediaKindName;
string routeMediaItemId = HttpContext.Request.RouteValues["mediaItemId"]?.ToString() ?? string.Empty;
string mediaItemId = Guid.TryParse(routeMediaItemId, out Guid parsedMediaItemId) ? parsedMediaItemId.ToString() : Guid.Empty.ToString();
await _apiHttpClient.DeleteAsync(
ApiRoutes.Favorites.REMOVE_FAVORITE
.Replace("{mediaKind}", mediaKind)
.Replace("{mediaItemId}", mediaItemId),
cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Favorites.RemoveFavorite;
/// <summary>
/// Class used for providing a textual description for the <see cref="RemoveFavoriteEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class RemoveFavoriteEndpointSummary : Summary<RemoveFavoriteEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="RemoveFavoriteEndpointSummary"/> class.
/// </summary>
public RemoveFavoriteEndpointSummary()
{
Summary = "Removes a media item from the favorites of the current user.";
Description = "Proxies the request that removes a favorite to the API server. The media item itself is not deleted. The favorite belongs to the current user, so this route cannot remove another user's favorite. Removing is idempotent: a media item that is not a favorite of the current user already has the desired state, so the request succeeds.";
Params["mediaKind"] = "The kind of the favorited media item: MusicArtist, MusicAlbum, MusicTrack or Book.";
Params["mediaItemId"] = "The Id of the favorited media item.";
Response(200, "The media item was removed from the favorites, or the item was already not a favorite.",
example: new SuccessResponse(true)
);
}
}
@@ -2,6 +2,7 @@
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Albums;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
@@ -50,7 +51,7 @@ public class GetArtistAlbumsEndpoint : BaseEndpoint<GetArtistAlbumsLiteRequest,
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetArtistAlbumsLiteRequest request, CancellationToken cancellationToken)
{
PaginatedMusicAlbumLiteDto response = await _apiHttpClient.GetAsync<PaginatedMusicAlbumLiteDto>(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false);
PaginatedDto<MusicAlbumLiteDto> response = await _apiHttpClient.GetAsync<PaginatedDto<MusicAlbumLiteDto>>(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false);
return JsonSuccess(response);
}
@@ -2,6 +2,7 @@
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Artists;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
@@ -50,7 +51,7 @@ public class GetMusicArtistsEndpoint : BaseEndpoint<GetMusicArtistsLiteRequest,
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetMusicArtistsLiteRequest request, CancellationToken cancellationToken)
{
PaginatedMusicArtistLiteDto response = await _apiHttpClient.GetAsync<PaginatedMusicArtistLiteDto>(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false);
PaginatedDto<MusicArtistLiteDto> response = await _apiHttpClient.GetAsync<PaginatedDto<MusicArtistLiteDto>>(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false);
return JsonSuccess(response);
}
@@ -2,6 +2,7 @@
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.Requests.Library.AudioLibrary.MusicLibrary.Tracks;
using Lumina.Presentation.Web.Common.Routes;
using Lumina.Presentation.Web.Core.Endpoints.Common;
@@ -50,7 +51,7 @@ public class GetAlbumTracksEndpoint : BaseEndpoint<GetAlbumTracksLiteRequest, IR
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetAlbumTracksLiteRequest request, CancellationToken cancellationToken)
{
PaginatedMusicTrackLiteDto response = await _apiHttpClient.GetAsync<PaginatedMusicTrackLiteDto>(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false);
PaginatedDto<MusicTrackLiteDto> response = await _apiHttpClient.GetAsync<PaginatedDto<MusicTrackLiteDto>>(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false);
return JsonSuccess(response);
}
@@ -1,6 +1,7 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Libraries;
using Lumina.Presentation.Web.Common.Requests.Libraries;
using Lumina.Presentation.Web.Common.Routes;
@@ -50,7 +51,7 @@ public class GetLibraryItemsEndpoint : BaseEndpoint<GetBooksLiteRequest, IResult
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetBooksLiteRequest request, CancellationToken cancellationToken)
{
PaginatedBookLiteDto response = await _apiHttpClient.GetAsync<PaginatedBookLiteDto>(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false);
PaginatedDto<BookLiteDto> response = await _apiHttpClient.GetAsync<PaginatedDto<BookLiteDto>>(BuildItemsEndpoint(request), cancellationToken).ConfigureAwait(false);
return JsonSuccess(response);
}
@@ -44,6 +44,6 @@ public class GetLibraryItemsEndpointSummary : Summary<GetLibraryItemsEndpoint, G
SortOrder: SortOrder.Ascending
);
Response(200, "The lightweight details of the books of the media library are returned.", example: new SuccessResponse<PaginatedBookLiteDto>(true, default));
Response(200, "The lightweight details of the books of the media library are returned.", example: new SuccessResponse<PaginatedDto<BookLiteDto>>(true, default));
}
}
@@ -19,8 +19,7 @@ namespace Lumina.Presentation.Web.Core.Endpoints.Playlists.GetPlaylist;
/// </summary>
public class GetPlaylistEndpoint : BaseEndpoint<GetPlaylistRequest, IResult>
{
private const int DEFAULT_ENTRY_WINDOW_SIZE = 200;
private const int MAXIMUM_ENTRY_WINDOW_SIZE = 1000;
private const int DEFAULT_ENTRY_PAGE_SIZE = 200;
private readonly IApiHttpClient _apiHttpClient;
@@ -46,7 +45,7 @@ public class GetPlaylistEndpoint : BaseEndpoint<GetPlaylistRequest, IResult>
}
/// <summary>
/// Retrieves a window of the entries of a playlist of the current user.
/// Retrieves a page of the entries of a playlist 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>
@@ -58,11 +57,10 @@ public class GetPlaylistEndpoint : BaseEndpoint<GetPlaylistRequest, IResult>
// The route value is normalized to a Guid before it is substituted into the upstream URL, so that a crafted value can never escape its URL segment.
string routePlaylistId = HttpContext.Request.RouteValues["playlistId"]?.ToString() ?? string.Empty;
string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString();
int offset = request.Offset ?? 0;
// The web tier enforces the same response-window bound before forwarding, so a crafted value cannot make this proxy buffer an
// unbounded playlist response even if it never reaches the API validator.
int limit = Math.Clamp(request.Limit ?? DEFAULT_ENTRY_WINDOW_SIZE, 1, MAXIMUM_ENTRY_WINDOW_SIZE);
string url = ApiRoutes.Playlists.GET_PLAYLIST.Replace("{playlistId}", playlistId) + $"?offset={offset}&limit={limit}";
int currentPage = request.CurrentPage ?? 1;
// The page bounds are normalized by the API pagination data.
int perPage = request.PerPage ?? DEFAULT_ENTRY_PAGE_SIZE;
string url = ApiRoutes.Playlists.GET_PLAYLIST.Replace("{playlistId}", playlistId) + $"?currentPage={currentPage}&perPage={perPage}";
PlaylistDto playlist = await _apiHttpClient.GetAsync<PlaylistDto>(url, cancellationToken).ConfigureAwait(false);
return JsonSuccess(playlist);
}
@@ -2,7 +2,9 @@
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Playlists;
using Lumina.Presentation.Web.Common.Enums.Playlists;
using Lumina.Presentation.Web.Common.Requests.Playlists;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
@@ -20,19 +22,46 @@ public class GetPlaylistEndpointSummary : Summary<GetPlaylistEndpoint, GetPlayli
public GetPlaylistEndpointSummary()
{
Summary = "Gets a playlist of the current user.";
Description = "Proxies the request that gets a playlist and a window of its ordered entries to the API server.";
Description = "Proxies the request that gets a playlist and a page of its ordered entries to the API server. The currentPage and perPage query parameters select the page, and entries.count reports the total number of entries.";
Params["playlistId"] = "The Id of the playlist to get.";
ExampleRequest = new GetPlaylistRequest(
Offset: 0,
Limit: 200
CurrentPage: 1,
PerPage: 200
);
RequestParam(request => request.Offset, "The zero based position of the first entry to return. Optional; defaults to 0.");
RequestParam(request => request.Limit, "The maximum number of entries to return, from 1 to 1000. Optional; defaults to 200.");
RequestParam(request => request.CurrentPage, "The one based page of entries to return. Optional; defaults to 1.");
RequestParam(request => request.PerPage, "The number of entries per page. Optional; defaults to 200.");
Response(200, "The playlist and its ordered entries are returned.",
example: new SuccessResponse<PlaylistDto>(true, default)
example: new SuccessResponse<PlaylistDto>(true, new PlaylistDto(
Id: Guid.Parse("1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b"),
Name: "Evening listening",
Description: "Quiet tracks for the end of the day.",
Type: PlaylistType.Music,
Entries: new PaginatedDto<PlaylistEntryDto>(
Data:
[
new PlaylistEntryDto(
Id: Guid.Parse("2a3b4c5d-6e7f-4a8b-9c0d-1e2f3a4b5c6d"),
MediaItemId: Guid.Parse("9f0e1d2c-3b4a-4c6d-8e7f-9a0b1c2d3e4f"),
MediaItemType: PlaylistMediaItemType.MusicTrack,
Position: 0,
LibraryId: Guid.Parse("3b3a19f3-1f5a-4d5a-9a3a-5c5a4a3a2a1a"),
CollectionId: Guid.Parse("e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f"),
CreatorId: Guid.Parse("d7c41e6a-9f2b-4b1c-9a3e-7f6e5d4c3b2a"),
MediaItemTitle: "The Show Must Go On",
CollectionTitle: "Innuendo",
CreatorName: "Queen",
DurationInSeconds: 262,
CoverPath: "/artwork/albums/e8d52f7b-0a3c-4c2d-ab4f-8a7b6c5d4e3f/cover.jpg")
],
CurrentPage: 1,
PerPage: 200,
Count: 1,
NumberOfPages: 1),
CreatedOnUtc: new DateTime(2026, 10, 19, 18, 0, 0, DateTimeKind.Utc),
UpdatedOnUtc: new DateTime(2026, 10, 19, 19, 30, 0, DateTimeKind.Utc)))
);
}
}
@@ -1,5 +1,6 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Playlists;
using Lumina.Presentation.Web.Common.DTO.Themes;
using Lumina.Presentation.Web.Common.Enums.Playlists;
@@ -31,6 +32,8 @@ public class AddPlaylistViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
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 = "playlists/item";
// A new playlist has no entries yet, but its serialized page still carries the shape the page script expects.
private const int DEFAULT_ENTRY_PAGE_SIZE = 200;
private static readonly JsonSerializerOptions s_camelCaseJsonOptions = new()
{
@@ -88,8 +91,12 @@ public class AddPlaylistViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
Name: string.Empty,
Description: null,
Type: PlaylistType.Music,
EntryCount: 0,
Entries: [],
Entries: new PaginatedDto<PlaylistEntryDto>(
Data: [],
CurrentPage: 1,
PerPage: DEFAULT_ENTRY_PAGE_SIZE,
Count: 0,
NumberOfPages: 0),
CreatedOnUtc: default,
UpdatedOnUtc: null
);
@@ -105,6 +112,7 @@ public class AddPlaylistViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
["isNew"] = true,
["playlistId"] = playlist.Id.ToString(),
["playlistJson"] = JsonSerializer.Serialize(playlist, s_camelCaseJsonOptions),
["entriesPerPage"] = DEFAULT_ENTRY_PAGE_SIZE,
["createPlaylistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.CREATE_PLAYLIST) ?? string.Empty,
["itemUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.ITEM, new { playlistId = default(Guid) }) ?? string.Empty,
["getEnabledLibrariesUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_ENABLED_LIBRARIES) ?? string.Empty,
@@ -31,8 +31,8 @@ public class PlaylistItemViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
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 = "playlists/item";
// The page renders one window at a time; the client asks for the next window through getPlaylistUrl.
private const int ENTRY_WINDOW_SIZE = 200;
// The page renders one page at a time; the client asks for the next page through getPlaylistUrl.
private const int ENTRY_PAGE_SIZE = 200;
private static readonly JsonSerializerOptions s_camelCaseJsonOptions = new()
{
@@ -91,7 +91,7 @@ public class PlaylistItemViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
string playlistId = Guid.TryParse(routePlaylistId, out Guid parsedPlaylistId) ? parsedPlaylistId.ToString() : Guid.Empty.ToString();
PlaylistDto playlist = await _apiHttpClient
.GetAsync<PlaylistDto>(
ApiRoutes.Playlists.GET_PLAYLIST.Replace("{playlistId}", playlistId) + $"?offset=0&limit={ENTRY_WINDOW_SIZE}",
ApiRoutes.Playlists.GET_PLAYLIST.Replace("{playlistId}", playlistId) + $"?currentPage=1&perPage={ENTRY_PAGE_SIZE}",
cancellationToken).ConfigureAwait(false);
// The page edits, reorders and deletes the playlist, which submit through the form anti-forgery token, so a fresh token is issued for it.
@@ -107,7 +107,7 @@ public class PlaylistItemViewEndpoint : BaseEndpoint<EmptyRequest, IResult>
["isNew"] = false,
["playlistId"] = playlist.Id.ToString(),
["playlistJson"] = JsonSerializer.Serialize(playlist, s_camelCaseJsonOptions),
["entriesWindowSize"] = ENTRY_WINDOW_SIZE,
["entriesPerPage"] = ENTRY_PAGE_SIZE,
["createPlaylistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.CREATE_PLAYLIST) ?? string.Empty,
["itemUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.ITEM, new { playlistId = default(Guid) }) ?? string.Empty,
["getPlaylistUrl"] = _urlService.GetAbsoluteUrl(WebRoutes.Playlists.GET_PLAYLIST, new { playlistId = playlist.Id }) ?? string.Empty,
@@ -0,0 +1,66 @@
<?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="NoFavorites" xml:space="preserve">
<value>ليست لديك أي عناصر مفضلة بعد.</value>
</data>
<data name="NoFavoritesInKind" xml:space="preserve">
<value>ليست لديك أي عناصر مفضلة من هذا النوع بعد.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>هذا العنصر لم يعد متاحًا.</value>
</data>
<data name="FilterAll" xml:space="preserve">
<value>الكل</value>
</data>
<data name="FilterArtists" xml:space="preserve">
<value>الفنانون</value>
</data>
<data name="FilterAlbums" xml:space="preserve">
<value>الألبومات</value>
</data>
<data name="FilterTracks" xml:space="preserve">
<value>المقاطع</value>
</data>
<data name="FilterBooks" xml:space="preserve">
<value>الكتب</value>
</data>
<data name="KindArtist" xml:space="preserve">
<value>فنان</value>
</data>
<data name="KindAlbum" xml:space="preserve">
<value>ألبوم</value>
</data>
<data name="KindTrack" xml:space="preserve">
<value>مقطع</value>
</data>
<data name="KindBook" xml:space="preserve">
<value>كتاب</value>
</data>
<data name="LoadMore" xml:space="preserve">
<value>تحميل المزيد</value>
</data>
<data name="ItemsCount" xml:space="preserve">
<value>عناصر</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>تعذر تحميل المفضلة.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>إعادة المحاولة</value>
</data>
</root>
@@ -0,0 +1,66 @@
<?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>Favoriten</value>
</data>
<data name="NoFavorites" xml:space="preserve">
<value>Du hast noch keine Favoriten.</value>
</data>
<data name="NoFavoritesInKind" xml:space="preserve">
<value>Du hast noch keine Favoriten dieser Art.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>Dieses Element ist nicht mehr verfügbar.</value>
</data>
<data name="FilterAll" xml:space="preserve">
<value>Alle</value>
</data>
<data name="FilterArtists" xml:space="preserve">
<value>Künstler</value>
</data>
<data name="FilterAlbums" xml:space="preserve">
<value>Alben</value>
</data>
<data name="FilterTracks" xml:space="preserve">
<value>Titel</value>
</data>
<data name="FilterBooks" xml:space="preserve">
<value>Bücher</value>
</data>
<data name="KindArtist" xml:space="preserve">
<value>Künstler</value>
</data>
<data name="KindAlbum" xml:space="preserve">
<value>Album</value>
</data>
<data name="KindTrack" xml:space="preserve">
<value>Titel</value>
</data>
<data name="KindBook" xml:space="preserve">
<value>Buch</value>
</data>
<data name="LoadMore" xml:space="preserve">
<value>Mehr laden</value>
</data>
<data name="ItemsCount" xml:space="preserve">
<value>Einträge</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>Die Favoriten konnten nicht geladen werden.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Wiederholen</value>
</data>
</root>
@@ -0,0 +1,66 @@
<?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>Favorites</value>
</data>
<data name="NoFavorites" xml:space="preserve">
<value>You have no favorites yet.</value>
</data>
<data name="NoFavoritesInKind" xml:space="preserve">
<value>You have no favorites of this kind yet.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>This item is no longer available.</value>
</data>
<data name="FilterAll" xml:space="preserve">
<value>All</value>
</data>
<data name="FilterArtists" xml:space="preserve">
<value>Artists</value>
</data>
<data name="FilterAlbums" xml:space="preserve">
<value>Albums</value>
</data>
<data name="FilterTracks" xml:space="preserve">
<value>Tracks</value>
</data>
<data name="FilterBooks" xml:space="preserve">
<value>Books</value>
</data>
<data name="KindArtist" xml:space="preserve">
<value>Artist</value>
</data>
<data name="KindAlbum" xml:space="preserve">
<value>Album</value>
</data>
<data name="KindTrack" xml:space="preserve">
<value>Track</value>
</data>
<data name="KindBook" xml:space="preserve">
<value>Book</value>
</data>
<data name="LoadMore" xml:space="preserve">
<value>Load more</value>
</data>
<data name="ItemsCount" xml:space="preserve">
<value>items</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>The favorites could not be loaded.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Retry</value>
</data>
</root>
@@ -0,0 +1,66 @@
<?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>Favoritos</value>
</data>
<data name="NoFavorites" xml:space="preserve">
<value>Todavía no tienes favoritos.</value>
</data>
<data name="NoFavoritesInKind" xml:space="preserve">
<value>Todavía no tienes favoritos de este tipo.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>Este elemento ya no está disponible.</value>
</data>
<data name="FilterAll" xml:space="preserve">
<value>Todos</value>
</data>
<data name="FilterArtists" xml:space="preserve">
<value>Artistas</value>
</data>
<data name="FilterAlbums" xml:space="preserve">
<value>Álbumes</value>
</data>
<data name="FilterTracks" xml:space="preserve">
<value>Pistas</value>
</data>
<data name="FilterBooks" xml:space="preserve">
<value>Libros</value>
</data>
<data name="KindArtist" xml:space="preserve">
<value>Artista</value>
</data>
<data name="KindAlbum" xml:space="preserve">
<value>Álbum</value>
</data>
<data name="KindTrack" xml:space="preserve">
<value>Pista</value>
</data>
<data name="KindBook" xml:space="preserve">
<value>Libro</value>
</data>
<data name="LoadMore" xml:space="preserve">
<value>Cargar más</value>
</data>
<data name="ItemsCount" xml:space="preserve">
<value>elementos</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>No se pudieron cargar los favoritos.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Reintentar</value>
</data>
</root>
@@ -0,0 +1,66 @@
<?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>Favoris</value>
</data>
<data name="NoFavorites" xml:space="preserve">
<value>Vous n'avez encore aucun favori.</value>
</data>
<data name="NoFavoritesInKind" xml:space="preserve">
<value>Vous n'avez encore aucun favori de ce type.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>Cet élément n'est plus disponible.</value>
</data>
<data name="FilterAll" xml:space="preserve">
<value>Tous</value>
</data>
<data name="FilterArtists" xml:space="preserve">
<value>Artistes</value>
</data>
<data name="FilterAlbums" xml:space="preserve">
<value>Albums</value>
</data>
<data name="FilterTracks" xml:space="preserve">
<value>Pistes</value>
</data>
<data name="FilterBooks" xml:space="preserve">
<value>Livres</value>
</data>
<data name="KindArtist" xml:space="preserve">
<value>Artiste</value>
</data>
<data name="KindAlbum" xml:space="preserve">
<value>Album</value>
</data>
<data name="KindTrack" xml:space="preserve">
<value>Piste</value>
</data>
<data name="KindBook" xml:space="preserve">
<value>Livre</value>
</data>
<data name="LoadMore" xml:space="preserve">
<value>Charger plus</value>
</data>
<data name="ItemsCount" xml:space="preserve">
<value>éléments</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>Les favoris n'ont pas pu être chargés.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Réessayer</value>
</data>
</root>
@@ -0,0 +1,66 @@
<?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>Preferiti</value>
</data>
<data name="NoFavorites" xml:space="preserve">
<value>Non hai ancora preferiti.</value>
</data>
<data name="NoFavoritesInKind" xml:space="preserve">
<value>Non hai ancora preferiti di questo tipo.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>Questo elemento non è più disponibile.</value>
</data>
<data name="FilterAll" xml:space="preserve">
<value>Tutti</value>
</data>
<data name="FilterArtists" xml:space="preserve">
<value>Artisti</value>
</data>
<data name="FilterAlbums" xml:space="preserve">
<value>Album</value>
</data>
<data name="FilterTracks" xml:space="preserve">
<value>Brani</value>
</data>
<data name="FilterBooks" xml:space="preserve">
<value>Libri</value>
</data>
<data name="KindArtist" xml:space="preserve">
<value>Artista</value>
</data>
<data name="KindAlbum" xml:space="preserve">
<value>Album</value>
</data>
<data name="KindTrack" xml:space="preserve">
<value>Brano</value>
</data>
<data name="KindBook" xml:space="preserve">
<value>Libro</value>
</data>
<data name="LoadMore" xml:space="preserve">
<value>Carica altri</value>
</data>
<data name="ItemsCount" xml:space="preserve">
<value>elementi</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>Non è stato possibile caricare i preferiti.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Riprova</value>
</data>
</root>
@@ -0,0 +1,66 @@
<?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="NoFavorites" xml:space="preserve">
<value>お気に入りはまだありません。</value>
</data>
<data name="NoFavoritesInKind" xml:space="preserve">
<value>この種類のお気に入りはまだありません。</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>この項目は利用できなくなりました。</value>
</data>
<data name="FilterAll" xml:space="preserve">
<value>すべて</value>
</data>
<data name="FilterArtists" xml:space="preserve">
<value>アーティスト</value>
</data>
<data name="FilterAlbums" xml:space="preserve">
<value>アルバム</value>
</data>
<data name="FilterTracks" xml:space="preserve">
<value>曲</value>
</data>
<data name="FilterBooks" xml:space="preserve">
<value>書籍</value>
</data>
<data name="KindArtist" xml:space="preserve">
<value>アーティスト</value>
</data>
<data name="KindAlbum" xml:space="preserve">
<value>アルバム</value>
</data>
<data name="KindTrack" xml:space="preserve">
<value>曲</value>
</data>
<data name="KindBook" xml:space="preserve">
<value>書籍</value>
</data>
<data name="LoadMore" xml:space="preserve">
<value>さらに読み込む</value>
</data>
<data name="ItemsCount" xml:space="preserve">
<value>件</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>お気に入りを読み込めませんでした。</value>
</data>
<data name="Retry" xml:space="preserve">
<value>再試行</value>
</data>
</root>
@@ -0,0 +1,66 @@
<?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>Favorites</value>
</data>
<data name="NoFavorites" xml:space="preserve">
<value>You have no favorites yet.</value>
</data>
<data name="NoFavoritesInKind" xml:space="preserve">
<value>You have no favorites of this kind yet.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>This item is no longer available.</value>
</data>
<data name="FilterAll" xml:space="preserve">
<value>All</value>
</data>
<data name="FilterArtists" xml:space="preserve">
<value>Artists</value>
</data>
<data name="FilterAlbums" xml:space="preserve">
<value>Albums</value>
</data>
<data name="FilterTracks" xml:space="preserve">
<value>Tracks</value>
</data>
<data name="FilterBooks" xml:space="preserve">
<value>Books</value>
</data>
<data name="KindArtist" xml:space="preserve">
<value>Artist</value>
</data>
<data name="KindAlbum" xml:space="preserve">
<value>Album</value>
</data>
<data name="KindTrack" xml:space="preserve">
<value>Track</value>
</data>
<data name="KindBook" xml:space="preserve">
<value>Book</value>
</data>
<data name="LoadMore" xml:space="preserve">
<value>Load more</value>
</data>
<data name="ItemsCount" xml:space="preserve">
<value>items</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>The favorites could not be loaded.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Retry</value>
</data>
</root>
@@ -0,0 +1,66 @@
<?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>Favorite</value>
</data>
<data name="NoFavorites" xml:space="preserve">
<value>Nu ai încă favorite.</value>
</data>
<data name="NoFavoritesInKind" xml:space="preserve">
<value>Nu ai încă favorite de acest fel.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>Acest element nu mai este disponibil.</value>
</data>
<data name="FilterAll" xml:space="preserve">
<value>Toate</value>
</data>
<data name="FilterArtists" xml:space="preserve">
<value>Artiști</value>
</data>
<data name="FilterAlbums" xml:space="preserve">
<value>Albume</value>
</data>
<data name="FilterTracks" xml:space="preserve">
<value>Piese</value>
</data>
<data name="FilterBooks" xml:space="preserve">
<value>Cărți</value>
</data>
<data name="KindArtist" xml:space="preserve">
<value>Artist</value>
</data>
<data name="KindAlbum" xml:space="preserve">
<value>Album</value>
</data>
<data name="KindTrack" xml:space="preserve">
<value>Piesă</value>
</data>
<data name="KindBook" xml:space="preserve">
<value>Carte</value>
</data>
<data name="LoadMore" xml:space="preserve">
<value>Încarcă mai multe</value>
</data>
<data name="ItemsCount" xml:space="preserve">
<value>elemente</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>Favoritele nu au putut fi încărcate.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Reîncercare</value>
</data>
</root>
@@ -0,0 +1,66 @@
<?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="NoFavorites" xml:space="preserve">
<value>У вас ще немає улюбленого.</value>
</data>
<data name="NoFavoritesInKind" xml:space="preserve">
<value>У вас ще немає улюбленого цього типу.</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>Цей елемент більше недоступний.</value>
</data>
<data name="FilterAll" xml:space="preserve">
<value>Усе</value>
</data>
<data name="FilterArtists" xml:space="preserve">
<value>Виконавці</value>
</data>
<data name="FilterAlbums" xml:space="preserve">
<value>Альбоми</value>
</data>
<data name="FilterTracks" xml:space="preserve">
<value>Треки</value>
</data>
<data name="FilterBooks" xml:space="preserve">
<value>Книги</value>
</data>
<data name="KindArtist" xml:space="preserve">
<value>Виконавець</value>
</data>
<data name="KindAlbum" xml:space="preserve">
<value>Альбом</value>
</data>
<data name="KindTrack" xml:space="preserve">
<value>Трек</value>
</data>
<data name="KindBook" xml:space="preserve">
<value>Книга</value>
</data>
<data name="LoadMore" xml:space="preserve">
<value>Завантажити ще</value>
</data>
<data name="ItemsCount" xml:space="preserve">
<value>елементів</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>Не вдалося завантажити улюблене.</value>
</data>
<data name="Retry" xml:space="preserve">
<value>Повторити</value>
</data>
</root>
@@ -0,0 +1,66 @@
<?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="NoFavorites" xml:space="preserve">
<value>你还没有收藏。</value>
</data>
<data name="NoFavoritesInKind" xml:space="preserve">
<value>你还没有此类收藏。</value>
</data>
<data name="Unavailable" xml:space="preserve">
<value>此项目已不可用。</value>
</data>
<data name="FilterAll" xml:space="preserve">
<value>全部</value>
</data>
<data name="FilterArtists" xml:space="preserve">
<value>艺术家</value>
</data>
<data name="FilterAlbums" xml:space="preserve">
<value>专辑</value>
</data>
<data name="FilterTracks" xml:space="preserve">
<value>曲目</value>
</data>
<data name="FilterBooks" xml:space="preserve">
<value>图书</value>
</data>
<data name="KindArtist" xml:space="preserve">
<value>艺术家</value>
</data>
<data name="KindAlbum" xml:space="preserve">
<value>专辑</value>
</data>
<data name="KindTrack" xml:space="preserve">
<value>曲目</value>
</data>
<data name="KindBook" xml:space="preserve">
<value>图书</value>
</data>
<data name="LoadMore" xml:space="preserve">
<value>加载更多</value>
</data>
<data name="ItemsCount" xml:space="preserve">
<value>项</value>
</data>
<data name="LoadFailed" xml:space="preserve">
<value>无法加载收藏。</value>
</data>
<data name="Retry" xml:space="preserve">
<value>重试</value>
</data>
</root>
@@ -66,6 +66,9 @@
<data name="AddFailed" xml:space="preserve">
<value>تعذر إضافة المقطع.</value>
</data>
<data name="RefreshFailed" xml:space="preserve">
<value>تم تحديث قائمة التشغيل، لكن تعذر تحديث القائمة. أعد تحميل الصفحة لرؤية التغيير.</value>
</data>
<data name="SelectLibrary" xml:space="preserve">
<value>اختر مكتبة</value>
</data>
@@ -66,6 +66,9 @@
<data name="AddFailed" xml:space="preserve">
<value>Der Titel konnte nicht hinzugefügt werden.</value>
</data>
<data name="RefreshFailed" xml:space="preserve">
<value>Die Wiedergabeliste wurde aktualisiert, aber die Liste konnte nicht neu geladen werden. Laden Sie die Seite neu, um die Änderung zu sehen.</value>
</data>
<data name="SelectLibrary" xml:space="preserve">
<value>Bibliothek auswählen</value>
</data>
@@ -66,6 +66,9 @@
<data name="AddFailed" xml:space="preserve">
<value>The track could not be added.</value>
</data>
<data name="RefreshFailed" xml:space="preserve">
<value>The playlist was updated, but the list could not be refreshed. Reload the page to see the change.</value>
</data>
<data name="SelectLibrary" xml:space="preserve">
<value>Select a library</value>
</data>
@@ -66,6 +66,9 @@
<data name="AddFailed" xml:space="preserve">
<value>No se pudo añadir la pista.</value>
</data>
<data name="RefreshFailed" xml:space="preserve">
<value>La lista de reproducción se actualizó, pero no se pudo actualizar la lista. Recarga la página para ver el cambio.</value>
</data>
<data name="SelectLibrary" xml:space="preserve">
<value>Selecciona una biblioteca</value>
</data>
@@ -66,6 +66,9 @@
<data name="AddFailed" xml:space="preserve">
<value>La piste n&apos;a pas pu être ajoutée.</value>
</data>
<data name="RefreshFailed" xml:space="preserve">
<value>La liste de lecture a été mise à jour, mais la liste n&apos;a pas pu être actualisée. Rechargez la page pour voir la modification.</value>
</data>
<data name="SelectLibrary" xml:space="preserve">
<value>Choisir une bibliothèque</value>
</data>
@@ -66,6 +66,9 @@
<data name="AddFailed" xml:space="preserve">
<value>Non è stato possibile aggiungere il brano.</value>
</data>
<data name="RefreshFailed" xml:space="preserve">
<value>La playlist è stata aggiornata, ma non è stato possibile aggiornare l&apos;elenco. Ricarica la pagina per vedere la modifica.</value>
</data>
<data name="SelectLibrary" xml:space="preserve">
<value>Seleziona una libreria</value>
</data>
@@ -66,6 +66,9 @@
<data name="AddFailed" xml:space="preserve">
<value>曲を追加できませんでした。</value>
</data>
<data name="RefreshFailed" xml:space="preserve">
<value>プレイリストは更新されましたが、一覧を更新できませんでした。変更を確認するにはページを再読み込みしてください。</value>
</data>
<data name="SelectLibrary" xml:space="preserve">
<value>ライブラリを選択</value>
</data>
@@ -66,6 +66,9 @@
<data name="AddFailed" xml:space="preserve">
<value>The track could not be added.</value>
</data>
<data name="RefreshFailed" xml:space="preserve">
<value>The playlist was updated, but the list could not be refreshed. Reload the page to see the change.</value>
</data>
<data name="SelectLibrary" xml:space="preserve">
<value>Select a library</value>
</data>
@@ -66,6 +66,9 @@
<data name="AddFailed" xml:space="preserve">
<value>Piesa nu a putut fi adăugată.</value>
</data>
<data name="RefreshFailed" xml:space="preserve">
<value>Lista de redare a fost actualizată, dar lista nu a putut fi reîmprospătată. Reîncarcă pagina pentru a vedea modificarea.</value>
</data>
<data name="SelectLibrary" xml:space="preserve">
<value>Selectează o bibliotecă</value>
</data>
@@ -66,6 +66,9 @@
<data name="AddFailed" xml:space="preserve">
<value>Не вдалося додати трек.</value>
</data>
<data name="RefreshFailed" xml:space="preserve">
<value>Список відтворення оновлено, але список не вдалося оновити. Перезавантажте сторінку, щоб побачити зміну.</value>
</data>
<data name="SelectLibrary" xml:space="preserve">
<value>Виберіть бібліотеку</value>
</data>
@@ -66,6 +66,9 @@
<data name="AddFailed" xml:space="preserve">
<value>无法添加曲目。</value>
</data>
<data name="RefreshFailed" xml:space="preserve">
<value>播放列表已更新,但无法刷新列表。请重新加载页面以查看更改。</value>
</data>
<data name="SelectLibrary" xml:space="preserve">
<value>选择库</value>
</data>
@@ -255,4 +255,10 @@
<data name="PlaylistNoTracksToAdd" xml:space="preserve">
<value>لا توجد مقاطع لإضافتها.</value>
</data>
<data name="FavoritesAdd" xml:space="preserve">
<value>إضافة إلى المفضلة</value>
</data>
<data name="FavoritesRemove" xml:space="preserve">
<value>إزالة من المفضلة</value>
</data>
</root>
@@ -255,4 +255,10 @@
<data name="PlaylistNoTracksToAdd" xml:space="preserve">
<value>Es gibt keine Titel zum Hinzufügen.</value>
</data>
<data name="FavoritesAdd" xml:space="preserve">
<value>Zu Favoriten hinzufügen</value>
</data>
<data name="FavoritesRemove" xml:space="preserve">
<value>Aus Favoriten entfernen</value>
</data>
</root>
@@ -255,4 +255,10 @@
<data name="PlaylistNoTracksToAdd" xml:space="preserve">
<value>There are no tracks to add.</value>
</data>
<data name="FavoritesAdd" xml:space="preserve">
<value>Add to favorites</value>
</data>
<data name="FavoritesRemove" xml:space="preserve">
<value>Remove from favorites</value>
</data>
</root>
@@ -255,4 +255,10 @@
<data name="PlaylistNoTracksToAdd" xml:space="preserve">
<value>No hay pistas para añadir.</value>
</data>
<data name="FavoritesAdd" xml:space="preserve">
<value>Añadir a favoritos</value>
</data>
<data name="FavoritesRemove" xml:space="preserve">
<value>Quitar de favoritos</value>
</data>
</root>
@@ -255,4 +255,10 @@
<data name="PlaylistNoTracksToAdd" xml:space="preserve">
<value>Il n'y a aucune piste à ajouter.</value>
</data>
<data name="FavoritesAdd" xml:space="preserve">
<value>Ajouter aux favoris</value>
</data>
<data name="FavoritesRemove" xml:space="preserve">
<value>Retirer des favoris</value>
</data>
</root>
@@ -255,4 +255,10 @@
<data name="PlaylistNoTracksToAdd" xml:space="preserve">
<value>Non ci sono tracce da aggiungere.</value>
</data>
<data name="FavoritesAdd" xml:space="preserve">
<value>Aggiungi ai preferiti</value>
</data>
<data name="FavoritesRemove" xml:space="preserve">
<value>Rimuovi dai preferiti</value>
</data>
</root>
@@ -255,4 +255,10 @@
<data name="PlaylistNoTracksToAdd" xml:space="preserve">
<value>追加するトラックがありません。</value>
</data>
<data name="FavoritesAdd" xml:space="preserve">
<value>お気に入りに追加</value>
</data>
<data name="FavoritesRemove" xml:space="preserve">
<value>お気に入りから削除</value>
</data>
</root>
@@ -255,4 +255,10 @@
<data name="PlaylistNoTracksToAdd" xml:space="preserve">
<value>There are no tracks to add.</value>
</data>
<data name="FavoritesAdd" xml:space="preserve">
<value>Add to favorites</value>
</data>
<data name="FavoritesRemove" xml:space="preserve">
<value>Remove from favorites</value>
</data>
</root>
@@ -255,4 +255,10 @@
<data name="PlaylistNoTracksToAdd" xml:space="preserve">
<value>Nu există piese de adăugat.</value>
</data>
<data name="FavoritesAdd" xml:space="preserve">
<value>Adaugă la favorite</value>
</data>
<data name="FavoritesRemove" xml:space="preserve">
<value>Elimină din favorite</value>
</data>
</root>
@@ -255,4 +255,10 @@
<data name="PlaylistNoTracksToAdd" xml:space="preserve">
<value>Немає треків для додавання.</value>
</data>
<data name="FavoritesAdd" xml:space="preserve">
<value>Додати до улюбленого</value>
</data>
<data name="FavoritesRemove" xml:space="preserve">
<value>Видалити з улюбленого</value>
</data>
</root>
@@ -255,4 +255,10 @@
<data name="PlaylistNoTracksToAdd" xml:space="preserve">
<value>没有可添加的曲目。</value>
</data>
<data name="FavoritesAdd" xml:space="preserve">
<value>添加到收藏</value>
</data>
<data name="FavoritesRemove" xml:space="preserve">
<value>取消收藏</value>
</data>
</root>
@@ -222,4 +222,7 @@
<data name="Playlists" xml:space="preserve">
<value>قوائم التشغيل</value>
</data>
<data name="Favorites" xml:space="preserve">
<value>المفضلة</value>
</data>
</root>
@@ -222,4 +222,7 @@
<data name="Playlists" xml:space="preserve">
<value>Wiedergabelisten</value>
</data>
<data name="Favorites" xml:space="preserve">
<value>Favoriten</value>
</data>
</root>
@@ -222,4 +222,7 @@
<data name="Playlists" xml:space="preserve">
<value>Playlists</value>
</data>
<data name="Favorites" xml:space="preserve">
<value>Favorites</value>
</data>
</root>
@@ -222,4 +222,7 @@
<data name="Playlists" xml:space="preserve">
<value>Listas de reproducción</value>
</data>
<data name="Favorites" xml:space="preserve">
<value>Favoritos</value>
</data>
</root>
@@ -222,4 +222,7 @@
<data name="Playlists" xml:space="preserve">
<value>Listes de lecture</value>
</data>
<data name="Favorites" xml:space="preserve">
<value>Favoris</value>
</data>
</root>
@@ -222,4 +222,7 @@
<data name="Playlists" xml:space="preserve">
<value>Playlist</value>
</data>
<data name="Favorites" xml:space="preserve">
<value>Preferiti</value>
</data>
</root>
@@ -222,4 +222,7 @@
<data name="Playlists" xml:space="preserve">
<value>プレイリスト</value>
</data>
<data name="Favorites" xml:space="preserve">
<value>お気に入り</value>
</data>
</root>
@@ -222,4 +222,7 @@
<data name="Playlists" xml:space="preserve">
<value>Playlists</value>
</data>
<data name="Favorites" xml:space="preserve">
<value>Favorites</value>
</data>
</root>
@@ -222,4 +222,7 @@
<data name="Playlists" xml:space="preserve">
<value>Liste de redare</value>
</data>
<data name="Favorites" xml:space="preserve">
<value>Favorite</value>
</data>
</root>
@@ -222,4 +222,7 @@
<data name="Playlists" xml:space="preserve">
<value>Списки відтворення</value>
</data>
<data name="Favorites" xml:space="preserve">
<value>Улюблене</value>
</data>
</root>
@@ -222,4 +222,7 @@
<data name="Playlists" xml:space="preserve">
<value>播放列表</value>
</data>
<data name="Favorites" xml:space="preserve">
<value>收藏夹</value>
</data>
</root>
@@ -152,6 +152,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", []));
// 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,534 @@
@*
FALLBACK FAVORITES PAGE - READ BEFORE EDITING
This view is the application fallback of the favorites page, rendered only when the theme template of the page cannot be
loaded. The bundled themes ship no template for it, so this view is what the user sees on a healthy site as well. It keeps
the DOM contract and the client script a theme template would mirror, so that listing, filtering and removing favorites
keep working with any theme.
The page lists the favorites of the current user across every media kind, from the most recently favorited, in pages of
50 items, and the kind filter restricts the list to one kind. Every card links to the page of its item, and carries a
favorite heart (a card-favorite-toggle button, always visible, in the place the actions trigger has on the library cards)
that the global favorites script drives, so a favorite is removed from the card itself. The page listens to
the lumina:favorite-changed event the script dispatches and removes the card of an item that is no longer a favorite, so
the counter and the empty state follow without another request. A favorite whose item was deleted, or whose library the
user can no longer access, is kept as an unavailable card without a link, so the owner can still remove it.
The element hooks the script needs are favorites-container, no-favorites, favorite-count, favorites-kind-filter,
load-more-favorites-button and retry-favorites-button, and the classes of the cards are media-card, media-panel and
card-favorite-toggle. A failed reload clears the rendered window and shows the retry button, so the page never keeps the cards
of a filter the combo no longer shows.
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.
/favorites
*@
@using Lumina.Presentation.Web.Common.Services
@using Microsoft.AspNetCore.Mvc.Localization
@using System
@using System.Collections.Generic
@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,
["noFavorites"] = _localizer["NoFavorites"].Value,
["noFavoritesInKind"] = _localizer["NoFavoritesInKind"].Value,
["unavailable"] = _localizer["Unavailable"].Value,
["itemsCount"] = _localizer["ItemsCount"].Value,
["loadFailed"] = _localizer["LoadFailed"].Value,
["kindMusicArtist"] = _localizer["KindArtist"].Value,
["kindMusicAlbum"] = _localizer["KindAlbum"].Value,
["kindMusicTrack"] = _localizer["KindTrack"].Value,
["kindBook"] = _localizer["KindBook"].Value
};
var jsonOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
Converters = { new JsonStringEnumConverter() }
};
}
@Html.AntiForgeryToken()
<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>
<!-- Kind filter. -->
<div class="form-row">
<div class="enlightenment-combobox inline-block w-200px" id="favorites-kind-filter">
<div class="shine-effect" style="top: 1px;"></div>
<input type="checkbox" class="enlightenment-toggle-checkbox" id="favorites-kind-filter-toggle" />
<label class="enlightenment-toggle" for="favorites-kind-filter-toggle">
<span class="enlightenment-selected-text" data-value="">@_localizer["FilterAll"]</span>
</label>
<div class="enlightenment-dropdown">
<div class="shine-effect" style="top: -4px;"></div>
<div class="enlightenment-option" data-value="">@_localizer["FilterAll"]</div>
<div class="enlightenment-option" data-value="MusicArtist">@_localizer["FilterArtists"]</div>
<div class="enlightenment-option" data-value="MusicAlbum">@_localizer["FilterAlbums"]</div>
<div class="enlightenment-option" data-value="MusicTrack">@_localizer["FilterTracks"]</div>
<div class="enlightenment-option last-option" data-value="Book">@_localizer["FilterBooks"]</div>
</div>
</div>
</div>
<div class="form-row">
<span id="favorite-count" class="text-light-two" aria-live="polite"></span>
</div>
<div id="favorites-container" class="cards-container justify-start h-100"></div>
<p id="no-favorites" class="hidden text-light-two text-center" aria-live="polite" aria-atomic="true" tabindex="-1">@_localizer["NoFavorites"]</p>
<div class="form-row">
<button id="load-more-favorites-button" type="button" class="confirm-button hidden">@_localizer["LoadMore"]</button>
<button id="retry-favorites-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 getFavoritesUrl = '@_urlService.GetAbsoluteUrl(WebRoutes.Favorites.GET_FAVORITES)';
const artistUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Music.ARTIST, new { artistId = default(Guid) })';
const albumUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Music.ALBUM, new { artistId = default(Guid), albumId = default(Guid) })';
const trackUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Music.TRACK, new { artistId = default(Guid), albumId = default(Guid), trackId = default(Guid) })';
const bookUrlTemplate = '@_urlService.GetAbsoluteUrl(WebRoutes.Books.EDIT_BOOK, new { bookId = default(Guid) })';
const EMPTY_GUID = '00000000-0000-0000-0000-000000000000';
const PAGE_SIZE = 50;
const favoritesContainer = document.getElementById('favorites-container');
const noFavoritesMessage = document.getElementById('no-favorites');
const favoriteCount = document.getElementById('favorite-count');
const kindFilter = document.getElementById('favorites-kind-filter');
const loadMoreButton = document.getElementById('load-more-favorites-button');
const retryButton = document.getElementById('retry-favorites-button');
let isInitialized = false;
let isLoading = false;
let requestSequence = 0;
let currentKind = '';
let hasLoadedWindow = false;
let hasLoadFailed = false;
let isRetrying = false;
// The page of the last loaded window, the page size, the total number of pages, the number of cards that are rendered and
// the total the server reported for the current filter.
let currentPage = 1;
let perPage = PAGE_SIZE;
let numberOfPages = 0;
let loadedCount = 0;
let totalCount = 0;
// A removal shifts one item of the next page into the last loaded page, so the next load more reads that page again.
let isWindowStale = false;
function isKnownId(id) {
return typeof id === 'string' && id !== '' && id !== EMPTY_GUID;
}
// Builds the page route of the item of a favorite. Returns an empty string when the page of the item cannot be addressed,
// for example a track whose album is not known, so the card is rendered without a link instead of with a broken one.
function buildItemUrl(item) {
if (!isKnownId(item.libraryId))
return '';
const libraryQuery = `?libraryId=${encodeURIComponent(item.libraryId)}`;
switch (item.mediaKind) {
case 'MusicArtist':
return artistUrlTemplate.replace(`/${EMPTY_GUID}`, `/${item.mediaItemId}`) + libraryQuery;
case 'MusicAlbum':
if (!isKnownId(item.creatorId))
return '';
return albumUrlTemplate.replace(`/${EMPTY_GUID}`, `/${item.creatorId}`).replace(`/${EMPTY_GUID}`, `/${item.mediaItemId}`) + libraryQuery;
case 'MusicTrack':
if (!isKnownId(item.creatorId) || !isKnownId(item.collectionId))
return '';
return trackUrlTemplate.replace(`/${EMPTY_GUID}`, `/${item.creatorId}`).replace(`/${EMPTY_GUID}`, `/${item.collectionId}`).replace(`/${EMPTY_GUID}`, `/${item.mediaItemId}`) + libraryQuery;
case 'Book':
return bookUrlTemplate.replace(`/${EMPTY_GUID}`, `/${item.mediaItemId}`) + libraryQuery;
default:
return '';
}
}
// The creator and the collection of the item, for example the artist and the album of a track, on one line.
function buildSubtitle(item) {
return [item.creatorName, item.collectionTitle].filter(value => value).join(' - ');
}
function createTextLine(text, isKindLine) {
const line = document.createElement('span');
line.className = 'text-light-two';
line.textContent = text;
line.style.display = 'block';
line.style.width = '200px';
line.style.height = 'auto';
line.style.boxSizing = 'border-box';
line.style.textAlign = 'center';
if (isKindLine) {
line.style.padding = '0 4px 4px';
line.style.fontSize = '12px';
line.style.opacity = '0.6';
} else {
line.style.padding = '0 4px';
line.style.whiteSpace = 'nowrap';
line.style.overflow = 'hidden';
line.style.textOverflow = 'ellipsis';
line.style.opacity = '0.8';
}
return line;
}
function findCard(mediaKind, mediaItemId) {
const itemId = String(mediaItemId).toLowerCase();
return Array.from(favoritesContainer.querySelectorAll('.media-card'))
.find(card => card.dataset.mediaKind === mediaKind && card.dataset.mediaItemId.toLowerCase() === itemId) || null;
}
// The heart of a card, drawn by the application style sheet like the actions trigger of the library cards, which the cards
// of this page do not have. It is a plain button: the global favorites script finds it by its data attributes, hydrates its state and handles its click.
function createFavoriteToggle(item) {
const toggle = document.createElement('button');
toggle.type = 'button';
toggle.className = 'card-favorite-toggle';
toggle.setAttribute('data-favorite-toggle', '');
toggle.setAttribute('data-favorite-media-kind', item.mediaKind);
toggle.setAttribute('data-favorite-media-item-id', item.mediaItemId);
// Every card of this page is a favorite, so the toggle starts in that state and does not flash while the global favorites
// script checks it. The script confirms the state and keeps the accessible name and the hover text in its language.
toggle.setAttribute('aria-pressed', 'true');
toggle.setAttribute('data-favorite-state', 'favorited');
return toggle;
}
function createFavoriteCard(item) {
const isAvailable = item.isAvailable === true;
const itemUrl = isAvailable ? buildItemUrl(item) : '';
const card = document.createElement('div');
card.className = 'media-card';
card.dataset.mediaKind = item.mediaKind;
card.dataset.mediaItemId = item.mediaItemId;
// A card without a page to open is not a link: the unavailable items have nothing to open, and a link to nowhere
// would only mislead the keyboard and the screen reader users.
const panel = document.createElement(itemUrl ? 'a' : 'div');
panel.className = itemUrl ? 'media-panel nav-link no-underline' : 'media-panel no-underline';
panel.style.width = '200px';
panel.style.height = 'auto';
if (itemUrl)
panel.href = itemUrl;
else
panel.style.cursor = 'default';
// The cover is shown as a square, cropped from its center (never stretched), like the cards of the library pages.
const image = document.createElement('img');
image.src = isAvailable && item.coverPath
? `${globalConfiguration.serverBasePath}${item.coverPath}`
: (item.mediaKind === 'Book' ? '/images/ui/book-placeholder.svg' : '/images/ui/music-placeholder.svg');
image.alt = '';
image.style.width = '200px';
image.style.height = '200px';
image.style.flexGrow = '0';
image.style.objectFit = 'cover';
image.style.objectPosition = 'center';
panel.appendChild(image);
// The title of an available item is kept on a single line, truncated with an ellipsis when it does not fit, so that all the cards share
// the same height. The unavailable message is a whole sentence and wraps on its own lines instead.
const titleSpan = document.createElement('span');
titleSpan.className = 'text-light-two';
titleSpan.style.display = 'block';
titleSpan.style.width = '200px';
titleSpan.style.boxSizing = 'border-box';
titleSpan.style.height = 'auto';
titleSpan.style.padding = '4px';
titleSpan.style.textAlign = 'center';
titleSpan.style.whiteSpace = 'nowrap';
titleSpan.style.overflow = 'hidden';
titleSpan.style.textOverflow = 'ellipsis';
const title = document.createElement('strong');
title.textContent = isAvailable ? item.title : strings.unavailable;
titleSpan.appendChild(title);
titleSpan.title = title.textContent;
// The unavailable message is a whole sentence, so it wraps instead of being cut to fit the single title line of an item.
if (!isAvailable) {
titleSpan.style.whiteSpace = 'normal';
titleSpan.style.overflow = 'visible';
titleSpan.style.textOverflow = 'clip';
}
panel.appendChild(titleSpan);
// The subtitle line is always rendered, with a non-breaking space when there is nothing to show, so that every card has the same
// number of lines and therefore the same height, whatever the kind of the favorite.
const subtitle = isAvailable ? buildSubtitle(item) : '';
const subtitleLine = createTextLine(subtitle || '\u00A0', false);
if (subtitle)
subtitleLine.title = subtitle;
panel.appendChild(subtitleLine);
panel.appendChild(createTextLine(strings[`kind${item.mediaKind}`] || item.mediaKind, true));
card.appendChild(panel);
card.appendChild(createFavoriteToggle(item));
return card;
}
function updateState() {
const hasCards = loadedCount > 0;
// A removal shifts one item of the next page into the last loaded page even when it was the last page, so the rendered
// count, not the page number alone, decides whether that shifted item still has to be fetched.
const hasMore = hasLoadedWindow && (currentPage < numberOfPages || (isWindowStale && loadedCount < totalCount));
// The empty state appears only after a window of the current filter was received, so it never flashes while the first
// window is loading, and the failure message replaces it when that window or a later reload failed.
const showEmptyState = hasLoadedWindow && !hasCards && !hasMore;
// Clearing the message while a retry is in flight lets the live region announce the failure again when the message returns.
noFavoritesMessage.textContent = isRetrying
? ''
: (hasLoadFailed ? strings.loadFailed : (currentKind === '' ? strings.noFavorites : strings.noFavoritesInKind));
noFavoritesMessage.classList.toggle('hidden', !hasLoadFailed && !showEmptyState);
favoriteCount.textContent = totalCount > 0 ? `${totalCount} ${strings.itemsCount}` : '';
loadMoreButton.classList.toggle('hidden', hasLoadFailed || isRetrying || !hasMore);
loadMoreButton.disabled = isLoading;
if (retryButton) {
retryButton.classList.toggle('hidden', !hasLoadFailed && !isRetrying);
retryButton.disabled = isLoading;
retryButton.setAttribute('aria-busy', isRetrying ? 'true' : 'false');
}
}
function buildFavoritesUrl(page) {
const parameters = new URLSearchParams();
if (currentKind !== '')
parameters.set('mediaKind', currentKind);
parameters.set('currentPage', page);
parameters.set('perPage', perPage);
return `${getFavoritesUrl}?${parameters.toString()}`;
}
// Loads a page of the favorites and renders it. A reload replaces the cards, which is what changing the filter does, and a
// load more appends the next page. An answer that was overtaken by a newer request is dropped.
async function loadFavoritesAsync(isAppend, isRetry = false, shouldRestartFromFirstPage = true) {
const requestId = ++requestSequence;
// A reload starts again from the first page of the filter. A load more asks for the page after the last one, or asks for
// the last one again when a removal shifted an item of the next page into it.
const requestedPage = isAppend ? (isWindowStale ? currentPage : currentPage + 1) : 1;
// A reload starts a new page chain for the filter, so the empty state stays hidden until its first answer arrives. A retry keeps
// the failure message and the retry button visible, with the button disabled and marked busy, until the answer arrives.
isRetrying = isRetry;
if (!isAppend) {
hasLoadedWindow = false;
if (!isRetry)
hasLoadFailed = false;
}
isLoading = true;
updateState();
const page = await callApiGetAsync(buildFavoritesUrl(requestedPage));
if (requestId !== requestSequence)
return;
isLoading = false;
isRetrying = false;
if (!page || !Array.isArray(page.data)) {
// The API helper already reported the failure. A reload has nothing left to show, so it clears the cards of the
// previous page and leaves a retry instead of hiding the only way to continue. A failed load more keeps its
// button, because the rendered page is still valid.
if (!isAppend) {
favoritesContainer.querySelectorAll('.media-card').forEach(card => card.remove());
loadedCount = 0;
currentPage = 1;
perPage = PAGE_SIZE;
numberOfPages = 0;
totalCount = 0;
hasLoadedWindow = false;
hasLoadFailed = true;
isWindowStale = false;
}
updateState();
if (isRetry)
focusAfterReload('', '');
return;
}
const wasWindowStale = isWindowStale;
if (!isAppend) {
favoritesContainer.querySelectorAll('.media-card').forEach(card => card.remove());
loadedCount = 0;
}
let pageHasRenderedItems = false;
page.data.forEach(item => {
// An item favorited since an earlier page shifts the list, so the same favorite could come twice. The card that is
// already rendered is kept, but the duplicate means the page chain no longer matches the rendered rows.
if (findCard(item.mediaKind, item.mediaItemId)) {
pageHasRenderedItems = true;
return;
}
favoritesContainer.appendChild(createFavoriteCard(item));
loadedCount++;
});
isWindowStale = false;
currentPage = Number.isInteger(page.currentPage) && page.currentPage > 0 ? page.currentPage : requestedPage;
perPage = Number.isInteger(page.perPage) && page.perPage > 0 ? page.perPage : PAGE_SIZE;
totalCount = Number.isInteger(page.count) ? page.count : loadedCount;
numberOfPages = Number.isInteger(page.numberOfPages) ? page.numberOfPages : (perPage > 0 ? Math.ceil(totalCount / perPage) : 0);
// An empty page means there is nothing more to read, even when a stale total still claims otherwise.
if (page.data.length === 0) {
totalCount = Math.min(totalCount, loadedCount);
numberOfPages = Math.min(numberOfPages, currentPage);
}
// An item favorited in another tab or on another device shifts every server page after it. The page then contains cards that
// are already rendered, and the last page can be reached while cards are still missing. Both mean the page chain no longer
// covers the rendered rows, so the only consistent window is a fresh read from the first page. The stale re-read after a
// removal is excluded, because that overlap is expected there and it keeps the card of the shifted item.
if (shouldRestartFromFirstPage && ((!wasWindowStale && pageHasRenderedItems) || (currentPage >= numberOfPages && loadedCount < totalCount))) {
await loadFavoritesAsync(false, false, false);
// The restart is a fresh read, so it does not carry the retry flag. The outer retry still owns the focus, and the inner
// call replaced the cards and hid the retry button, so the focus has to move after it completes.
if (isRetry)
focusAfterReload('', '');
return;
}
hasLoadedWindow = true;
hasLoadFailed = false;
bindNavigationLinks();
updateState();
if (isRetry)
focusAfterReload('', '');
}
async function loadMoreAsync() {
if (isLoading)
return;
await loadFavoritesAsync(true);
}
async function retryLoadAsync() {
if (isLoading)
return;
await loadFavoritesAsync(false, true);
}
// Moves focus into the window a removal or a retry loaded: the neighboring card when it is still there, the first card otherwise,
// the load more button or the retry button, and finally the visible message when the window is empty.
function focusAfterReload(neighborKind, neighborId) {
const refreshedNeighbor = neighborKind ? findCard(neighborKind, neighborId) : null;
const firstCard = favoritesContainer.querySelector('.media-card');
const focusTarget = refreshedNeighbor || firstCard;
const focusToggle = focusTarget ? focusTarget.querySelector('[data-favorite-toggle]') : null;
if (focusToggle)
focusToggle.focus();
else if (!loadMoreButton.classList.contains('hidden'))
loadMoreButton.focus();
else if (retryButton && !retryButton.classList.contains('hidden'))
retryButton.focus();
else if (!noFavoritesMessage.classList.contains('hidden'))
noFavoritesMessage.focus();
}
// Removes the card of an item that is no longer a favorite, and moves the keyboard focus to the neighboring card, so a keyboard user is not dropped to the top of the page.
async function handleFavoriteChanged(event) {
const detail = event.detail;
if (!detail || detail.isFavorite)
return;
const card = findCard(detail.mediaKind, detail.mediaItemId);
if (!card)
return;
const neighbor = card.nextElementSibling || card.previousElementSibling;
const neighborKind = neighbor ? neighbor.dataset.mediaKind : '';
const neighborId = neighbor ? neighbor.dataset.mediaItemId : '';
const hadFocus = card.contains(document.activeElement);
card.remove();
loadedCount--;
totalCount = Math.max(0, totalCount - 1);
numberOfPages = perPage > 0 ? Math.ceil(totalCount / perPage) : 0;
// A page that was requested before this removal describes the list that still contained the item, so neither its
// cards nor its total can be applied. Drop it and load the first page again.
const mustReload = isLoading;
if (mustReload) {
requestSequence++;
isLoading = false;
hasLoadedWindow = false;
isWindowStale = false;
updateState();
await loadFavoritesAsync(false);
if (hadFocus)
focusAfterReload(neighborKind, neighborId);
return;
}
// The list lost one item, so one item of the next page shifted into the last loaded page. The next load more reads
// that page again, so the shifted item is not skipped.
isWindowStale = true;
updateState();
// Every rendered card was removed but the user has more favorites, so the first page is loaded again instead of
// starting from a page that no longer matches the empty screen. Focus moves after that reload, because it
// replaces the cards and hides the load more button the old focus fallback would have chosen.
if (loadedCount === 0 && totalCount > 0) {
await loadFavoritesAsync(false);
if (hadFocus)
focusAfterReload(neighborKind, neighborId);
return;
}
if (hadFocus) {
const neighborToggle = neighbor ? neighbor.querySelector('[data-favorite-toggle]') : null;
if (neighborToggle)
neighborToggle.focus();
else if (!loadMoreButton.classList.contains('hidden'))
loadMoreButton.focus();
}
}
function handleKindFilterClick(event) {
const option = event.target.closest('.enlightenment-option');
if (!option || option.classList.contains('disabled'))
return;
const selected = kindFilter.querySelector('.enlightenment-selected-text');
if (selected) {
selected.textContent = option.textContent;
selected.setAttribute('data-value', option.getAttribute('data-value') || '');
}
const toggle = kindFilter.querySelector('.enlightenment-toggle-checkbox');
if (toggle)
toggle.checked = false;
const kind = option.getAttribute('data-value') || '';
if (kind === currentKind)
return;
currentKind = kind;
loadFavoritesAsync(false);
}
document.addEventListener('lumina:favorite-changed', handleFavoriteChanged);
if (kindFilter)
kindFilter.addEventListener('click', handleKindFilterClick);
if (loadMoreButton)
loadMoreButton.addEventListener('click', loadMoreAsync);
if (retryButton)
retryButton.addEventListener('click', retryLoadAsync);
async function InitializeAsync() {
if (isInitialized)
return;
if (!favoritesContainer)
return;
isInitialized = true;
await loadFavoritesAsync(false);
}
window.viewCleanups = window.viewCleanups || {};
window.viewCleanups['@scriptId'] = () => {
document.removeEventListener('lumina:favorite-changed', handleFavoriteChanged);
if (kindFilter)
kindFilter.removeEventListener('click', handleKindFilterClick);
if (loadMoreButton)
loadMoreButton.removeEventListener('click', loadMoreAsync);
if (retryButton)
retryButton.removeEventListener('click', retryLoadAsync);
console.log(`Unloaded @scriptId`);
};
console.log(`Loaded @scriptId`);
</script>
}
@@ -137,6 +137,7 @@
<col class="track-number-column" />
<col />
<col class="track-duration-column" />
<col class="track-favorite-column" />
<col class="track-actions-column" />
</colgroup>
<tbody id="tracks-body"></tbody>
@@ -995,7 +996,7 @@
}
// Creates a row of the tracks table, with the play trigger, the number, the name of the track linking to its own page,
// the duration and the actions menu of the track.
// the duration, the favorite heart and the actions menu of the track.
function createTrackRow(track) {
const row = document.createElement('tr');
row.className = 'track-row';
@@ -1021,10 +1022,26 @@
row.appendChild(numberCell);
row.appendChild(nameCell);
row.appendChild(durationCell);
row.appendChild(createTrackFavoriteCell(track));
row.appendChild(createTrackActionsCell(track));
return row;
}
// Creates the favorite cell of a track row, right after the duration. The heart is a plain button: the global favorites
// script finds it by its data attributes, hydrates its state and handles its click.
function createTrackFavoriteCell(track) {
const cell = document.createElement('td');
cell.className = 'track-favorite-cell';
const favoriteToggle = document.createElement('button');
favoriteToggle.type = 'button';
favoriteToggle.className = 'card-favorite-toggle track-favorite-toggle';
favoriteToggle.setAttribute('data-favorite-toggle', '');
favoriteToggle.setAttribute('data-favorite-media-kind', 'MusicTrack');
favoriteToggle.setAttribute('data-favorite-media-item-id', track.id);
cell.appendChild(favoriteToggle);
return cell;
}
// Gets the singleton audio player, or null when the layout did not render it.
function getAudioPlayer() {
return window.LuminaAudioPlayer && window.LuminaAudioPlayer.instance
@@ -298,7 +298,16 @@
await updateContentAsync(menuItem.href, true);
});
// The favorite heart is a plain button: the global favorites script finds it by its data attributes, hydrates its state and handles its click.
const favoriteToggle = document.createElement('button');
favoriteToggle.type = 'button';
favoriteToggle.className = 'card-favorite-toggle';
favoriteToggle.setAttribute('data-favorite-toggle', '');
favoriteToggle.setAttribute('data-favorite-media-kind', 'MusicArtist');
favoriteToggle.setAttribute('data-favorite-media-item-id', artist.id);
card.appendChild(cardLink);
card.appendChild(favoriteToggle);
card.appendChild(trigger);
card.appendChild(menu);
@@ -1159,7 +1159,16 @@
await deleteAlbumAsync(card.dataset.albumId);
});
// The favorite heart is a plain button: the global favorites script finds it by its data attributes, hydrates its state and handles its click.
const favoriteToggle = document.createElement('button');
favoriteToggle.type = 'button';
favoriteToggle.className = 'card-favorite-toggle';
favoriteToggle.setAttribute('data-favorite-toggle', '');
favoriteToggle.setAttribute('data-favorite-media-kind', 'MusicAlbum');
favoriteToggle.setAttribute('data-favorite-media-item-id', album.id);
card.appendChild(cardLink);
card.appendChild(favoriteToggle);
card.appendChild(trigger);
card.appendChild(menu);
@@ -226,7 +226,16 @@
await updateContentAsync(menuItem.href, true);
});
// The favorite heart is a plain button: the global favorites script finds it by its data attributes, hydrates its state and handles its click.
const favoriteToggle = document.createElement('button');
favoriteToggle.type = 'button';
favoriteToggle.className = 'card-favorite-toggle';
favoriteToggle.setAttribute('data-favorite-toggle', '');
favoriteToggle.setAttribute('data-favorite-media-kind', 'Book');
favoriteToggle.setAttribute('data-favorite-media-item-id', book.id);
card.appendChild(cardLink);
card.appendChild(favoriteToggle);
card.appendChild(trigger);
card.appendChild(menu);
@@ -54,6 +54,7 @@
["track"] = _localizer["Track"].Value,
["add"] = _localizer["Add"].Value,
["addFailed"] = _localizer["AddFailed"].Value,
["refreshFailed"] = _localizer["RefreshFailed"].Value,
["selectLibrary"] = _localizer["SelectLibrary"].Value,
["selectArtist"] = _localizer["SelectArtist"].Value,
["selectAlbum"] = _localizer["SelectAlbum"].Value,
@@ -276,10 +277,23 @@
const addTrackButton = document.getElementById('add-track-button');
const noMusicLibrariesMessage = document.getElementById('no-music-libraries');
const loadMoreEntriesButton = document.getElementById('load-more-entries-button');
const entriesWindowSize = 200;
// The global position of the first row currently on screen. Local row indexes are only meaningful after adding this offset, which
// is why the move and Load more logic use it for every comparison against the whole playlist.
const DEFAULT_PAGE_SIZE = 200;
// The page the first rendered row belongs to, the size of each page and the total number of pages. The global position of the
// first row currently on screen is derived from the page, and local row indexes are only meaningful after adding this offset,
// which is why the move and Load more logic use it for every comparison against the whole playlist.
let currentPage = 1;
let perPage = DEFAULT_PAGE_SIZE;
let numberOfPages = 0;
let entriesOffset = 0;
if (playlist && playlist.entries) {
if (Number.isInteger(playlist.entries.currentPage) && playlist.entries.currentPage > 0)
currentPage = playlist.entries.currentPage;
if (Number.isInteger(playlist.entries.perPage) && playlist.entries.perPage > 0)
perPage = playlist.entries.perPage;
if (Number.isInteger(playlist.entries.numberOfPages))
numberOfPages = playlist.entries.numberOfPages;
entriesOffset = (currentPage - 1) * perPage;
}
let isInitialized = false;
let draggedEntryId = null;
let dragWasDropped = false;
@@ -289,6 +303,32 @@
return itemUrlTemplate.replace(`/${EMPTY_GUID}`, `/${playlistId}`);
}
// The entries of the page currently rendered, and the total the server reported for the whole playlist.
function getPlaylistEntries() {
return playlist && playlist.entries && Array.isArray(playlist.entries.data) ? playlist.entries.data : [];
}
function getPlaylistEntryCount() {
return playlist && playlist.entries && Number.isFinite(playlist.entries.count) ? playlist.entries.count : getPlaylistEntries().length;
}
function findEntryRow(entryId) {
if (!entriesContainer)
return null;
return Array.from(entriesContainer.querySelectorAll('.playlist-entry'))
.find(row => row.dataset.entryId === entryId) || null;
}
// Applies a playlist read back from the server and derives the global position of its first row.
function applyPlaylistPage(page) {
playlist = page;
const entries = page && page.entries ? page.entries : null;
currentPage = entries && Number.isInteger(entries.currentPage) && entries.currentPage > 0 ? entries.currentPage : 1;
perPage = entries && Number.isInteger(entries.perPage) && entries.perPage > 0 ? entries.perPage : DEFAULT_PAGE_SIZE;
numberOfPages = entries && Number.isInteger(entries.numberOfPages) ? entries.numberOfPages : 0;
entriesOffset = (currentPage - 1) * perPage;
}
function formatDuration(totalSeconds) {
const seconds = Number.isFinite(Number(totalSeconds)) ? Math.max(0, Math.floor(Number(totalSeconds))) : 0;
const minutes = Math.floor(seconds / 60);
@@ -387,12 +427,12 @@
}
}
// Shows the load more control only while the page has entry windows left to fetch.
// Shows the load more control only while the page has entry pages left to fetch.
function updateLoadMoreButton() {
if (!loadMoreEntriesButton)
return;
const loaded = Array.isArray(playlist.entries) ? playlist.entries.length : 0;
const total = Number.isFinite(playlist.entryCount) ? playlist.entryCount : loaded;
const loaded = getPlaylistEntries().length;
const total = getPlaylistEntryCount();
// The rows on screen start at entriesOffset, not at the beginning of the playlist, so the loaded count alone cannot tell
// whether the whole playlist is on screen.
const hasMore = entriesOffset + loaded < total;
@@ -413,37 +453,89 @@
if (!entriesContainer)
return;
entriesContainer.querySelectorAll('.playlist-entry').forEach(row => row.remove());
const entries = Array.isArray(playlist.entries) ? playlist.entries : [];
const total = Number.isFinite(playlist.entryCount) ? playlist.entryCount : entries.length;
const entries = getPlaylistEntries();
const total = getPlaylistEntryCount();
if (total === 0) {
noTracksMessage.classList.remove('hidden');
return;
}
noTracksMessage.classList.add('hidden');
entries.forEach((entry, index) => entriesContainer.appendChild(createEntryRow(entry, index, entries.length)));
entries.forEach((entry, index) => entriesContainer.appendChild(createEntryRow(entry, index)));
updateLoadMoreButton();
}
// Fetches the next window of entries and appends it to the rows already on screen.
// Whether the fetched page proves that the rendered window no longer matches the server. A page behind the requested one means
// the server clamped it because the playlist shrank, and a total smaller than the rendered rows means the rows themselves are
// stale. Neither can be fixed by appending, so the caller reloads the first page instead.
function pageShrankBeforeWindow(page, requestedPage) {
if (!page || !page.entries)
return false;
const resolvedPage = Number.isInteger(page.entries.currentPage) && page.entries.currentPage > 0
? page.entries.currentPage
: requestedPage;
return resolvedPage < requestedPage
|| (Number.isInteger(page.entries.count) && page.entries.count < entriesOffset + getPlaylistEntries().length);
}
// Replaces the rendered rows with the first page, which is the only window that is valid after the playlist shrank.
async function reloadFirstPageAsync() {
const page = await callApiGetAsync(`${getPlaylistUrl}?currentPage=1&perPage=${perPage}`);
if (!page || !page.entries || !Array.isArray(page.entries.data))
return false;
applyPlaylistPage(page);
renderPlaylist();
return true;
}
// Merges the entries of one fetched page into the rows already on screen, without replacing them. A page that starts after the
// first entry that is not on screen would leave a hole in the rendered rows, so it is not merged and the Load more state stays
// responsible for reaching it. The rows are numbered from entriesOffset, which is only valid while the rendered entries are
// contiguous, so a page that overlaps the rendered rows is merged by Id and a page after a gap is left for Load more.
function mergeEntriesPage(page, pageNumber) {
if (!entriesContainer || !page || !page.entries || !Array.isArray(page.entries.data))
return false;
// The server can clamp the requested page to the last one, so its answer is the page that actually arrived.
const resolvedPage = Number.isInteger(page.entries.currentPage) && page.entries.currentPage > 0 ? page.entries.currentPage : pageNumber;
const pageStart = (resolvedPage - 1) * perPage;
const entries = getPlaylistEntries();
if (pageStart < entriesOffset || pageStart > entriesOffset + entries.length)
return false;
page.entries.data.forEach(entry => {
if (findEntryRow(entry.id))
return;
entries.push(entry);
entriesContainer.appendChild(createEntryRow(entry, entries.length - 1));
});
playlist.entries.count = page.entries.count;
playlist.entries.numberOfPages = page.entries.numberOfPages;
numberOfPages = Number.isInteger(page.entries.numberOfPages) ? page.entries.numberOfPages : numberOfPages;
refreshEntryRows();
return true;
}
// Fetches the next page of entries and appends it to the rows already on screen.
async function loadMoreEntriesAsync() {
if (!entriesContainer || !loadMoreEntriesButton || isEntryMutationInFlight)
return;
const loaded = Array.isArray(playlist.entries) ? playlist.entries.length : 0;
const total = Number.isFinite(playlist.entryCount) ? playlist.entryCount : loaded;
const loaded = getPlaylistEntries().length;
const total = getPlaylistEntryCount();
// The loaded rows begin at entriesOffset, so they cover the playlist only when offset plus loaded reaches the total.
if (entriesOffset + loaded >= total)
return;
// The next page is the one that contains the first entry that is not on screen yet. A removal shifts the entries by one,
// so this page can overlap the rows already rendered; rows are appended by Id, so the overlap is skipped and the shifted entry is not lost.
const nextPage = Math.floor((entriesOffset + loaded) / perPage) + 1;
if (numberOfPages > 0 && nextPage > numberOfPages)
return;
setEntryMutationInFlight(true);
try {
const page = await callApiGetAsync(`${getPlaylistUrl}?offset=${entriesOffset + loaded}&limit=${entriesWindowSize}`);
if (!page || !Array.isArray(page.entries))
const page = await callApiGetAsync(`${getPlaylistUrl}?currentPage=${nextPage}&perPage=${perPage}`);
if (pageShrankBeforeWindow(page, nextPage)) {
if (!await reloadFirstPageAsync())
notificationService.show(strings.refreshFailed, NotificationType.ERROR);
return;
playlist.entryCount = page.entryCount;
page.entries.forEach(entry => {
playlist.entries.push(entry);
entriesContainer.appendChild(createEntryRow(entry, playlist.entries.length - 1, playlist.entries.length));
});
refreshEntryRows();
}
mergeEntriesPage(page, nextPage);
} finally {
setEntryMutationInFlight(false);
}
@@ -454,7 +546,7 @@
if (!entriesContainer)
return;
const rows = Array.from(entriesContainer.querySelectorAll('.playlist-entry'));
const total = Number.isFinite(playlist.entryCount) ? playlist.entryCount : rows.length;
const total = getPlaylistEntryCount();
rows.forEach((row, index) => {
// The move controls are guarded by the global position of the row, not by its index inside the loaded window.
const globalIndex = entriesOffset + index;
@@ -483,7 +575,7 @@
return;
// Use the rows already on screen, not the post-push entries length, so the new row is numbered correctly before refreshEntryRows.
const index = entriesContainer.querySelectorAll('.playlist-entry').length;
entriesContainer.appendChild(createEntryRow(entry, index, index + 1));
entriesContainer.appendChild(createEntryRow(entry, index));
refreshEntryRows();
}
@@ -514,11 +606,11 @@
// Keeps the in-memory entries in the same order as the rows, so playback and later moves use the order on screen.
function syncPlaylistEntriesFromOrder(orderedEntryIds) {
const entriesById = new Map((playlist.entries || []).map(entry => [entry.id, entry]));
playlist.entries = orderedEntryIds
const entriesById = new Map(getPlaylistEntries().map(entry => [entry.id, entry]));
playlist.entries.data = orderedEntryIds
.map(entryId => entriesById.get(entryId))
.filter(entry => !!entry);
playlist.entries.forEach((entry, index) => entry.position = entriesOffset + index);
playlist.entries.data.forEach((entry, index) => entry.position = entriesOffset + index);
}
// Applies a details update without touching the rows of the playlist.
@@ -534,7 +626,7 @@
playlistDescriptionInput.value = playlist.description;
}
function createEntryRow(entry, index, count) {
function createEntryRow(entry, index) {
const row = document.createElement('div');
row.className = 'playlist-entry form-row';
row.dataset.entryId = entry.id;
@@ -576,7 +668,7 @@
else
// Escape, or a drop outside the list, cancels the drag. The DOM was already reordered while dragging, so it is
// restored to the last order the server accepted instead of persisting the cancelled order.
applyEntryOrderByIds((playlist.entries || []).map(entry => entry.id));
applyEntryOrderByIds(getPlaylistEntries().map(entry => entry.id));
});
row.appendChild(dragHandle);
@@ -663,7 +755,7 @@
// The index passed to this function is local to the rendered rows. Disabling the move controls requires the global position,
// otherwise the first row of a window that does not start at zero looks like the first row of the whole playlist.
const total = Number.isFinite(playlist.entryCount) ? playlist.entryCount : entriesOffset + count;
const total = getPlaylistEntryCount();
const globalIndex = entriesOffset + index;
const moveUpButton = document.createElement('button');
@@ -701,7 +793,7 @@
return;
const orderedEntryIds = Array.from(entriesContainer.querySelectorAll('.playlist-entry'))
.map(row => row.dataset.entryId);
const currentEntryIds = (playlist.entries || []).map(entry => entry.id);
const currentEntryIds = getPlaylistEntries().map(entry => entry.id);
if (orderedEntryIds.length !== currentEntryIds.length) {
applyEntryOrderByIds(currentEntryIds);
return;
@@ -748,26 +840,40 @@
return;
if (detail.playlist && detail.playlist.id && detail.playlist.id !== playlist.id)
return;
// An append made elsewhere only announces the playlist Id. Re-read the window the user is currently looking at, instead of
// resetting the view to the first window and throwing a user who is deep in a large playlist back to the top.
const currentOffset = entriesOffset;
const updatedPlaylist = await callApiGetAsync(`${getPlaylistUrl}?offset=${currentOffset}&limit=${entriesWindowSize}`);
if (!updatedPlaylist)
// A local mutation already refreshes the view, so an external event that arrives while one is running must not read a
// playlist that the mutation is still changing. Dropping it avoids replacing the rows with an answer taken mid-write.
if (isEntryMutationInFlight)
return;
if (currentOffset > 0 && updatedPlaylist.entries.length === 0 && updatedPlaylist.entryCount > 0) {
// The playlist shrank past this window. Show the last window instead of an empty page.
const lastWindowOffset = Math.max(0, updatedPlaylist.entryCount - entriesWindowSize);
const lastWindow = await callApiGetAsync(`${getPlaylistUrl}?offset=${lastWindowOffset}&limit=${entriesWindowSize}`);
if (!lastWindow)
setEntryMutationInFlight(true);
try {
// An append made elsewhere announces either a batch result with addedCount, or a single entry result with entry.
// The rows on screen start at currentPage, which is the first rendered page and never advances when more pages are
// loaded. The page to read is therefore the first page that is not fully rendered, not currentPage. Reading it merges
// the appended entries into the rows already on screen instead of replacing pages 2 and later with page 1.
const addedCount = Number.isInteger(detail.addedCount) ? detail.addedCount : (detail.entry ? 1 : 0);
if (addedCount > 0) {
playlist.entries.count = getPlaylistEntryCount() + addedCount;
playlist.entries.numberOfPages = perPage > 0 ? Math.ceil(playlist.entries.count / perPage) : 0;
numberOfPages = playlist.entries.numberOfPages;
}
if (detail.updatedOnUtc)
playlist.updatedOnUtc = detail.updatedOnUtc;
const loaded = getPlaylistEntries().length;
const nextPage = Math.floor((entriesOffset + loaded) / perPage) + 1;
if (nextPage > numberOfPages)
return;
entriesOffset = lastWindowOffset;
playlist = lastWindow;
renderPlaylist();
return;
const page = await callApiGetAsync(`${getPlaylistUrl}?currentPage=${nextPage}&perPage=${perPage}`);
if (!page || !page.entries || !Array.isArray(page.entries.data))
return;
if (pageShrankBeforeWindow(page, nextPage)) {
if (!await reloadFirstPageAsync())
notificationService.show(strings.refreshFailed, NotificationType.ERROR);
return;
}
mergeEntriesPage(page, nextPage);
} finally {
setEntryMutationInFlight(false);
}
entriesOffset = currentOffset;
playlist = updatedPlaylist;
renderPlaylist();
}
async function saveDetailsAsync(event) {
@@ -823,7 +929,7 @@
// The server accepts a target position anywhere in the whole playlist. The target is therefore compared with the global
// position of the row, so the first row of a shifted window can still move up and the last loaded row can still move down into
// the entries that are not loaded yet.
const total = Number.isFinite(playlist.entryCount) ? playlist.entryCount : orderedEntryIds.length;
const total = getPlaylistEntryCount();
const targetGlobalIndex = entriesOffset + index + offset;
if (targetGlobalIndex < 0 || targetGlobalIndex >= total)
return;
@@ -834,11 +940,11 @@
playlist.updatedOnUtc = result.data.updatedOnUtc;
const isOutsideLoadedWindow = targetGlobalIndex < entriesOffset || targetGlobalIndex >= entriesOffset + orderedEntryIds.length;
if (isOutsideLoadedWindow) {
// The row moved into a window that is not loaded, so another entry moved into its place. Re-read the current window
// The row moved into a page that is not loaded, so another entry moved into its place. Re-read the current page
// instead of leaving an order on screen that the next Load more would duplicate.
const refreshedWindow = await callApiGetAsync(`${getPlaylistUrl}?offset=${entriesOffset}&limit=${entriesWindowSize}`);
if (refreshedWindow && Array.isArray(refreshedWindow.entries)) {
playlist = refreshedWindow;
const refreshedWindow = await callApiGetAsync(`${getPlaylistUrl}?currentPage=${currentPage}&perPage=${perPage}`);
if (refreshedWindow && refreshedWindow.entries && Array.isArray(refreshedWindow.entries.data)) {
applyPlaylistPage(refreshedWindow);
renderPlaylist();
} else
notificationService.show(strings.reorderFailed, NotificationType.ERROR);
@@ -867,11 +973,13 @@
try {
const removed = await callApiDeleteAsync(buildRemoveEntryUrl(entryId));
if (removed) {
// The row is removed from the existing DOM and the remaining rows are renumbered, so the page does not read the whole
// playlist back for a single removed entry.
playlist.entries = (playlist.entries || []).filter(entry => entry.id !== entryId);
playlist.entries.forEach((entry, index) => entry.position = entriesOffset + index);
playlist.entryCount = Math.max(0, (Number.isFinite(playlist.entryCount) ? playlist.entryCount : playlist.entries.length) - 1);
// The row is removed from the existing DOM and the remaining rows are renumbered, so the page does not read the whole playlist back for a single removed entry.
const totalBefore = getPlaylistEntryCount();
playlist.entries.data = getPlaylistEntries().filter(entry => entry.id !== entryId);
playlist.entries.data.forEach((entry, index) => entry.position = entriesOffset + index);
playlist.entries.count = Math.max(0, totalBefore - 1);
playlist.entries.numberOfPages = perPage > 0 ? Math.ceil(playlist.entries.count / perPage) : 0;
numberOfPages = playlist.entries.numberOfPages;
removeEntryRow(entryId);
} else
notificationService.show(strings.removeFailed, NotificationType.ERROR);
@@ -880,18 +988,21 @@
}
}
// Fetches every entry of the playlist in windows, for the explicit play action. A large playlist is never loaded for the page itself.
// Fetches every entry of the playlist page by page, for the explicit play action. A large playlist is never loaded for the page itself.
async function fetchAllPlaylistEntriesAsync() {
const allEntries = [];
let offset = 0;
let pageNumber = 1;
while (true) {
const page = await callApiGetAsync(`${getPlaylistUrl}?offset=${offset}&limit=1000`);
if (!page || !Array.isArray(page.entries) || page.entries.length === 0)
const page = await callApiGetAsync(`${getPlaylistUrl}?currentPage=${pageNumber}&perPage=1000`);
if (!page || !page.entries || !Array.isArray(page.entries.data) || page.entries.data.length === 0)
break;
allEntries.push(...page.entries);
offset += page.entries.length;
if (offset >= page.entryCount)
allEntries.push(...page.entries.data);
const totalPages = Number.isInteger(page.entries.numberOfPages) && page.entries.numberOfPages > 0
? page.entries.numberOfPages
: Math.max(1, Math.ceil(page.entries.count / 1000));
if (allEntries.length >= page.entries.count || pageNumber >= totalPages)
break;
pageNumber++;
}
return allEntries;
}
@@ -984,22 +1095,45 @@
try {
const added = await callApiPostAsync(addEntryUrl, { trackId });
if (added && added.entry) {
playlist.entries = Array.isArray(playlist.entries) ? playlist.entries : [];
const totalBefore = Number.isFinite(playlist.entryCount) ? playlist.entryCount : playlist.entries.length;
if (playlist.entries.length >= totalBefore) {
playlist.entries.push(added.entry);
playlist.entryCount = totalBefore + 1;
const entries = getPlaylistEntries();
const totalBefore = getPlaylistEntryCount();
if (entries.length >= totalBefore) {
entries.push(added.entry);
playlist.entries.count = totalBefore + 1;
playlist.entries.numberOfPages = perPage > 0 ? Math.ceil(playlist.entries.count / perPage) : 0;
numberOfPages = playlist.entries.numberOfPages;
playlist.updatedOnUtc = added.updatedOnUtc;
appendEntryRow(added.entry);
} else {
// The new entry is at the global end, beyond the loaded window, so the last window is loaded to show it.
// The new entry is at the global end, beyond the rendered rows. The count and the number of pages change even
// when the page that contains the new entry cannot be merged, because that page may start after the first entry
// that is not on screen. Keeping the optimistic values means Load more still leads to it.
const newCount = totalBefore + 1;
const newOffset = Math.max(0, newCount - entriesWindowSize);
const page = await callApiGetAsync(`${getPlaylistUrl}?offset=${newOffset}&limit=${entriesWindowSize}`);
if (page) {
entriesOffset = newOffset;
playlist = page;
renderPlaylist();
const newNumberOfPages = perPage > 0 ? Math.ceil(newCount / perPage) : 0;
playlist.entries.count = newCount;
playlist.entries.numberOfPages = newNumberOfPages;
numberOfPages = newNumberOfPages;
playlist.updatedOnUtc = added.updatedOnUtc;
// The last page is fetched to show the new entry, and merged only when it is the page that directly follows the
// rendered rows. When several pages are not on screen, replacing the rows with only the last page would hide the
// entries that were already rendered, so the page is left to Load more instead.
const lastPage = Math.max(1, Math.ceil(newCount / perPage));
const page = await callApiGetAsync(`${getPlaylistUrl}?currentPage=${lastPage}&perPage=${perPage}`);
if (!page || !page.entries || !Array.isArray(page.entries.data)) {
// The add is committed and the counts above already include it, but the rows could not be read back. Saying so
// is what keeps the user from adding the same track again because the list still looks unchanged.
notificationService.show(strings.refreshFailed, NotificationType.ERROR);
} else if (pageShrankBeforeWindow(page, lastPage)) {
// Another client shrank the playlist while the rows were on screen, and the server clamped the requested page
// behind them. Appending would keep rows that no longer exist, so the whole window is read again.
if (!await reloadFirstPageAsync())
notificationService.show(strings.refreshFailed, NotificationType.ERROR);
} else {
// The fetched page is authoritative for the totals, which can differ from the optimistic values when another request changed the playlist in the meantime.
playlist.entries.count = page.entries.count;
playlist.entries.numberOfPages = page.entries.numberOfPages;
numberOfPages = Number.isInteger(page.entries.numberOfPages) ? page.entries.numberOfPages : numberOfPages;
mergeEntriesPage(page, lastPage);
}
}
resetCombobox(trackCombobox, strings.selectTrack);
@@ -104,6 +104,20 @@
add: '@localizer["AudioPlayerAdd"]'
}
};
// The endpoints and labels of the favorite toggles that every media page and theme template can render. The script reads which
// items of a kind are favorites of the current user, adds a favorite, and removes one through the culture aware web routes, so
// the pages never hardcode a path. The remove route is rendered with its named mediaKind and mediaItemId placeholders intact, which
// the script fills in, so the two values keep their meaning even if the route segment order changes. The labels are serialized as
// script literals, because a localized text can contain characters that would end a quoted literal.
var favoritesConfiguration = {
getFavoriteStatusUrl: '@_urlService.GetRelativeUrl(WebRoutes.Favorites.GET_FAVORITE_STATUS)',
addFavoriteUrl: '@_urlService.GetRelativeUrl(WebRoutes.Favorites.ADD_FAVORITE)',
removeFavoriteUrlTemplate: '@_urlService.GetRelativeUrl(WebRoutes.Favorites.REMOVE_FAVORITE)',
strings: {
add: @Json.Serialize(localizer["FavoritesAdd"].Value),
remove: @Json.Serialize(localizer["FavoritesRemove"].Value)
}
};
</script>
@if (User?.Identity?.IsAuthenticated == true)
{
@@ -118,6 +132,7 @@
<script defer src="~/js/image-viewer.js" asp-append-version="true"></script>
<script defer src="~/js/site.js" asp-append-version="true"></script>
<script defer src="~/js/playlists.js" asp-append-version="true"></script>
<script defer src="~/js/favorites.js" asp-append-version="true"></script>
<script defer src="~/js/theme-client-template-engine.js" asp-append-version="true"></script>
<script defer src="~/js/audio-player/audio-player-utils.js" asp-append-version="true"></script>
<script defer src="~/js/audio-player/audio-player-errors.js" asp-append-version="true"></script>