Adds artwork provider management to the library edit page

Adds the artwork providers list to the library edit page, mirroring the
metadata providers list, so that the artwork providers of a library can be
enabled, disabled and reordered. Adds the web routes, request types, DTO and
endpoints that proxy the artwork provider operations to the API.
This commit is contained in:
BinaryAlley committed 2026-08-26 21:49:49 +03:00
1 parent 4b861d8323
commit 4ee2976806
30 files changed
+905 -1

No files matched your search

@@ -0,0 +1,33 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.DTO.Plugins;
/// <summary>
/// Data transfer object for an artwork provider configured for a media library.
/// </summary>
[DebuggerDisplay("Name: {Name}")]
public class LibraryArtworkProviderDto
{
/// <summary>
/// Gets or sets the unique identifier of the plugin providing the artwork.
/// </summary>
public Guid PluginId { get; set; }
/// <summary>
/// Gets or sets the display name of the artwork provider.
/// </summary>
public string Name { get; set; } = string.Empty;
/// <summary>
/// Gets or sets whether the artwork provider is enabled for the media library.
/// </summary>
public bool IsEnabled { get; set; }
/// <summary>
/// Gets or sets the rank of the artwork provider, determining the order in which providers are tried.
/// </summary>
public int Rank { get; set; }
}
@@ -0,0 +1,15 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Requests.Library.Management;
/// <summary>
/// Represents the request for retrieving the artwork providers of a media library.
/// </summary>
/// <param name="LibraryId">The unique identifier of the media library whose artwork providers are retrieved.</param>
[DebuggerDisplay("LibraryId: {LibraryId}")]
public record GetArtworkProvidersRequest(
Guid LibraryId
);
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Requests.Plugins;
/// <summary>
/// Represents a request to reorder the artwork providers of a media library.
/// </summary>
[DebuggerDisplay("LibraryId: {LibraryId}")]
public class ReorderLibraryArtworkProvidersRequest
{
/// <summary>
/// Gets or sets the Id of the media library whose artwork providers are reordered.
/// </summary>
public Guid LibraryId { get; set; }
/// <summary>
/// Gets or sets the plugin Ids in the new order, from highest to lowest rank.
/// </summary>
public List<Guid> PluginIds { get; set; } = [];
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Diagnostics;
#endregion
namespace Lumina.Presentation.Web.Common.Requests.Plugins;
/// <summary>
/// Represents a request to enable or disable an artwork provider for a media library.
/// </summary>
[DebuggerDisplay("LibraryId: {LibraryId}, PluginId: {PluginId}")]
public class SetLibraryArtworkProviderEnabledRequest
{
/// <summary>
/// Gets or sets the Id of the media library whose artwork provider is enabled or disabled.
/// </summary>
public Guid LibraryId { get; set; }
/// <summary>
/// Gets or sets the unique identifier of the plugin providing the artwork.
/// </summary>
public Guid PluginId { get; set; }
/// <summary>
/// Gets or sets whether the artwork provider should be enabled for the media library.
/// </summary>
public bool IsEnabled { get; set; }
}
@@ -24,5 +24,8 @@ public static partial class ApiRoutes
public const string GET_LIBRARY_METADATA_PROVIDERS = "libraries/{libraryId}/metadata-providers";
public const string SET_LIBRARY_METADATA_PROVIDER_ENABLED = "libraries/{libraryId}/metadata-providers/{pluginId}/enabled";
public const string REORDER_LIBRARY_METADATA_PROVIDERS = "libraries/{libraryId}/metadata-providers/reorder";
public const string GET_LIBRARY_ARTWORK_PROVIDERS = "libraries/{libraryId}/artwork-providers";
public const string SET_LIBRARY_ARTWORK_PROVIDER_ENABLED = "libraries/{libraryId}/artwork-providers/{pluginId}/enabled";
public const string REORDER_LIBRARY_ARTWORK_PROVIDERS = "libraries/{libraryId}/artwork-providers/reorder";
}
}
@@ -25,5 +25,8 @@ public static partial class WebRoutes
public const string GET_METADATA_PROVIDERS = "{culture}/libraries/manage/api-get-metadata-providers/{libraryId}";
public const string SET_METADATA_PROVIDER_ENABLED = "{culture}/libraries/manage/api-set-metadata-provider-enabled";
public const string REORDER_METADATA_PROVIDERS = "{culture}/libraries/manage/api-reorder-metadata-providers";
public const string GET_ARTWORK_PROVIDERS = "{culture}/libraries/manage/api-get-artwork-providers/{libraryId}";
public const string SET_ARTWORK_PROVIDER_ENABLED = "{culture}/libraries/manage/api-set-artwork-provider-enabled";
public const string REORDER_ARTWORK_PROVIDERS = "{culture}/libraries/manage/api-reorder-artwork-providers";
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.DTO.Plugins;
using Lumina.Presentation.Web.Common.Requests.Library.Management;
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.Library.Management.GetArtworkProviders;
/// <summary>
/// API endpoint for the <c>/{culture}/libraries/manage/api-get-artwork-providers/{libraryId}</c> route.
/// </summary>
public class GetArtworkProvidersEndpoint : BaseEndpoint<GetArtworkProvidersRequest, IResult>
{
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="GetArtworkProvidersEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public GetArtworkProvidersEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.GET);
Routes(WebRoutes.LibraryManagement.GET_ARTWORK_PROVIDERS);
DontAutoTag();
Options(options => options.WithTags("Libraries"));
}
/// <summary>
/// Retrieves the artwork providers of a media library.
/// </summary>
/// <param name="request">The request containing the Id of the media library whose artwork providers are retrieved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetArtworkProvidersRequest request, CancellationToken cancellationToken)
{
LibraryArtworkProviderDto[] response = await _apiHttpClient.GetAsync<LibraryArtworkProviderDto[]>(ApiRoutes.Libraries.GET_LIBRARY_ARTWORK_PROVIDERS.Replace("{libraryId}", request.LibraryId.ToString()), cancellationToken).ConfigureAwait(false);
return JsonSuccess(response);
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.DTO.Plugins;
using Lumina.Presentation.Web.Common.Requests.Library.Management;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetArtworkProviders;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetArtworkProvidersEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtworkProvidersEndpointSummary : Summary<GetArtworkProvidersEndpoint, GetArtworkProvidersRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetArtworkProvidersEndpointSummary"/> class.
/// </summary>
public GetArtworkProvidersEndpointSummary()
{
Summary = "Retrieves the artwork providers of a media library.";
Description = "Retrieves the artwork providers of the media library identified by the request.";
RequestParam(r => r.LibraryId, "The unique identifier of the media library whose artwork providers are retrieved.");
Response(200, "The artwork providers of the media library are returned.", example: new SuccessResponse<LibraryArtworkProviderDto[]>(true, default));
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Plugins;
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.Library.Management.ReorderArtworkProviders;
/// <summary>
/// API endpoint for the <c>/{culture}/libraries/manage/api-reorder-artwork-providers</c> route.
/// </summary>
public class ReorderArtworkProvidersEndpoint : BaseEndpoint<ReorderLibraryArtworkProvidersRequest, IResult>
{
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="ReorderArtworkProvidersEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public ReorderArtworkProvidersEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.PUT);
Routes(WebRoutes.LibraryManagement.REORDER_ARTWORK_PROVIDERS);
DontAutoTag();
Options(options => options.WithTags("Libraries"));
EnableAntiforgery();
}
/// <summary>
/// Reorders the artwork providers of a media library.
/// </summary>
/// <param name="request">The request containing the Id of the media library and the plugin Ids in the new order.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(ReorderLibraryArtworkProvidersRequest request, CancellationToken cancellationToken)
{
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, ReorderLibraryArtworkProvidersRequest>(ApiRoutes.Libraries.REORDER_LIBRARY_ARTWORK_PROVIDERS.Replace("{libraryId}", request.LibraryId.ToString()), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
@@ -0,0 +1,34 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderArtworkProviders;
/// <summary>
/// Class used for providing a textual description for the <see cref="ReorderArtworkProvidersEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderArtworkProvidersEndpointSummary : Summary<ReorderArtworkProvidersEndpoint, ReorderLibraryArtworkProvidersRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="ReorderArtworkProvidersEndpointSummary"/> class.
/// </summary>
public ReorderArtworkProvidersEndpointSummary()
{
Summary = "Reorders the artwork providers of a media library.";
Description = "Reorders the artwork providers of the media library identified by the request, in the provided order.";
RequestParam(r => r.LibraryId, "The Id of the media library whose artwork providers are reordered. Required.");
ExampleRequest = new ReorderLibraryArtworkProvidersRequest
{
LibraryId = Guid.NewGuid(),
PluginIds = [Guid.NewGuid(), Guid.NewGuid()]
};
Response(200, "The artwork providers of the media library are reordered.", example: new SuccessResponse(true));
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.Api;
using Lumina.Presentation.Web.Common.Requests.Plugins;
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.Library.Management.SetArtworkProviderEnabled;
/// <summary>
/// API endpoint for the <c>/{culture}/libraries/manage/api-set-artwork-provider-enabled</c> route.
/// </summary>
public class SetArtworkProviderEnabledEndpoint : BaseEndpoint<SetLibraryArtworkProviderEnabledRequest, IResult>
{
private readonly IApiHttpClient _apiHttpClient;
/// <summary>
/// Initializes a new instance of the <see cref="SetArtworkProviderEnabledEndpoint"/> class.
/// </summary>
/// <param name="apiHttpClient">Injected service for interactions with the API.</param>
public SetArtworkProviderEnabledEndpoint(IApiHttpClient apiHttpClient)
{
_apiHttpClient = apiHttpClient;
}
/// <summary>
/// Configures the endpoint.
/// </summary>
public override void Configure()
{
base.Configure();
Verbs(Http.PUT);
Routes(WebRoutes.LibraryManagement.SET_ARTWORK_PROVIDER_ENABLED);
DontAutoTag();
Options(options => options.WithTags("Libraries"));
EnableAntiforgery();
}
/// <summary>
/// Enables or disables an artwork provider of a media library.
/// </summary>
/// <param name="request">The request containing the Ids of the media library and of the plugin, and whether the provider is enabled.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(SetLibraryArtworkProviderEnabledRequest request, CancellationToken cancellationToken)
{
await _apiHttpClient.PutAsync<Web.Common.Requests.Common.EmptyRequest, SetLibraryArtworkProviderEnabledRequest>(ApiRoutes.Libraries.SET_LIBRARY_ARTWORK_PROVIDER_ENABLED.Replace("{libraryId}", request.LibraryId.ToString()).Replace("{pluginId}", request.PluginId.ToString()), request, cancellationToken).ConfigureAwait(false);
return JsonSuccess();
}
}
@@ -0,0 +1,37 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Presentation.Web.Common.DTO.Common;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using System;
using System.Diagnostics.CodeAnalysis;
#endregion
namespace Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetArtworkProviderEnabled;
/// <summary>
/// Class used for providing a textual description for the <see cref="SetArtworkProviderEnabledEndpoint"/> endpoint, for OpenAPI.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetArtworkProviderEnabledEndpointSummary : Summary<SetArtworkProviderEnabledEndpoint, SetLibraryArtworkProviderEnabledRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="SetArtworkProviderEnabledEndpointSummary"/> class.
/// </summary>
public SetArtworkProviderEnabledEndpointSummary()
{
Summary = "Enables or disables an artwork provider of a media library.";
Description = "Enables or disables the artwork provider of the media library identified by the request.";
RequestParam(r => r.LibraryId, "The Id of the media library whose artwork provider is enabled or disabled. Required.");
RequestParam(r => r.PluginId, "The unique identifier of the plugin providing the artwork. Required.");
RequestParam(r => r.IsEnabled, "Whether the artwork provider should be enabled for the media library, or not. Required.");
ExampleRequest = new SetLibraryArtworkProviderEnabledRequest
{
LibraryId = Guid.NewGuid(),
PluginId = Guid.NewGuid(),
IsEnabled = true
};
Response(200, "The artwork provider of the media library is enabled or disabled.", example: new SuccessResponse(true));
}
}
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>مزوّدو البيانات الوصفية المستخدمون لإثراء عناصر هذه المكتبة، بالترتيب الذي يتم تجريبهم به.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>Die Metadatenanbieter, die verwendet werden, um die Elemente dieser Bibliothek anzureichern, in der Reihenfolge, in der sie versucht werden.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>The metadata providers used to enrich the items of this library, in the order they are tried.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>Los proveedores de metadatos utilizados para enriquecer los elementos de esta biblioteca, en el orden en que se prueban.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>Les fournisseurs de métadonnées utilisés pour enrichir les éléments de cette bibliothèque, dans l'ordre où ils sont essayés.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>I fornitori di metadati utilizzati per arricchire gli elementi di questa libreria, nell'ordine in cui vengono provati.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>このライブラリのアイテムを補完するために使用されるメタデータプロバイダーを、試行する順序で指定します。</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>The metadata providers used to enrich the items of this library, in the order they are tried.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>Furnizorii de metadate folosiți pentru a îmbogăți elementele acestei biblioteci, în ordinea în care sunt încercați.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>Постачальники метаданих, які використовуються для збагачення елементів цієї бібліотеки, у порядку, в якому вони випробовуються.</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -336,4 +336,10 @@
<data name="DescriptionMetadataProviders" xml:space="preserve">
<value>用于丰富此库项目内容的元数据提供程序,按其尝试顺序排列。</value>
</data>
<data name="ArtworkProviders" xml:space="preserve">
<value>Artwork providers</value>
</data>
<data name="DescriptionArtworkProviders" xml:space="preserve">
<value>The artwork providers used to retrieve the covers of the items of this library, in the order they are tried.</value>
</data>
</root>
@@ -222,6 +222,22 @@
</table>
<small class="form-label text-disabled form-description">@_localizer["DescriptionMetadataProviders"]</small>
</div>
<h3 class="text-light-two">@_localizer["ArtworkProviders"]</h3>
<div class="form-row">
<table id="artwork-providers-table" class="w-100">
<thead>
<tr>
<th class="w-50">@_localizer["Name"]</th>
<th class="w-15 text-center">@_localizer["Enabled"]</th>
<th class="w-35 text-center">@_localizer["Order"]</th>
</tr>
</thead>
<tbody>
<!-- artwork providers will be populated here -->
</tbody>
</table>
<small class="form-label text-disabled form-description">@_localizer["DescriptionArtworkProviders"]</small>
</div>
}
<div class="form-row">
<button type="submit" class="confirm-button w-100px">@_localizer["Save"]</button>
@@ -435,6 +451,77 @@
}
};
const artworkProvidersTable = document.getElementById('artwork-providers-table');
const artworkProvidersTbody = artworkProvidersTable ? artworkProvidersTable.querySelector('tbody') : null;
// loads the artwork providers configured for the library, when editing an existing library
async function loadArtworkProvidersAsync() {
if (!id || !artworkProvidersTbody) return;
const url = '@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.GET_ARTWORK_PROVIDERS, new { libraryId = default(Guid) })'
.replace('/@(default(Guid))', `/${id}`); // libraryId needs to be replaced here, because GetAbsoluteUrl is server side, libraryId is client side
const response = await callApiGetAsync(url);
if (response && response.length > 0) {
artworkProvidersTbody.innerHTML = response.map((provider, index) => renderArtworkProviderRow(provider, index, response.length)).join('');
}
}
// renders an artwork provider row of the library
function renderArtworkProviderRow(provider, index, count) {
return `
<tr data-provider-plugin-id="${provider.pluginId}">
<td>${provider.name}</td>
<td class="text-center">
<label class="enlightenment-checkbox-label">
<input type="checkbox" class="enlightenment-checkbox-hidden artwork-provider-enabled" ${provider.isEnabled ? 'checked' : ''} />
<span class="enlightenment-checkbox"></span>
</label>
</td>
<td class="text-center">
<button type="button" class="artwork-provider-move-up confirm-button f-12 h-20px" ${index === 0 ? 'disabled' : ''}>@_localizer["MoveUp"]</button>
<button type="button" class="artwork-provider-move-down abort-button f-12 h-20px" ${index === count - 1 ? 'disabled' : ''}>@_localizer["MoveDown"]</button>
</td>
</tr>`;
}
// on artwork provider move button click, reorders the providers and persists the new order
async function handleArtworkProviderReorderAsync(e) {
const button = e.target.closest('.artwork-provider-move-up, .artwork-provider-move-down');
if (!button || !artworkProvidersTbody) return;
const row = button.closest('tr');
if (button.classList.contains('artwork-provider-move-up')) {
const previousRow = row.previousElementSibling;
if (previousRow) artworkProvidersTbody.insertBefore(row, previousRow);
} else {
const nextRow = row.nextElementSibling;
if (nextRow) artworkProvidersTbody.insertBefore(nextRow, row);
}
await saveArtworkProviderOrderAsync();
}
// persists the current order of the artwork providers of the library
async function saveArtworkProviderOrderAsync() {
if (!id || !artworkProvidersTbody) return;
const pluginIds = Array.from(artworkProvidersTbody.querySelectorAll('tr[data-provider-plugin-id]'))
.map(row => row.getAttribute('data-provider-plugin-id'));
const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.REORDER_ARTWORK_PROVIDERS)', { libraryId: id, pluginIds: pluginIds });
if (result.success) {
notificationService.show('@_localizer["OrderSaved"]', NotificationType.SUCCESS);
}
}
// on artwork provider enabled checkbox change, persists the new state
async function handleArtworkProviderEnabledChangeAsync(e) {
if (e.target.matches('.artwork-provider-enabled')) {
const row = e.target.closest('tr');
const pluginId = row.getAttribute('data-provider-plugin-id');
const isEnabled = e.target.checked;
const result = await callApiPutAsync('@_urlService.GetAbsoluteUrl(WebRoutes.LibraryManagement.SET_ARTWORK_PROVIDER_ENABLED)', { libraryId: id, pluginId: pluginId, isEnabled: isEnabled });
if (!result.success) {
e.target.checked = !isEnabled;
}
}
};
// add listeners
form.addEventListener('keypress', handleEnterKey);
form.addEventListener('submit', handleSubmit);
@@ -448,6 +535,10 @@
metadataProvidersTbody.addEventListener('click', handleMetadataProviderReorderAsync);
metadataProvidersTbody.addEventListener('change', handleMetadataProviderEnabledChangeAsync);
}
if (artworkProvidersTbody) {
artworkProvidersTbody.addEventListener('click', handleArtworkProviderReorderAsync);
artworkProvidersTbody.addEventListener('change', handleArtworkProviderEnabledChangeAsync);
}
// register cleanup for these listeners
cleanupFunctions.push(() => {
@@ -463,11 +554,16 @@
metadataProvidersTbody.removeEventListener('click', handleMetadataProviderReorderAsync);
metadataProvidersTbody.removeEventListener('change', handleMetadataProviderEnabledChangeAsync);
}
if (artworkProvidersTbody) {
artworkProvidersTbody.removeEventListener('click', handleArtworkProviderReorderAsync);
artworkProvidersTbody.removeEventListener('change', handleArtworkProviderEnabledChangeAsync);
}
});
// load the metadata providers when editing an existing library
// load the metadata and artwork providers when editing an existing library
if (id) {
loadMetadataProvidersAsync();
loadArtworkProvidersAsync();
}
// store all cleanups for this view on window object using the scriptId
@@ -0,0 +1,52 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.DTO.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
/// <summary>
/// Fixture class for generating <see cref="LibraryArtworkProviderDto"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class LibraryArtworkProviderDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="LibraryArtworkProviderDto"/> instance with randomized test data.
/// </summary>
/// <param name="pluginId">Optional unique identifier of the plugin providing the artwork.</param>
/// <param name="name">Optional display name of the artwork provider.</param>
/// <param name="isEnabled">Whether the artwork provider is enabled for the media library or not.</param>
/// <param name="rank">Optional rank of the artwork provider, determining the order in which providers are tried.</param>
/// <returns>A configured <see cref="LibraryArtworkProviderDto"/> instance.</returns>
public LibraryArtworkProviderDto Create(
Guid? pluginId = null,
string? name = null,
bool? isEnabled = null,
int? rank = null)
{
return new LibraryArtworkProviderDto
{
PluginId = pluginId ?? Guid.NewGuid(),
Name = name ?? _faker.Company.CompanyName(),
IsEnabled = isEnabled ?? _faker.Random.Bool(),
Rank = rank ?? _faker.Random.Int(0, 100)
};
}
/// <summary>
/// Creates multiple <see cref="LibraryArtworkProviderDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="LibraryArtworkProviderDto"/> instances.</returns>
public List<LibraryArtworkProviderDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,46 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
/// <summary>
/// Fixture class for generating <see cref="ReorderLibraryArtworkProvidersRequest"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderLibraryArtworkProvidersRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="ReorderLibraryArtworkProvidersRequest"/> instance with randomized test data.
/// </summary>
/// <param name="libraryId">Optional identifier of the media library.</param>
/// <param name="pluginIds">Optional plugin Ids in the new order.</param>
/// <returns>A configured <see cref="ReorderLibraryArtworkProvidersRequest"/> instance.</returns>
public ReorderLibraryArtworkProvidersRequest Create(
Guid? libraryId = null,
List<Guid>? pluginIds = null)
{
return new ReorderLibraryArtworkProvidersRequest
{
LibraryId = libraryId ?? Guid.NewGuid(),
PluginIds = pluginIds ?? [_faker.Random.Guid(), _faker.Random.Guid()]
};
}
/// <summary>
/// Creates multiple <see cref="ReorderLibraryArtworkProvidersRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="ReorderLibraryArtworkProvidersRequest"/> instances.</returns>
public List<ReorderLibraryArtworkProvidersRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using Bogus;
using Lumina.Presentation.Web.Common.Requests.Plugins;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
#endregion
namespace Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
/// <summary>
/// Fixture class for generating <see cref="SetLibraryArtworkProviderEnabledRequest"/> test data.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetLibraryArtworkProviderEnabledRequestFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="SetLibraryArtworkProviderEnabledRequest"/> instance with randomized test data.
/// </summary>
/// <param name="libraryId">Optional identifier of the media library.</param>
/// <param name="pluginId">Optional identifier of the plugin.</param>
/// <param name="isEnabled">Optional value indicating whether the artwork provider is enabled.</param>
/// <returns>A configured <see cref="SetLibraryArtworkProviderEnabledRequest"/> instance.</returns>
public SetLibraryArtworkProviderEnabledRequest Create(
Guid? libraryId = null,
Guid? pluginId = null,
bool? isEnabled = null)
{
return new SetLibraryArtworkProviderEnabledRequest
{
LibraryId = libraryId ?? Guid.NewGuid(),
PluginId = pluginId ?? Guid.NewGuid(),
IsEnabled = isEnabled ?? _faker.Random.Bool()
};
}
/// <summary>
/// Creates multiple <see cref="SetLibraryArtworkProviderEnabledRequest"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="SetLibraryArtworkProviderEnabledRequest"/> instances.</returns>
public List<SetLibraryArtworkProviderEnabledRequest> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,84 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.DTO.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.GetArtworkProviders;
using Lumina.Presentation.Web.Fixtures.Common.DTO.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.GetArtworkProviders;
/// <summary>
/// Contains integration tests for the <c>/{culture}/libraries/manage/api-get-artwork-providers/{{libraryId}}</c> route served by the <see cref="GetArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class GetArtworkProvidersEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly LibraryArtworkProviderDtoFixture _libraryArtworkProviderDtoFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="GetArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public GetArtworkProvidersEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task GetArtworkProviders_WhenCalledByAuthenticatedUser_ShouldReturnArtworkProvidersJson()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
LibraryArtworkProviderDto[] expectedProviders =
[
_libraryArtworkProviderDtoFixture.Create(name: "Artwork Provider One", isEnabled: true, rank: 1),
_libraryArtworkProviderDtoFixture.Create(name: "Artwork Provider Two", isEnabled: false, rank: 2)
];
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artwork-providers", expectedProviders);
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-artwork-providers/{libraryId}");
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
JsonElement data = json.RootElement.GetProperty("data");
Assert.Equal(2, data.GetArrayLength());
Assert.Equal("Artwork Provider One", data[0].GetProperty("name").GetString());
}
[Fact]
public async Task GetArtworkProviders_WhenCalled_ShouldRequestArtworkProvidersFromApi()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
_apiFactory.ApiClientStub.RegisterGetResponse($"libraries/{libraryId}/artwork-providers", Array.Empty<LibraryArtworkProviderDto>());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage getRequest = new(HttpMethod.Get, $"/en-us/libraries/manage/api-get-artwork-providers/{libraryId}");
getRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(getRequest);
// Assert
response.EnsureSuccessStatusCode();
Assert.Contains($"libraries/{libraryId}/artwork-providers", _apiFactory.ApiClientStub.GetEndpointsCalled);
}
}
@@ -0,0 +1,71 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.ReorderArtworkProviders;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.ReorderArtworkProviders;
/// <summary>
/// Contains integration tests for the <c>/{culture}/libraries/manage/api-reorder-artwork-providers</c> route served by the <see cref="ReorderArtworkProvidersEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class ReorderArtworkProvidersEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly ReorderLibraryArtworkProvidersRequestFixture _reorderLibraryArtworkProvidersRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="ReorderArtworkProvidersEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public ReorderArtworkProvidersEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task ReorderArtworkProviders_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldReorderProvidersAndReturnSuccess()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid firstPluginId = Guid.NewGuid();
Guid secondPluginId = Guid.NewGuid();
ReorderLibraryArtworkProvidersRequest request = _reorderLibraryArtworkProvidersRequestFixture.Create(
libraryId: libraryId,
pluginIds: [firstPluginId, secondPluginId]
);
string expectedEndpoint = $"libraries/{libraryId}/artwork-providers/reorder";
_apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-reorder-artwork-providers")
{
Content = JsonContent.Create(request)
};
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
}
}
@@ -0,0 +1,71 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Web.Common.Requests.Plugins;
using Lumina.Presentation.Web.Core.Endpoints.Library.Management.SetArtworkProviderEnabled;
using Lumina.Presentation.Web.Fixtures.Common.Requests.Plugins;
using Lumina.Presentation.Web.Fixtures.Common.TestHelpers;
using Lumina.Presentation.Web.IntegrationTests.Common.Setup;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Web.IntegrationTests.Core.Endpoints.Library.Management.SetArtworkProviderEnabled;
/// <summary>
/// Contains integration tests for the <c>/{culture}/libraries/manage/api-set-artwork-provider-enabled</c> route served by the <see cref="SetArtworkProviderEnabledEndpoint"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class SetArtworkProviderEnabledEndpointTests : IClassFixture<LuminaWebFactory>
{
private readonly LuminaWebFactory _apiFactory;
private readonly SetLibraryArtworkProviderEnabledRequestFixture _setLibraryArtworkProviderEnabledRequestFixture = new();
/// <summary>
/// Initializes a new instance of the <see cref="SetArtworkProviderEnabledEndpointTests"/> class.
/// </summary>
/// <param name="apiFactory">Injected Web application factory.</param>
public SetArtworkProviderEnabledEndpointTests(LuminaWebFactory apiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task SetArtworkProviderEnabled_WhenCalledByAuthenticatedUserWithAntiforgeryToken_ShouldEnableProviderAndReturnSuccess()
{
// Arrange
_apiFactory.ApiClientStub.Reset();
Guid libraryId = Guid.NewGuid();
Guid pluginId = Guid.NewGuid();
SetLibraryArtworkProviderEnabledRequest request = _setLibraryArtworkProviderEnabledRequestFixture.Create(
libraryId: libraryId,
pluginId: pluginId,
isEnabled: true
);
string expectedEndpoint = $"libraries/{libraryId}/artwork-providers/{pluginId}/enabled";
_apiFactory.ApiClientStub.RegisterPutResponseFactory(expectedEndpoint, _ => new Lumina.Presentation.Web.Common.Requests.Common.EmptyRequest());
AuthenticatedWebClient webClient = await WebTestHelpers.CreateAuthenticatedClientAsync(_apiFactory);
HttpRequestMessage updateRequest = new(HttpMethod.Put, "/en-us/libraries/manage/api-set-artwork-provider-enabled")
{
Content = JsonContent.Create(request)
};
updateRequest.Content!.Headers.ContentType = new MediaTypeHeaderValue("application/json");
updateRequest.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
updateRequest.Headers.Add("RequestVerificationToken", webClient.AntiforgeryToken);
// Act
HttpResponseMessage response = await webClient.Client.SendAsync(updateRequest);
string content = await response.Content.ReadAsStringAsync();
// Assert
response.EnsureSuccessStatusCode();
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
using JsonDocument json = JsonDocument.Parse(content);
Assert.True(json.RootElement.GetProperty("success").GetBoolean());
Assert.Contains(_apiFactory.ApiClientStub.PutRequests, putRequest => putRequest.Endpoint == expectedEndpoint);
}
}