mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 18:21:10 +00:00
Adds favorites and aligns playlist and favorite pagination
This commit is contained in:
1 parent
2e9f7d8496
commit
525ac1348d
193 files changed
+10944
-643
No files matched your search
-38
@@ -1,38 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a paginated collection of lightweight album elements, together with pagination metadata.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")]
|
||||
public class PaginatedMusicAlbumLiteDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the collection of lightweight album elements associated with this instance.
|
||||
/// </summary>
|
||||
public IReadOnlyList<MusicAlbumLiteDto> Data { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the current page number in a paginated collection.
|
||||
/// </summary>
|
||||
public int CurrentPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of items to include per page in paginated results.
|
||||
/// </summary>
|
||||
public int PerPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of elements available in the paginated result set.
|
||||
/// </summary>
|
||||
public int Count { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of pages based on elements available in the result set and per page.
|
||||
/// </summary>
|
||||
public int NumberOfPages { get; set; }
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a paginated collection of lightweight music artist elements, together with pagination metadata.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")]
|
||||
public class PaginatedMusicArtistLiteDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the collection of lightweight music artist elements associated with this instance.
|
||||
/// </summary>
|
||||
public IReadOnlyList<MusicArtistLiteDto> Data { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the current page number in a paginated collection.
|
||||
/// </summary>
|
||||
public int CurrentPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of items to include per page in paginated results.
|
||||
/// </summary>
|
||||
public int PerPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of elements available in the paginated result set.
|
||||
/// </summary>
|
||||
public int Count { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of pages based on elements available in the result set and per page.
|
||||
/// </summary>
|
||||
public int NumberOfPages { get; set; }
|
||||
}
|
||||
-38
@@ -1,38 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.AudioLibrary.MusicLibrary;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a paginated collection of lightweight track elements, together with pagination metadata.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")]
|
||||
public class PaginatedMusicTrackLiteDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the collection of lightweight track elements associated with this instance.
|
||||
/// </summary>
|
||||
public IReadOnlyList<MusicTrackLiteDto> Data { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the current page number in a paginated collection.
|
||||
/// </summary>
|
||||
public int CurrentPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of items to include per page in paginated results.
|
||||
/// </summary>
|
||||
public int PerPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of elements available in the paginated result set.
|
||||
/// </summary>
|
||||
public int Count { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of pages based on elements available in the result set and per page.
|
||||
/// </summary>
|
||||
public int NumberOfPages { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Common;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a page of elements together with its pagination metadata.
|
||||
/// </summary>
|
||||
/// <typeparam name="T">The type of the elements of the page.</typeparam>
|
||||
/// <param name="Data">The elements of the requested page.</param>
|
||||
/// <param name="CurrentPage">The one based number of the returned page.</param>
|
||||
/// <param name="PerPage">The number of elements requested per page.</param>
|
||||
/// <param name="Count">The total number of elements that match the filter, even when only a page of them is returned.</param>
|
||||
/// <param name="NumberOfPages">The total number of pages that match the filter.</param>
|
||||
[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}; Count: {Count}")]
|
||||
public sealed record PaginatedDto<T>(
|
||||
List<T> Data,
|
||||
int CurrentPage,
|
||||
int PerPage,
|
||||
int Count,
|
||||
int NumberOfPages
|
||||
);
|
||||
@@ -0,0 +1,22 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a favorite of the current user.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the favorite.</param>
|
||||
/// <param name="MediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="MediaItemId">The Id of the favorited media item.</param>
|
||||
/// <param name="FavoritedOnUtc">The date and time when the media item was favorited.</param>
|
||||
[DebuggerDisplay("Id: {Id}; MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public sealed record FavoriteDto(
|
||||
Guid Id,
|
||||
FavoriteMediaKind MediaKind,
|
||||
Guid MediaItemId,
|
||||
DateTime FavoritedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,34 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a favorite of the current user together with the display details of the media item it references.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of the favorited media item.</param>
|
||||
/// <param name="MediaItemId">The Id of the favorited media item.</param>
|
||||
/// <param name="IsAvailable">Whether the media item still exists and can be accessed by the user. When <see langword="false"/>, every display field is empty.</param>
|
||||
/// <param name="LibraryId">The Id of the media library that contains the media item, or an empty Guid when the item is not available.</param>
|
||||
/// <param name="Title">The title of the media item, or an empty string when the item is not available.</param>
|
||||
/// <param name="CollectionId">The Id of the collection that contains the media item, or an empty Guid when there is none.</param>
|
||||
/// <param name="CollectionTitle">The title of the collection that contains the media item, or an empty string when there is none.</param>
|
||||
/// <param name="CreatorId">The Id of the creator of the media item, or an empty Guid when there is none.</param>
|
||||
/// <param name="CreatorName">The name of the creator of the media item, or an empty string when there is none.</param>
|
||||
/// <param name="CoverPath">The path of the cover art of the media item, if available.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public sealed record FavoriteItemDto(
|
||||
FavoriteMediaKind MediaKind,
|
||||
Guid MediaItemId,
|
||||
bool IsAvailable,
|
||||
Guid LibraryId,
|
||||
string Title,
|
||||
Guid CollectionId,
|
||||
string CollectionTitle,
|
||||
Guid CreatorId,
|
||||
string CreatorName,
|
||||
string? CoverPath
|
||||
);
|
||||
@@ -0,0 +1,16 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object that tells which of the checked media items are favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="FavoritedMediaItemIds">The Ids, among the checked ones, of the media items that are favorites of the current user.</param>
|
||||
[DebuggerDisplay("Favorited: {FavoritedMediaItemIds.Count}")]
|
||||
public sealed record FavoriteStatusDto(
|
||||
List<Guid> FavoritedMediaItemIds
|
||||
);
|
||||
@@ -1,38 +0,0 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Libraries;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a paginated collection of lightweight book elements, together with pagination metadata.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("CurrentPage: {CurrentPage}; Count: {Count}")]
|
||||
public class PaginatedBookLiteDto
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets the collection of lightweight book elements associated with this instance.
|
||||
/// </summary>
|
||||
public IReadOnlyList<BookLiteDto> Data { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the current page number in a paginated collection.
|
||||
/// </summary>
|
||||
public int CurrentPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the number of items to include per page in paginated results.
|
||||
/// </summary>
|
||||
public int PerPage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of elements available in the paginated result set.
|
||||
/// </summary>
|
||||
public int Count { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the total number of pages based on elements available in the result set and per page.
|
||||
/// </summary>
|
||||
public int NumberOfPages { get; set; }
|
||||
}
|
||||
@@ -1,21 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.DTO.Common;
|
||||
using Lumina.Presentation.Web.Common.Enums.Playlists;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.DTO.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Data transfer object for a playlist together with its ordered entries.
|
||||
/// Data transfer object for a playlist together with a page of its ordered entries.
|
||||
/// </summary>
|
||||
/// <param name="Id">The Id of the playlist.</param>
|
||||
/// <param name="Name">The name of the playlist.</param>
|
||||
/// <param name="Description">The description of the playlist, if applicable.</param>
|
||||
/// <param name="Type">The kind of media the playlist holds.</param>
|
||||
/// <param name="EntryCount">The number of entries the playlist holds, even when only a window of them is returned.</param>
|
||||
/// <param name="Entries">The ordered entries of the requested window of the playlist.</param>
|
||||
/// <param name="Entries">The page of ordered entries of the playlist, together with its pagination metadata.</param>
|
||||
/// <param name="CreatedOnUtc">The date and time when the playlist was created.</param>
|
||||
/// <param name="UpdatedOnUtc">The date and time when the playlist was last updated, if applicable.</param>
|
||||
[DebuggerDisplay("Id: {Id}; Name: {Name}; Entries: {Entries.Count}")]
|
||||
@@ -24,8 +23,7 @@ public sealed record PlaylistDto(
|
||||
string Name,
|
||||
string? Description,
|
||||
PlaylistType Type,
|
||||
int EntryCount,
|
||||
List<PlaylistEntryDto> Entries,
|
||||
PaginatedDto<PlaylistEntryDto> Entries,
|
||||
DateTime CreatedOnUtc,
|
||||
DateTime? UpdatedOnUtc
|
||||
);
|
||||
@@ -0,0 +1,42 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Enumeration for the kinds of media item that can be marked as a favorite.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{ToString()}")]
|
||||
public enum FavoriteMediaKind
|
||||
{
|
||||
/// <summary>
|
||||
/// A favorite that references an artist of a music library.
|
||||
/// </summary>
|
||||
MusicArtist,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references an album of a music library.
|
||||
/// </summary>
|
||||
MusicAlbum,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references a track of a music library.
|
||||
/// </summary>
|
||||
MusicTrack,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references a book of a book library.
|
||||
/// </summary>
|
||||
Book,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references a video file. Planned: video libraries are not catalogued yet, so this kind cannot be favorited.
|
||||
/// </summary>
|
||||
Video,
|
||||
|
||||
/// <summary>
|
||||
/// A favorite that references a photo. Planned: photo libraries are not catalogued yet, so this kind cannot be favorited.
|
||||
/// </summary>
|
||||
Photo,
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Requests.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for marking a media item as a favorite of the current user.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of the media item to favorite. Required.</param>
|
||||
/// <param name="MediaItemId">The Id of the media item to favorite. Required.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}; MediaItemId: {MediaItemId}")]
|
||||
public record AddFavoriteRequest(
|
||||
FavoriteMediaKind? MediaKind,
|
||||
Guid? MediaItemId
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Requests.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for finding out which media items of one kind are favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of the media items to check. Required.</param>
|
||||
/// <param name="MediaItemIds">The Ids of the media items to check, from 1 to 100. Required.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}")]
|
||||
public record GetFavoriteStatusRequest(
|
||||
FavoriteMediaKind? MediaKind,
|
||||
List<Guid>? MediaItemIds
|
||||
);
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Presentation.Web.Common.Enums.Favorites;
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Presentation.Web.Common.Requests.Favorites;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for getting a page of the favorites of the current user.
|
||||
/// </summary>
|
||||
/// <param name="MediaKind">The kind of media item to restrict the favorites to. Optional; every kind is returned when omitted.</param>
|
||||
/// <param name="CurrentPage">The one based page of favorites to return. Optional; defaults to 1.</param>
|
||||
/// <param name="PerPage">The number of favorites per page. Optional; defaults to 200.</param>
|
||||
[DebuggerDisplay("MediaKind: {MediaKind}; CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
|
||||
public record GetFavoritesRequest(
|
||||
FavoriteMediaKind? MediaKind,
|
||||
int? CurrentPage,
|
||||
int? PerPage
|
||||
);
|
||||
@@ -5,12 +5,12 @@ using System.Diagnostics;
|
||||
namespace Lumina.Presentation.Web.Common.Requests.Playlists;
|
||||
|
||||
/// <summary>
|
||||
/// Represents a request for getting a window of the entries of a playlist of the current user.
|
||||
/// Represents a request for getting a page of the entries of a playlist of the current user.
|
||||
/// </summary>
|
||||
/// <param name="Offset">The zero based position of the first entry to return. Optional; defaults to 0.</param>
|
||||
/// <param name="Limit">The maximum number of entries to return, from 1 to 1000. Optional; defaults to 200.</param>
|
||||
[DebuggerDisplay("Offset: {Offset}; Limit: {Limit}")]
|
||||
/// <param name="CurrentPage">The one based page of entries to return. Optional; defaults to 1.</param>
|
||||
/// <param name="PerPage">The number of entries per page. Optional; defaults to 200.</param>
|
||||
[DebuggerDisplay("CurrentPage: {CurrentPage}; PerPage: {PerPage}")]
|
||||
public record GetPlaylistRequest(
|
||||
int? Offset,
|
||||
int? Limit
|
||||
int? CurrentPage,
|
||||
int? PerPage
|
||||
);
|
||||
@@ -0,0 +1,18 @@
|
||||
namespace Lumina.Presentation.Web.Common.Routes;
|
||||
|
||||
/// <summary>
|
||||
/// Class for the collection of remote API routes called by this Web application.
|
||||
/// </summary>
|
||||
public static partial class ApiRoutes
|
||||
{
|
||||
/// <summary>
|
||||
/// Routes for the favorites endpoints of the remote API.
|
||||
/// </summary>
|
||||
public static class Favorites
|
||||
{
|
||||
public const string GET_FAVORITES = "users/me/favorites";
|
||||
public const string ADD_FAVORITE = "users/me/favorites";
|
||||
public const string REMOVE_FAVORITE = "users/me/favorites/{mediaKind}/{mediaItemId}";
|
||||
public const string GET_FAVORITE_STATUS = "users/me/favorites/status";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace Lumina.Presentation.Web.Common.Routes;
|
||||
|
||||
/// <summary>
|
||||
/// Class for the collection of routes defined in the Web application.
|
||||
/// </summary>
|
||||
public static partial class WebRoutes
|
||||
{
|
||||
/// <summary>
|
||||
/// Routes for the favorites pages.
|
||||
/// </summary>
|
||||
public static class Favorites
|
||||
{
|
||||
public const string INDEX = "{culture}/favorites";
|
||||
public const string GET_FAVORITES = "{culture}/favorites/api-get-favorites";
|
||||
public const string GET_FAVORITE_STATUS = "{culture}/favorites/api-get-favorite-status";
|
||||
public const string ADD_FAVORITE = "{culture}/favorites/api-add-favorite";
|
||||
public const string REMOVE_FAVORITE = "{culture}/favorites/{mediaKind}/{mediaItemId}/api-remove-favorite";
|
||||
}
|
||||
}
|
||||
+55
@@ -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);
|
||||
}
|
||||
}
|
||||
+42
@@ -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)))
|
||||
);
|
||||
}
|
||||
}
|
||||
+72
@@ -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);
|
||||
}
|
||||
}
|
||||
+43
@@ -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")]))
|
||||
);
|
||||
}
|
||||
}
|
||||
+69
@@ -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);
|
||||
}
|
||||
}
|
||||
+58
@@ -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))
|
||||
);
|
||||
}
|
||||
}
|
||||
+108
@@ -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 });
|
||||
}
|
||||
}
|
||||
+24
@@ -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.");
|
||||
}
|
||||
}
|
||||
+71
@@ -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();
|
||||
}
|
||||
}
|
||||
+30
@@ -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
-1
@@ -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
-1
@@ -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
-1
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
+2
-1
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -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));
|
||||
}
|
||||
}
|
||||
+6
-8
@@ -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);
|
||||
}
|
||||
|
||||
+35
-6
@@ -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)))
|
||||
);
|
||||
}
|
||||
}
|
||||
+10
-2
@@ -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,
|
||||
|
||||
+4
-4
@@ -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'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'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'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>
|
||||
}
|
||||
+18
-1
@@ -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
|
||||
|
||||
+9
@@ -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);
|
||||
|
||||
|
||||
+9
@@ -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);
|
||||
|
||||
|
||||
+9
@@ -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>
|
||||
|
||||
@@ -1203,11 +1203,13 @@ body {
|
||||
}
|
||||
|
||||
.tracks-table .track-play-column,
|
||||
.tracks-table .track-favorite-column,
|
||||
.tracks-table .track-actions-column {
|
||||
width: 40px;
|
||||
}
|
||||
|
||||
.tracks-table .track-play-cell,
|
||||
.tracks-table .track-favorite-cell,
|
||||
.tracks-table .track-actions-cell {
|
||||
width: 40px;
|
||||
padding-left: 0;
|
||||
@@ -1264,6 +1266,68 @@ body {
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
/* The favorite heart of a media card: the box of the actions trigger, placed immediately on its left. The global favorites script writes the state attributes. */
|
||||
.card-favorite-toggle {
|
||||
position: absolute;
|
||||
right: 28px;
|
||||
bottom: 28px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
display: none;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
color: #6DCBFE;
|
||||
border: 1px solid #777777;
|
||||
border-bottom-color: #000000;
|
||||
border-right-color: #000000;
|
||||
background: linear-gradient(to bottom, #505050 0%, #464646 35%, #404040 55%, #363636 100%);
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.card-favorite-toggle::after {
|
||||
content: '\2665';
|
||||
}
|
||||
|
||||
.media-card:hover .card-favorite-toggle,
|
||||
.media-card.open .card-favorite-toggle,
|
||||
.media-card:focus-within .card-favorite-toggle {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.card-favorite-toggle:hover {
|
||||
color: #FFFFFF;
|
||||
}
|
||||
|
||||
.card-favorite-toggle[aria-pressed="true"],
|
||||
.card-favorite-toggle.is-favorite {
|
||||
color: #FF5D5D;
|
||||
}
|
||||
|
||||
.card-favorite-toggle[data-favorite-state="loading"] {
|
||||
opacity: 0.5;
|
||||
cursor: progress;
|
||||
}
|
||||
|
||||
.card-favorite-toggle[data-favorite-state="failed"] {
|
||||
border-color: #FF5D5D;
|
||||
}
|
||||
|
||||
/* A card without an actions trigger, like the cards of the favorites page, gives its place to the heart. The heart is the
|
||||
only action of such a card, so it is always visible: a touch screen has no hover to reveal it, and a display: none control cannot be reached with the keyboard. */
|
||||
.media-card:not(:has(.card-actions-trigger)) > .card-favorite-toggle {
|
||||
right: 2px;
|
||||
display: flex;
|
||||
}
|
||||
|
||||
/* The track row places the same heart inline and always visible, instead of on a media card. */
|
||||
.track-favorite-cell .card-favorite-toggle {
|
||||
position: static;
|
||||
display: flex;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.card-actions-menu {
|
||||
display: none;
|
||||
position: fixed;
|
||||
|
||||
@@ -0,0 +1,553 @@
|
||||
/**
|
||||
* Favorite toggles: the hearts of the media cards (books, artists and albums, and the cards of the favorites page) and of the
|
||||
* track rows of the album page. The detail pages of an item have no toggle.
|
||||
*
|
||||
* A toggle is any focusable element, normally a button, that carries the `data-favorite-toggle` marker together with the
|
||||
* `data-favorite-media-kind` (`MusicArtist`, `MusicAlbum`, `MusicTrack` or `Book`) and `data-favorite-media-item-id`
|
||||
* attributes. The module owns the whole behavior of such an element, so a page or a theme template only renders the markup:
|
||||
* it finds the toggles, asks the server which of their items the current user favorited, writes the state on them, and
|
||||
* adds or removes the favorite when one is clicked. The state is exposed as `aria-pressed`, `data-favorite-state`
|
||||
* (`favorited`, `not-favorited`, `loading` or `failed`) and the `is-favorite` class, so a theme owns the look. The module
|
||||
* writes the localized text of the next action ("Add to favorites" or "Remove from favorites") as the `aria-label` and as
|
||||
* the `title`, which is the hover text of a heart that has no visible text, and also as the text of the optional
|
||||
* `.favorite-toggle-label` element. The module never renders markup: it only sets those attributes, the class and the text.
|
||||
*
|
||||
* Everything is attached once, to the document. The click listener uses event delegation and a MutationObserver hydrates
|
||||
* the toggles that are added later, by a page script or by the in-place navigation that swaps the page content, so no page
|
||||
* has to bind or unbind anything and loading this script a second time changes nothing. The state lives only on the
|
||||
* elements and in the requests in flight: nothing is cached or stored in the browser, so the favorites of one user can
|
||||
* never be shown to another user who signs in without a page reload.
|
||||
*
|
||||
* After every successful change the module dispatches the `lumina:favorite-changed` DOM event on the document, with
|
||||
* `detail = { mediaKind, mediaItemId, isFavorite }`, so a page that lists favorites can react while it stays decoupled
|
||||
* from the toggle that caused the change.
|
||||
*/
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
// The layout may render this script on a page that already ran it, and the in-place navigation can evaluate scripts
|
||||
// again. A second set of listeners would send every request twice, so the first load owns the document.
|
||||
if (window.LuminaFavorites)
|
||||
return;
|
||||
|
||||
// The layout renders the route templates with empty Guids because the kind and the item are not known until a toggle
|
||||
// is clicked. Replacing this sentinel keeps the route construction in one place and avoids hand-built paths.
|
||||
const EMPTY_GUID = '00000000-0000-0000-0000-000000000000';
|
||||
// The favorite kinds the server supports today. Anything else is rejected here, so a typo in a template shows up as a
|
||||
// failed toggle instead of as a request that the server would reject.
|
||||
const MEDIA_KINDS = ['MusicArtist', 'MusicAlbum', 'MusicTrack', 'Book'];
|
||||
// The server accepts up to 100 ids per status request, because the ids travel in the query string: 200 Guids are about
|
||||
// 10 KB, which is more than the 8 KB request line the web server accepts by default, while 100 ids stay under 6 KB.
|
||||
const MAX_STATUS_IDS_PER_REQUEST = 100;
|
||||
const TOGGLE_SELECTOR = '[data-favorite-toggle]';
|
||||
const FAVORITE_CHANGED_EVENT = 'lumina:favorite-changed';
|
||||
const GUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
||||
|
||||
// The status checks asked for in the current tick, grouped by kind and then by item Id. They are sent together on the
|
||||
// next macrotask, so the toggles a page renders in a loop cost one request per kind instead of one per toggle.
|
||||
let pendingStatus = new Map();
|
||||
let statusFlushHandle = null;
|
||||
// The add or remove request of every item that is being changed. It makes a second click on the same item a no-op
|
||||
// while the first request is in flight, whichever toggle of the item it comes from.
|
||||
const mutationsInFlight = new Map();
|
||||
// A counter per item that moves every time the item changes. A status answer that was asked for before a change
|
||||
// describes an old state, so it is dropped when the counter moved while the request was in flight.
|
||||
const revisions = new Map();
|
||||
|
||||
/**
|
||||
* Gets the favorites configuration the layout renders for every page.
|
||||
*
|
||||
* The configuration is the only contract between the layout and this module: it carries the routes and the localized
|
||||
* labels. Reading it lazily, instead of capturing it when the script loads, lets the layout render the configuration
|
||||
* after this deferred script has been parsed.
|
||||
* @returns {Object|null} The configuration, or null when the layout did not render it.
|
||||
*/
|
||||
function getConfiguration() {
|
||||
return window.favoritesConfiguration || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the localized strings of the favorites, with empty values when the layout did not render them.
|
||||
* @returns {Object} The localized strings.
|
||||
*/
|
||||
function getStrings() {
|
||||
const configuration = getConfiguration();
|
||||
return configuration && configuration.strings ? configuration.strings : {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a media kind to its canonical name.
|
||||
*
|
||||
* The comparison ignores the case, so a template that renders `musicalbum` still works, and the canonical name is what the routes and the request bodies carry.
|
||||
* @param {*} mediaKind - The kind to normalize.
|
||||
* @returns {string} The canonical kind name, or an empty string when the kind is not supported.
|
||||
*/
|
||||
function normalizeMediaKind(mediaKind) {
|
||||
if (typeof mediaKind !== 'string')
|
||||
return '';
|
||||
const lowered = mediaKind.trim().toLowerCase();
|
||||
return MEDIA_KINDS.find(kind => kind.toLowerCase() === lowered) || '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes the Id of a media item to its lowercase Guid text.
|
||||
*
|
||||
* Ids are compared as text across the DOM and the server answers, and the casing of a Guid is not significant, so the
|
||||
* lowercase form is the one key. An empty Guid is rejected because it never identifies an item.
|
||||
* @param {*} mediaItemId - The Id to normalize.
|
||||
* @returns {string} The lowercase Guid, or an empty string when the value is not a valid, non empty Guid.
|
||||
*/
|
||||
function normalizeMediaItemId(mediaItemId) {
|
||||
if (typeof mediaItemId !== 'string')
|
||||
return '';
|
||||
const lowered = mediaItemId.trim().toLowerCase();
|
||||
return GUID_PATTERN.test(lowered) && lowered !== EMPTY_GUID ? lowered : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Describes a media item by its normalized kind and Id.
|
||||
* @param {*} mediaKind - The kind of the item.
|
||||
* @param {*} mediaItemId - The Id of the item.
|
||||
* @returns {Object|null} The item, with its kind, its Id and the key that identifies it, or null when either is invalid.
|
||||
*/
|
||||
function describeItem(mediaKind, mediaItemId) {
|
||||
const kind = normalizeMediaKind(mediaKind);
|
||||
const id = normalizeMediaItemId(mediaItemId);
|
||||
if (!kind || !id)
|
||||
return null;
|
||||
return { kind, id, key: `${kind}:${id}` };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the item a toggle element refers to from its data attributes.
|
||||
* @param {Element} toggle - The toggle element.
|
||||
* @returns {Object|null} The item, or null when the attributes are missing or invalid.
|
||||
*/
|
||||
function readToggleItem(toggle) {
|
||||
return describeItem(toggle.getAttribute('data-favorite-media-kind'), toggle.getAttribute('data-favorite-media-item-id'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects the toggles inside an element, including the element itself.
|
||||
* @param {Element|Document|DocumentFragment} root - The element to search.
|
||||
* @returns {Array<Element>} The toggles that were found.
|
||||
*/
|
||||
function collectToggles(root) {
|
||||
const toggles = [];
|
||||
if (root.nodeType === Node.ELEMENT_NODE && root.matches(TOGGLE_SELECTOR))
|
||||
toggles.push(root);
|
||||
if (typeof root.querySelectorAll === 'function')
|
||||
root.querySelectorAll(TOGGLE_SELECTOR).forEach(toggle => toggles.push(toggle));
|
||||
return toggles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds every toggle of the document that refers to an item.
|
||||
*
|
||||
* A page can render the same item more than once, for example the artist in a header and in a list, and every one of
|
||||
* them must show the same state. The toggles are looked up when a state is written, not remembered, so a toggle that
|
||||
* was added while a request was in flight is also updated and a removed one is not touched.
|
||||
* @param {string} key - The key of the item.
|
||||
* @returns {Array<Element>} The toggles of the item.
|
||||
*/
|
||||
function findToggles(key) {
|
||||
return collectToggles(document).filter(toggle => {
|
||||
const item = readToggleItem(toggle);
|
||||
return item !== null && item.key === key;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the revision counter of an item.
|
||||
* @param {string} key - The key of the item.
|
||||
* @returns {number} The current revision.
|
||||
*/
|
||||
function getRevision(key) {
|
||||
return revisions.get(key) || 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the revision counter of an item, which invalidates the status answers that are still in flight for it.
|
||||
* @param {string} key - The key of the item.
|
||||
*/
|
||||
function bumpRevision(key) {
|
||||
revisions.set(key, getRevision(key) + 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a state on a toggle: the pressed state, the state attribute, the class, and the localized label and hover text.
|
||||
*
|
||||
* The loading and failed states keep the pressed state the toggle already had, so the toggle does not flicker to
|
||||
* "not favorite" while a request is in flight, and the label always names the action the next click performs.
|
||||
* @param {Element} toggle - The toggle element.
|
||||
* @param {string} state - The state to write: favorited, not-favorited, loading or failed.
|
||||
* @param {boolean} isFavorite - Whether the toggle must show the item as a favorite.
|
||||
*/
|
||||
function renderToggle(toggle, state, isFavorite) {
|
||||
toggle.setAttribute('data-favorite-state', state);
|
||||
toggle.setAttribute('aria-pressed', isFavorite ? 'true' : 'false');
|
||||
toggle.classList.toggle('is-favorite', isFavorite);
|
||||
if (state === 'loading')
|
||||
toggle.setAttribute('aria-busy', 'true');
|
||||
else
|
||||
toggle.removeAttribute('aria-busy');
|
||||
const label = isFavorite ? getStrings().remove : getStrings().add;
|
||||
if (!label)
|
||||
return;
|
||||
toggle.setAttribute('aria-label', label);
|
||||
toggle.setAttribute('title', label);
|
||||
const labelElement = toggle.querySelector('.favorite-toggle-label');
|
||||
// The text is written only when it changes, so the observer of the document does not see a change per state write.
|
||||
if (labelElement && labelElement.textContent !== label)
|
||||
labelElement.textContent = label;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets whether a toggle currently shows its item as a favorite.
|
||||
* @param {Element} toggle - The toggle element.
|
||||
* @returns {boolean} True when the toggle is pressed.
|
||||
*/
|
||||
function isPressed(toggle) {
|
||||
return toggle.getAttribute('aria-pressed') === 'true';
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the settled state of an item on every toggle that shows it.
|
||||
* @param {string} key - The key of the item.
|
||||
* @param {boolean} isFavorite - Whether the item is a favorite of the current user.
|
||||
*/
|
||||
function applyFavoriteState(key, isFavorite) {
|
||||
findToggles(key).forEach(toggle => renderToggle(toggle, isFavorite ? 'favorited' : 'not-favorited', isFavorite));
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the status request route of a batch of items of one kind.
|
||||
* @param {string} kind - The kind of the items.
|
||||
* @param {Array<string>} ids - The Ids of the items to check.
|
||||
* @returns {string} The route with its query string, or an empty string when the layout did not render the route.
|
||||
*/
|
||||
function buildStatusUrl(kind, ids) {
|
||||
const configuration = getConfiguration();
|
||||
const url = configuration ? configuration.getFavoriteStatusUrl : '';
|
||||
if (typeof url !== 'string' || url.length === 0)
|
||||
return '';
|
||||
const parameters = new URLSearchParams();
|
||||
parameters.set('mediaKind', kind);
|
||||
ids.forEach(id => parameters.append('mediaItemIds', id));
|
||||
return `${url}${url.includes('?') ? '&' : '?'}${parameters.toString()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the route that removes a favorite by replacing its named mediaKind and mediaItemId route placeholders.
|
||||
*
|
||||
* The layout renders the route template with the placeholders of the route intact, so each value is filled in by name and a change
|
||||
* in the segment order cannot silently swap them. Both values are encoded so they stay single path segments even if the DOM value is malformed.
|
||||
* @param {Object} item - The item to remove from the favorites.
|
||||
* @returns {string} The route, or an empty string when the layout did not render the template.
|
||||
*/
|
||||
function buildRemoveUrl(item) {
|
||||
const configuration = getConfiguration();
|
||||
const template = configuration ? configuration.removeFavoriteUrlTemplate : '';
|
||||
if (typeof template !== 'string' || template.length === 0)
|
||||
return '';
|
||||
return template
|
||||
.replace('{mediaKind}', encodeURIComponent(item.kind))
|
||||
.replace('{mediaItemId}', encodeURIComponent(item.id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the server which items of one kind are favorites of the current user, in one request.
|
||||
* @param {string} kind - The kind of the items.
|
||||
* @param {Array<string>} ids - The Ids of the items to check.
|
||||
* @returns {Promise<Set<string>>} The lowercase Ids, among the checked ones, that are favorites.
|
||||
* @throws {Error} When the route is not available or the request failed.
|
||||
*/
|
||||
async function requestStatusAsync(kind, ids) {
|
||||
const url = buildStatusUrl(kind, ids);
|
||||
if (!url)
|
||||
throw new Error('Favorites: the status route was not rendered by the layout.');
|
||||
if (typeof callApiGetAsync !== 'function')
|
||||
throw new Error('Favorites: the global API helper is not available.');
|
||||
const data = await callApiGetAsync(url);
|
||||
// The API helper resolves to undefined after it reported a failed request, and a malformed answer would let a toggle show a wrong state, so both are failures.
|
||||
if (!data || !Array.isArray(data.favoritedMediaItemIds))
|
||||
throw new Error('Favorites: the status request failed.');
|
||||
return new Set(data.favoritedMediaItemIds.map(normalizeMediaItemId).filter(id => id !== ''));
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the waiters of one chunk of a status batch from a single request.
|
||||
* @param {string} kind - The kind of the items of the chunk.
|
||||
* @param {Array<string>} ids - The Ids of the chunk.
|
||||
* @param {Map<string, Array<Object>>} waiters - The waiters of the whole batch, by item Id.
|
||||
* @returns {Promise<void>} A promise that completes when every waiter of the chunk was settled.
|
||||
*/
|
||||
async function resolveStatusChunkAsync(kind, ids, waiters) {
|
||||
try {
|
||||
const favorited = await requestStatusAsync(kind, ids);
|
||||
ids.forEach(id => waiters.get(id).forEach(waiter => waiter.resolve(favorited.has(id))));
|
||||
} catch (error) {
|
||||
console.error('Favorites: reading the favorite state failed.', error);
|
||||
ids.forEach(id => waiters.get(id).forEach(waiter => waiter.reject(error)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the status checks queued in the current tick, one request per kind and per chunk of ids.
|
||||
*
|
||||
* The ids of a kind are deduplicated by the queue, and split into chunks so the query string stays below the request line limit of the server.
|
||||
*/
|
||||
function flushStatusQueue() {
|
||||
statusFlushHandle = null;
|
||||
const batches = pendingStatus;
|
||||
pendingStatus = new Map();
|
||||
batches.forEach((waiters, kind) => {
|
||||
const ids = Array.from(waiters.keys());
|
||||
for (let start = 0; start < ids.length; start += MAX_STATUS_IDS_PER_REQUEST)
|
||||
resolveStatusChunkAsync(kind, ids.slice(start, start + MAX_STATUS_IDS_PER_REQUEST), waiters);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Queues the status check of an item, so it is sent in one request together with the items asked for in the same tick.
|
||||
* @param {Object} item - The item to check.
|
||||
* @returns {Promise<boolean>} A promise that resolves to whether the item is a favorite, and rejects when the check failed.
|
||||
*/
|
||||
function queueStatusCheck(item) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!pendingStatus.has(item.kind))
|
||||
pendingStatus.set(item.kind, new Map());
|
||||
const waiters = pendingStatus.get(item.kind);
|
||||
if (!waiters.has(item.id))
|
||||
waiters.set(item.id, []);
|
||||
waiters.get(item.id).push({ resolve, reject });
|
||||
if (statusFlushHandle === null)
|
||||
statusFlushHandle = setTimeout(flushStatusQueue, 0);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the favorite state of the toggles from the server and writes it on them.
|
||||
*
|
||||
* A toggle with a settled state keeps showing it while the state is checked again, which is what happens when the
|
||||
* in-place navigation renders a page again, so nothing flickers. A toggle without a settled state shows the loading state. An item that is being
|
||||
* changed is skipped, because its change writes the state when it completes, and an answer that was overtaken by a change is dropped.
|
||||
* A failed check marks the toggles that have no settled state as failed, and a click on such a toggle checks it again.
|
||||
* @param {Array<Element>} toggles - The toggles to hydrate.
|
||||
* @returns {Promise<void>} A promise that completes when every check has finished. It never rejects.
|
||||
*/
|
||||
async function hydrateToggles(toggles) {
|
||||
const checks = new Map();
|
||||
for (const toggle of toggles) {
|
||||
const item = readToggleItem(toggle);
|
||||
if (!item) {
|
||||
console.warn('Favorites: a toggle has an invalid media kind or media item Id.', toggle);
|
||||
renderToggle(toggle, 'failed', false);
|
||||
continue;
|
||||
}
|
||||
if (mutationsInFlight.has(item.key))
|
||||
continue;
|
||||
const state = toggle.getAttribute('data-favorite-state');
|
||||
if (state !== 'favorited' && state !== 'not-favorited')
|
||||
renderToggle(toggle, 'loading', isPressed(toggle));
|
||||
if (!checks.has(item.key))
|
||||
checks.set(item.key, { item, revision: getRevision(item.key) });
|
||||
}
|
||||
await Promise.all(Array.from(checks.values(), check => queueStatusCheck(check.item).then(
|
||||
isFavorite => {
|
||||
if (getRevision(check.item.key) === check.revision && !mutationsInFlight.has(check.item.key))
|
||||
applyFavoriteState(check.item.key, isFavorite);
|
||||
},
|
||||
() => {
|
||||
findToggles(check.item.key)
|
||||
.filter(toggle => toggle.getAttribute('data-favorite-state') === 'loading')
|
||||
.forEach(toggle => renderToggle(toggle, 'failed', isPressed(toggle)));
|
||||
})));
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds or removes the favorite on the server, and writes the result on every toggle of the item.
|
||||
*
|
||||
* Every toggle of the item shows the loading state meanwhile. On success they show the new state and the change event
|
||||
* is dispatched. On failure they get back the state they had, because a failed request changed nothing, and the failure is reported by the global API helper.
|
||||
* @param {Object} item - The item to change.
|
||||
* @param {boolean} shouldFavorite - True to add the favorite, false to remove it.
|
||||
* @returns {Promise<boolean>} A promise that resolves to whether the change was made.
|
||||
*/
|
||||
async function changeFavoriteAsync(item, shouldFavorite) {
|
||||
const previousStates = new Map();
|
||||
findToggles(item.key).forEach(toggle => {
|
||||
previousStates.set(toggle, { state: toggle.getAttribute('data-favorite-state'), isFavorite: isPressed(toggle) });
|
||||
renderToggle(toggle, 'loading', isPressed(toggle));
|
||||
});
|
||||
bumpRevision(item.key);
|
||||
|
||||
let isChanged = false;
|
||||
try {
|
||||
const configuration = getConfiguration();
|
||||
if (shouldFavorite) {
|
||||
const addUrl = configuration ? configuration.addFavoriteUrl : '';
|
||||
if (addUrl) {
|
||||
const result = await callApiPostAsync(addUrl, { mediaKind: item.kind, mediaItemId: item.id });
|
||||
isChanged = Boolean(result);
|
||||
}
|
||||
} else {
|
||||
const removeUrl = buildRemoveUrl(item);
|
||||
if (removeUrl)
|
||||
isChanged = Boolean(await callApiDeleteAsync(removeUrl));
|
||||
}
|
||||
} catch (error) {
|
||||
// The API helpers normally resolve to a falsy value on failure; this catch is for unexpected errors, such as a
|
||||
// rejected promise from a test double. The toggles must leave the loading state either way.
|
||||
console.error('Favorites: changing the favorite failed.', error);
|
||||
}
|
||||
|
||||
bumpRevision(item.key);
|
||||
if (isChanged) {
|
||||
applyFavoriteState(item.key, shouldFavorite);
|
||||
document.dispatchEvent(new CustomEvent(FAVORITE_CHANGED_EVENT, {
|
||||
detail: { mediaKind: item.kind, mediaItemId: item.id, isFavorite: shouldFavorite }
|
||||
}));
|
||||
return true;
|
||||
}
|
||||
|
||||
// A toggle added while the request was in flight has no remembered state, so it gets the state that was true before the change.
|
||||
findToggles(item.key).forEach(toggle => {
|
||||
const previous = previousStates.get(toggle) || { state: shouldFavorite ? 'not-favorited' : 'favorited', isFavorite: !shouldFavorite };
|
||||
const state = previous.state === 'favorited' || previous.state === 'not-favorited' ? previous.state : 'failed';
|
||||
renderToggle(toggle, state, previous.isFavorite);
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a media item to the favorites of the current user, or removes it.
|
||||
*
|
||||
* A second call for an item that is already being changed is ignored: it resolves to the result of the running change
|
||||
* when it asks for the same state, and to false when it asks for the opposite one, so a double click can never send two requests.
|
||||
* @param {string} mediaKind - The kind of the item: MusicArtist, MusicAlbum, MusicTrack or Book.
|
||||
* @param {string} mediaItemId - The Id of the item.
|
||||
* @param {boolean} shouldFavorite - True to add the favorite, false to remove it.
|
||||
* @returns {Promise<boolean>} A promise that resolves to true when the favorite state of the item is now the requested
|
||||
* one, and to false when the change was not made. A failure is reported to the user, so the caller only needs to react to the result.
|
||||
*/
|
||||
function setFavoriteAsync(mediaKind, mediaItemId, shouldFavorite) {
|
||||
const item = describeItem(mediaKind, mediaItemId);
|
||||
if (!item) {
|
||||
console.error('Favorites: the media kind or the media item Id is invalid.', mediaKind, mediaItemId);
|
||||
return Promise.resolve(false);
|
||||
}
|
||||
const wanted = Boolean(shouldFavorite);
|
||||
const running = mutationsInFlight.get(item.key);
|
||||
if (running)
|
||||
return running.shouldFavorite === wanted ? running.promise : Promise.resolve(false);
|
||||
const promise = changeFavoriteAsync(item, wanted).finally(() => mutationsInFlight.delete(item.key));
|
||||
mutationsInFlight.set(item.key, { shouldFavorite: wanted, promise });
|
||||
return promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets whether a media item is a favorite of the current user.
|
||||
*
|
||||
* The answer always comes from the server, never from a cache, and the check is batched with the other checks asked for in the same tick.
|
||||
* @param {string} mediaKind - The kind of the item: MusicArtist, MusicAlbum, MusicTrack or Book.
|
||||
* @param {string} mediaItemId - The Id of the item.
|
||||
* @returns {Promise<boolean>} A promise that resolves to whether the item is a favorite. It rejects when the kind or the
|
||||
* Id is invalid or the request failed; the failure of a request is also reported to the user.
|
||||
*/
|
||||
function isFavorite(mediaKind, mediaItemId) {
|
||||
const item = describeItem(mediaKind, mediaItemId);
|
||||
if (!item)
|
||||
return Promise.reject(new Error('Favorites: the media kind or the media item Id is invalid.'));
|
||||
return queueStatusCheck(item);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hydrates the favorite toggles inside an element: reads which of their items are favorites and writes the state.
|
||||
*
|
||||
* The module already hydrates the toggles of the page and the ones that are added to it, so a page only needs this
|
||||
* for toggles that live in an element that is not attached to the document yet.
|
||||
* @param {Element|Document} [rootElement] - The element to search for toggles. Defaults to the whole document.
|
||||
* @returns {Promise<void>} A promise that completes when the state of the toggles was written. It never rejects.
|
||||
*/
|
||||
function hydrate(rootElement) {
|
||||
const root = rootElement || document;
|
||||
if (!root || typeof root.querySelectorAll !== 'function')
|
||||
return Promise.resolve();
|
||||
return hydrateToggles(collectToggles(root));
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a click on the document and toggles the favorite when the click happened on a favorite toggle.
|
||||
*
|
||||
* The click is handled by delegation, so a toggle works wherever it is rendered, even inside a link or a card, and a
|
||||
* toggle that is added later needs no listener. The default action is prevented, so a toggle inside a link does not also navigate.
|
||||
* @param {MouseEvent} event - The click event.
|
||||
*/
|
||||
function handleClick(event) {
|
||||
const target = event.target;
|
||||
if (!target || typeof target.closest !== 'function')
|
||||
return;
|
||||
const toggle = target.closest(TOGGLE_SELECTOR);
|
||||
if (!toggle)
|
||||
return;
|
||||
event.preventDefault();
|
||||
const item = readToggleItem(toggle);
|
||||
if (!item)
|
||||
return;
|
||||
const state = toggle.getAttribute('data-favorite-state');
|
||||
if (state === 'loading' || mutationsInFlight.has(item.key))
|
||||
return;
|
||||
// The real state of the item is not known, because the toggle was not hydrated yet or its hydration failed, so a
|
||||
// click would guess the direction. The click reads the state again instead, and the next click acts on it.
|
||||
if (state !== 'favorited' && state !== 'not-favorited') {
|
||||
hydrateToggles([toggle]);
|
||||
return;
|
||||
}
|
||||
setFavoriteAsync(item.kind, item.id, !isPressed(toggle));
|
||||
}
|
||||
|
||||
/**
|
||||
* Hydrates the toggles that were added to the document, and the toggles whose item attributes changed.
|
||||
*
|
||||
* This is how the toggles that a page script renders, or that the in-place navigation swaps in, get their state
|
||||
* without any call from the page. The writes of this module only touch attributes that are not observed and text nodes, so the observer cannot trigger itself.
|
||||
* @param {Array<MutationRecord>} mutations - The mutations of the document.
|
||||
*/
|
||||
function handleMutations(mutations) {
|
||||
const toggles = new Set();
|
||||
for (const mutation of mutations) {
|
||||
if (mutation.type === 'attributes') {
|
||||
if (mutation.target.nodeType === Node.ELEMENT_NODE && mutation.target.matches(TOGGLE_SELECTOR)) {
|
||||
// The element now refers to another item, so the state it shows belongs to the old one.
|
||||
mutation.target.removeAttribute('data-favorite-state');
|
||||
toggles.add(mutation.target);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
mutation.addedNodes.forEach(node => {
|
||||
if (node.nodeType === Node.ELEMENT_NODE)
|
||||
collectToggles(node).forEach(toggle => toggles.add(toggle));
|
||||
});
|
||||
}
|
||||
if (toggles.size > 0)
|
||||
hydrateToggles(Array.from(toggles));
|
||||
}
|
||||
|
||||
document.addEventListener('click', handleClick);
|
||||
new MutationObserver(handleMutations).observe(document.documentElement, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
attributeFilter: ['data-favorite-toggle', 'data-favorite-media-kind', 'data-favorite-media-item-id']
|
||||
});
|
||||
|
||||
window.LuminaFavorites = {
|
||||
hydrate,
|
||||
isFavorite,
|
||||
setFavoriteAsync
|
||||
};
|
||||
|
||||
// The script is deferred, so the toggles that the server rendered are already in the document.
|
||||
hydrate(document);
|
||||
})();
|
||||
Reference in new issue
Block a user