From 0abda472c6a614581bd342a6617f9129d6dba52c Mon Sep 17 00:00:00 2001 From: Binary Alley Date: Thu, 1 Oct 2026 12:00:00 +0300 Subject: [PATCH] Adds the MusicBrainz music metadata plugin, its fixtures, and its unit test suite --- .../MusicBrainzServices.cs | 60 + .../Responses/MusicBrainzAliasResponse.cs | 59 + .../Responses/MusicBrainzAreaResponse.cs | 54 + .../MusicBrainzArtistCreditResponse.cs | 29 + .../Responses/MusicBrainzArtistResponse.cs | 120 ++ .../MusicBrainzArtistSearchResponse.cs | 30 + .../Responses/MusicBrainzLabelInfoResponse.cs | 23 + .../Responses/MusicBrainzLabelResponse.cs | 35 + .../Responses/MusicBrainzLifeSpanResponse.cs | 29 + .../Responses/MusicBrainzMediumResponse.cs | 42 + .../Responses/MusicBrainzRatingResponse.cs | 23 + .../MusicBrainzRecordingListResponse.cs | 18 + .../Responses/MusicBrainzRecordingResponse.cs | 90 + .../MusicBrainzRecordingSearchResponse.cs | 30 + .../Responses/MusicBrainzRelationResponse.cs | 60 + .../MusicBrainzReleaseBrowseResponse.cs | 30 + .../MusicBrainzReleaseEventResponse.cs | 23 + .../MusicBrainzReleaseGroupResponse.cs | 78 + .../MusicBrainzReleaseGroupSearchResponse.cs | 30 + .../Responses/MusicBrainzReleaseResponse.cs | 120 ++ .../Responses/MusicBrainzTagResponse.cs | 35 + .../MusicBrainzTextRepresentationResponse.cs | 23 + .../Responses/MusicBrainzTrackResponse.cs | 47 + .../Responses/MusicBrainzUrlResponse.cs | 23 + .../Responses/MusicBrainzWorkResponse.cs | 66 + .../DTO/Settings/MusicBrainzSettingsDto.cs | 49 + .../Core/Api/MusicBrainzHttpClient.cs | 336 ++++ .../Core/Api/MusicBrainzRequestThrottle.cs | 49 + .../Core/Api/MusicBrainzResponseCache.cs | 140 ++ .../Core/Mapping/MusicBrainzMapper.cs | 759 +++++++++ .../Core/MusicBrainzAlbumMetadataProvider.cs | 206 +++ .../Core/MusicBrainzArtistMetadataProvider.cs | 103 ++ .../Core/MusicBrainzPlugin.cs | 97 ++ .../Core/MusicBrainzTrackMetadataProvider.cs | 270 +++ .../Core/Settings/MusicBrainzSettingsKeys.cs | 37 + .../Settings/MusicBrainzSettingsProvider.cs | 210 +++ .../Lumina.Plugins.MusicBrainz.csproj | 34 + .../Properties/AssemblyInfo.cs | 6 + .../MusicBrainzAliasResponseFixture.cs | 80 + .../MusicBrainzAreaResponseFixture.cs | 71 + .../MusicBrainzArtistCreditResponseFixture.cs | 57 + .../MusicBrainzArtistResponseFixture.cs | 124 ++ .../MusicBrainzArtistSearchResponseFixture.cs | 51 + .../MusicBrainzLabelInfoResponseFixture.cs | 51 + .../MusicBrainzLabelResponseFixture.cs | 60 + .../MusicBrainzLifeSpanResponseFixture.cs | 55 + .../MusicBrainzMediumResponseFixture.cs | 61 + .../MusicBrainzRatingResponseFixture.cs | 50 + ...MusicBrainzRecordingListResponseFixture.cs | 41 + .../MusicBrainzRecordingResponseFixture.cs | 98 ++ ...sicBrainzRecordingSearchResponseFixture.cs | 51 + .../MusicBrainzRelationResponseFixture.cs | 85 + ...MusicBrainzReleaseBrowseResponseFixture.cs | 51 + .../MusicBrainzReleaseEventResponseFixture.cs | 51 + .../MusicBrainzReleaseGroupResponseFixture.cs | 89 + ...BrainzReleaseGroupSearchResponseFixture.cs | 51 + .../MusicBrainzReleaseResponseFixture.cs | 123 ++ .../MusicBrainzTagResponseFixture.cs | 58 + ...BrainzTextRepresentationResponseFixture.cs | 50 + .../MusicBrainzTrackResponseFixture.cs | 71 + .../MusicBrainzUrlResponseFixture.cs | 50 + .../MusicBrainzWorkResponseFixture.cs | 77 + .../Settings/MusicBrainzSettingsDtoFixture.cs | 63 + ...Lumina.Plugins.MusicBrainz.Fixtures.csproj | 25 + .../Properties/AssemblyInfo.cs | 22 + .../MusicBrainzServicesTests.cs | 147 ++ .../MusicBrainzAliasResponseTests.cs | 75 + .../Responses/MusicBrainzAreaResponseTests.cs | 70 + .../MusicBrainzArtistCreditResponseTests.cs | 54 + .../MusicBrainzArtistResponseTests.cs | 103 ++ .../MusicBrainzArtistSearchResponseTests.cs | 52 + .../MusicBrainzLabelInfoResponseTests.cs | 51 + .../MusicBrainzLabelResponseTests.cs | 54 + .../MusicBrainzLifeSpanResponseTests.cs | 65 + .../MusicBrainzMediumResponseTests.cs | 57 + .../MusicBrainzRatingResponseTests.cs | 66 + .../MusicBrainzRecordingListResponseTests.cs | 50 + .../MusicBrainzRecordingResponseTests.cs | 86 + ...MusicBrainzRecordingSearchResponseTests.cs | 52 + .../MusicBrainzRelationResponseTests.cs | 77 + .../MusicBrainzReleaseBrowseResponseTests.cs | 52 + .../MusicBrainzReleaseEventResponseTests.cs | 52 + .../MusicBrainzReleaseGroupResponseTests.cs | 79 + ...icBrainzReleaseGroupSearchResponseTests.cs | 52 + .../MusicBrainzReleaseResponseTests.cs | 135 ++ .../Responses/MusicBrainzTagResponseTests.cs | 54 + ...icBrainzTextRepresentationResponseTests.cs | 44 + .../MusicBrainzTrackResponseTests.cs | 70 + .../Responses/MusicBrainzUrlResponseTests.cs | 44 + .../Responses/MusicBrainzWorkResponseTests.cs | 64 + .../TestHelpers/StubHttpMessageHandler.cs | 60 + .../Core/Api/MusicBrainzHttpClientTests.cs | 578 +++++++ .../Api/MusicBrainzRequestThrottleTests.cs | 106 ++ .../Core/Api/MusicBrainzResponseCacheTests.cs | 149 ++ .../Core/Mapping/MusicBrainzMapperTests.cs | 1508 +++++++++++++++++ .../MusicBrainzAlbumMetadataProviderTests.cs | 592 +++++++ .../MusicBrainzArtistMetadataProviderTests.cs | 308 ++++ .../Core/MusicBrainzPluginTests.cs | 129 ++ .../MusicBrainzTrackMetadataProviderTests.cs | 730 ++++++++ .../MusicBrainzSettingsProviderTests.cs | 359 ++++ ...umina.Plugins.MusicBrainz.UnitTests.csproj | 48 + 101 files changed, 11461 insertions(+) create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/DependencyInjection/MusicBrainzServices.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAliasResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAreaResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzMediumResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRatingResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRelationResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTagResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTrackResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzUrlResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzWorkResponse.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Common/Models/DTO/Settings/MusicBrainzSettingsDto.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzHttpClient.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzRequestThrottle.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzResponseCache.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzAlbumMetadataProvider.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzArtistMetadataProvider.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzPlugin.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzTrackMetadataProvider.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsKeys.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsProvider.cs create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Lumina.Plugins.MusicBrainz.csproj create mode 100644 plugins/Lumina.Plugins.MusicBrainz/Properties/AssemblyInfo.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAliasResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAreaResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzMediumResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRatingResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRelationResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTagResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTrackResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzUrlResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzWorkResponseFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/DTO/Settings/MusicBrainzSettingsDtoFixture.cs create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Lumina.Plugins.MusicBrainz.Fixtures.csproj create mode 100644 tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Properties/AssemblyInfo.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/DependencyInjection/MusicBrainzServicesTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAliasResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAreaResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzMediumResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRatingResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRelationResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTagResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTrackResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzUrlResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzWorkResponseTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/TestHelpers/StubHttpMessageHandler.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzHttpClientTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzRequestThrottleTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzResponseCacheTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Mapping/MusicBrainzMapperTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzAlbumMetadataProviderTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzArtistMetadataProviderTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzPluginTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzTrackMetadataProviderTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Settings/MusicBrainzSettingsProviderTests.cs create mode 100644 tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Lumina.Plugins.MusicBrainz.UnitTests.csproj diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/DependencyInjection/MusicBrainzServices.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/DependencyInjection/MusicBrainzServices.cs new file mode 100644 index 00000000..f4364382 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/DependencyInjection/MusicBrainzServices.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.Core; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using System; +using System.Net.Http; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.DependencyInjection; + +/// +/// Utility class for registering the services of the MusicBrainz metadata provider into the Dependency Injection container. +/// +internal static class MusicBrainzServices +{ + /// + /// Registers the services of the MusicBrainz metadata providers into the Dependency Injection container. + /// + /// The service collection to add the services to. + /// The unique identifier of the plugin that provides the metadata. + /// Action used to configure the . + /// The updated . + internal static IServiceCollection AddMusicBrainzMetadataProviders(this IServiceCollection services, Guid pluginId, Action? settingsCallback = null) + { + ArgumentNullException.ThrowIfNull(services); + + // Build the runtime settings provider per scope, overlaying the settings persisted by the host over the defaults and the optional callback. + services.TryAddScoped(serviceProvider => + { + MusicBrainzSettingsDto defaults = new(); + settingsCallback?.Invoke(defaults); + + IPluginSettingsStore? settingsStore = serviceProvider.GetService(); + return new MusicBrainzSettingsProvider(settingsStore, pluginId, defaults); + }); + + // The throttle must be process-wide, because the MusicBrainz web service enforces its request policy across all callers, not per scope. + services.TryAddSingleton(); + + // The response cache is process-wide, so that an entity shared by many items, like a release shared by all its tracks, is fetched only once. + services.TryAddSingleton(); + + // Redirects are not followed, so the configurable base URL cannot be used to reach an internal address through a redirect from a mirror. + services.AddHttpClient() + .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); + + // Register the metadata providers as keyed by pluginId transient services, so they can be resolved specifically among other IMetadataProvider implementations. + // A single plugin exposes one provider per entity type, because the metadata contract is typed to a single lookup and metadata pair. + services.AddKeyedTransient(pluginId); + services.AddKeyedTransient(pluginId); + services.AddKeyedTransient(pluginId); + + return services; + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAliasResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAliasResponse.cs new file mode 100644 index 00000000..80aa0157 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAliasResponse.cs @@ -0,0 +1,59 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for an alias of a MusicBrainz entity. +/// +internal sealed record MusicBrainzAliasResponse +{ + /// + /// Gets the name of the alias. + /// + [JsonPropertyName("name")] + public string? Name { get; init; } + + /// + /// Gets the sort name of the alias. + /// + [JsonPropertyName("sort-name")] + public string? SortName { get; init; } + + /// + /// Gets the type of the alias. + /// + [JsonPropertyName("type")] + public string? Type { get; init; } + + /// + /// Gets the locale the alias is used in. + /// + [JsonPropertyName("locale")] + public string? Locale { get; init; } + + /// + /// Gets a value indicating whether this is the primary alias. + /// + [JsonPropertyName("primary")] + public bool? IsPrimary { get; init; } + + /// + /// Gets the begin date of the alias. + /// + [JsonPropertyName("begin")] + public string? Begin { get; init; } + + /// + /// Gets the end date of the alias. + /// + [JsonPropertyName("end")] + public string? End { get; init; } + + /// + /// Gets a value indicating whether the alias has ended. + /// + [JsonPropertyName("ended")] + public bool? IsEnded { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAreaResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAreaResponse.cs new file mode 100644 index 00000000..1049e58a --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAreaResponse.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for an area from the MusicBrainz API. +/// +internal sealed record MusicBrainzAreaResponse +{ + /// + /// Gets the MusicBrainz identifier of the area. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the name of the area. + /// + [JsonPropertyName("name")] + public string? Name { get; init; } + + /// + /// Gets the sort name of the area. + /// + [JsonPropertyName("sort-name")] + public string? SortName { get; init; } + + /// + /// Gets the disambiguation comment of the area. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the MusicBrainz type of the area. + /// + [JsonPropertyName("type")] + public string? Type { get; init; } + + /// + /// Gets the ISO 3166-1 codes of the area. + /// + [JsonPropertyName("iso-3166-1-codes")] + public List Iso3166Part1Codes { get; init; } = []; + + /// + /// Gets the ISO 3166-2 codes of the area. + /// + [JsonPropertyName("iso-3166-2-codes")] + public List Iso3166Part2Codes { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponse.cs new file mode 100644 index 00000000..b659ba13 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponse.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a single credit in the artist credit of a MusicBrainz entity. +/// +internal sealed record MusicBrainzArtistCreditResponse +{ + /// + /// Gets the credited name of the artist. + /// + [JsonPropertyName("name")] + public string? Name { get; init; } + + /// + /// Gets the join phrase that follows the credit. + /// + [JsonPropertyName("joinphrase")] + public string? JoinPhrase { get; init; } + + /// + /// Gets the artist the credit refers to. + /// + [JsonPropertyName("artist")] + public MusicBrainzArtistResponse? Artist { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistResponse.cs new file mode 100644 index 00000000..bfedacfd --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistResponse.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for an artist from the MusicBrainz API. +/// +internal sealed record MusicBrainzArtistResponse +{ + /// + /// Gets the MusicBrainz identifier of the artist. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the name of the artist. + /// + [JsonPropertyName("name")] + public string? Name { get; init; } + + /// + /// Gets the sort name of the artist. + /// + [JsonPropertyName("sort-name")] + public string? SortName { get; init; } + + /// + /// Gets the disambiguation comment of the artist. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the MusicBrainz type of the artist. + /// + [JsonPropertyName("type")] + public string? Type { get; init; } + + /// + /// Gets the gender of the artist. + /// + [JsonPropertyName("gender")] + public string? Gender { get; init; } + + /// + /// Gets the ISO 3166-1 alpha-2 code of the country of the artist. + /// + [JsonPropertyName("country")] + public string? Country { get; init; } + + /// + /// Gets the area the artist is primarily identified with. + /// + [JsonPropertyName("area")] + public MusicBrainzAreaResponse? Area { get; init; } + + /// + /// Gets the area the artist began in. + /// + [JsonPropertyName("begin-area")] + public MusicBrainzAreaResponse? BeginArea { get; init; } + + /// + /// Gets the area the artist ended in. + /// + [JsonPropertyName("end-area")] + public MusicBrainzAreaResponse? EndArea { get; init; } + + /// + /// Gets the life span of the artist. + /// + [JsonPropertyName("life-span")] + public MusicBrainzLifeSpanResponse? LifeSpan { get; init; } + + /// + /// Gets the ISNI codes of the artist. + /// + [JsonPropertyName("isnis")] + public List Isnis { get; init; } = []; + + /// + /// Gets the IPI codes of the artist. + /// + [JsonPropertyName("ipis")] + public List Ipis { get; init; } = []; + + /// + /// Gets the alternative names of the artist. + /// + [JsonPropertyName("aliases")] + public List Aliases { get; init; } = []; + + /// + /// Gets the tags of the artist. + /// + [JsonPropertyName("tags")] + public List Tags { get; init; } = []; + + /// + /// Gets the genres of the artist. + /// + [JsonPropertyName("genres")] + public List Genres { get; init; } = []; + + /// + /// Gets the relationships of the artist to other entities. + /// + [JsonPropertyName("relations")] + public List Relations { get; init; } = []; + + /// + /// Gets the aggregated rating of the artist. + /// + [JsonPropertyName("rating")] + public MusicBrainzRatingResponse? Rating { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponse.cs new file mode 100644 index 00000000..21abdaa3 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponse.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for an artist search from the MusicBrainz API. +/// +internal sealed record MusicBrainzArtistSearchResponse +{ + /// + /// Gets the total number of matching artists. + /// + [JsonPropertyName("count")] + public int Count { get; init; } + + /// + /// Gets the offset of the returned artists. + /// + [JsonPropertyName("offset")] + public int Offset { get; init; } + + /// + /// Gets the matching artists. + /// + [JsonPropertyName("artists")] + public List Artists { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponse.cs new file mode 100644 index 00000000..3a45cd2a --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponse.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the label information of a MusicBrainz release. +/// +internal sealed record MusicBrainzLabelInfoResponse +{ + /// + /// Gets the catalog number assigned by the label. + /// + [JsonPropertyName("catalog-number")] + public string? CatalogNumber { get; init; } + + /// + /// Gets the label that issued the release. + /// + [JsonPropertyName("label")] + public MusicBrainzLabelResponse? Label { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelResponse.cs new file mode 100644 index 00000000..2a9c49e8 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelResponse.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a label from the MusicBrainz API. +/// +internal sealed record MusicBrainzLabelResponse +{ + /// + /// Gets the MusicBrainz identifier of the label. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the name of the label. + /// + [JsonPropertyName("name")] + public string? Name { get; init; } + + /// + /// Gets the disambiguation comment of the label. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the label code of the label. + /// + [JsonPropertyName("label-code")] + public int? LabelCode { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponse.cs new file mode 100644 index 00000000..1a8ef2c5 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponse.cs @@ -0,0 +1,29 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the life span of a MusicBrainz artist, label, or area. +/// +internal sealed record MusicBrainzLifeSpanResponse +{ + /// + /// Gets the begin date of the life span. + /// + [JsonPropertyName("begin")] + public string? Begin { get; init; } + + /// + /// Gets the end date of the life span. + /// + [JsonPropertyName("end")] + public string? End { get; init; } + + /// + /// Gets a value indicating whether the life span has ended. + /// + [JsonPropertyName("ended")] + public bool? IsEnded { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzMediumResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzMediumResponse.cs new file mode 100644 index 00000000..e7e2f675 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzMediumResponse.cs @@ -0,0 +1,42 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a medium of a MusicBrainz release. +/// +internal sealed record MusicBrainzMediumResponse +{ + /// + /// Gets the position of the medium within its release. + /// + [JsonPropertyName("position")] + public int Position { get; init; } + + /// + /// Gets the title of the medium. + /// + [JsonPropertyName("title")] + public string? Title { get; init; } + + /// + /// Gets the format of the medium (e.g., CD, Vinyl, Digital Media). + /// + [JsonPropertyName("format")] + public string? Format { get; init; } + + /// + /// Gets the number of tracks of the medium. + /// + [JsonPropertyName("track-count")] + public int TrackCount { get; init; } + + /// + /// Gets the tracks of the medium. The tracks are only returned when the recordings are included in the request. + /// + [JsonPropertyName("tracks")] + public List Tracks { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRatingResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRatingResponse.cs new file mode 100644 index 00000000..f0983b8a --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRatingResponse.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the aggregated rating of a MusicBrainz entity. +/// +internal sealed record MusicBrainzRatingResponse +{ + /// + /// Gets the average rating value. + /// + [JsonPropertyName("value")] + public decimal? Value { get; init; } + + /// + /// Gets the number of votes that contributed to the rating. + /// + [JsonPropertyName("votes-count")] + public int? VotesCount { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponse.cs new file mode 100644 index 00000000..a1dbc913 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponse.cs @@ -0,0 +1,18 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the recordings returned by an ISRC lookup from the MusicBrainz API. +/// +internal sealed record MusicBrainzRecordingListResponse +{ + /// + /// Gets the recordings that carry the looked up ISRC. + /// + [JsonPropertyName("recordings")] + public List Recordings { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingResponse.cs new file mode 100644 index 00000000..9b773f15 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingResponse.cs @@ -0,0 +1,90 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a recording from the MusicBrainz API. +/// +internal sealed record MusicBrainzRecordingResponse +{ + /// + /// Gets the MusicBrainz identifier of the recording. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the title of the recording. + /// + [JsonPropertyName("title")] + public string? Title { get; init; } + + /// + /// Gets the disambiguation comment of the recording. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the length of the recording in milliseconds. + /// + [JsonPropertyName("length")] + public long? Length { get; init; } + + /// + /// Gets a value indicating whether the recording is a video recording. + /// + [JsonPropertyName("video")] + public bool? IsVideo { get; init; } + + /// + /// Gets the date the recording was first released. + /// + [JsonPropertyName("first-release-date")] + public string? FirstReleaseDate { get; init; } + + /// + /// Gets the artist credit of the recording. + /// + [JsonPropertyName("artist-credit")] + public List ArtistCredit { get; init; } = []; + + /// + /// Gets the ISRC (International Standard Recording Code) of the recording. + /// + [JsonPropertyName("isrcs")] + public List Isrcs { get; init; } = []; + + /// + /// Gets the releases the recording appears on. + /// + [JsonPropertyName("releases")] + public List Releases { get; init; } = []; + + /// + /// Gets the tags of the recording. + /// + [JsonPropertyName("tags")] + public List Tags { get; init; } = []; + + /// + /// Gets the genres of the recording. + /// + [JsonPropertyName("genres")] + public List Genres { get; init; } = []; + + /// + /// Gets the relationships of the recording to other entities (e.g., its work, and its performers). + /// + [JsonPropertyName("relations")] + public List Relations { get; init; } = []; + + /// + /// Gets the aggregated rating of the recording. + /// + [JsonPropertyName("rating")] + public MusicBrainzRatingResponse? Rating { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponse.cs new file mode 100644 index 00000000..6e9fe611 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponse.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a recording search from the MusicBrainz API. +/// +internal sealed record MusicBrainzRecordingSearchResponse +{ + /// + /// Gets the total number of matching recordings. + /// + [JsonPropertyName("count")] + public int Count { get; init; } + + /// + /// Gets the offset of the returned recordings. + /// + [JsonPropertyName("offset")] + public int Offset { get; init; } + + /// + /// Gets the matching recordings. + /// + [JsonPropertyName("recordings")] + public List Recordings { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRelationResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRelationResponse.cs new file mode 100644 index 00000000..269fcc50 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRelationResponse.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a relationship between a MusicBrainz entity and another entity. +/// +internal sealed record MusicBrainzRelationResponse +{ + /// + /// Gets the type of the relationship (e.g., producer, composer, member of band). + /// + [JsonPropertyName("type")] + public string? Type { get; init; } + + /// + /// Gets the MusicBrainz identifier of the type of the relationship. + /// + [JsonPropertyName("type-id")] + public string? TypeId { get; init; } + + /// + /// Gets the direction of the relationship. + /// + [JsonPropertyName("direction")] + public string? Direction { get; init; } + + /// + /// Gets the type of the entity the relationship targets. + /// + [JsonPropertyName("target-type")] + public string? TargetType { get; init; } + + /// + /// Gets the artist the relationship targets, when the target is an artist. + /// + [JsonPropertyName("artist")] + public MusicBrainzArtistResponse? Artist { get; init; } + + /// + /// Gets the work the relationship targets, when the target is a work. + /// + [JsonPropertyName("work")] + public MusicBrainzWorkResponse? Work { get; init; } + + /// + /// Gets the URL the relationship targets, when the target is a URL. + /// + [JsonPropertyName("url")] + public MusicBrainzUrlResponse? Url { get; init; } + + /// + /// Gets the attributes of the relationship (e.g., the instrument that was performed). + /// + [JsonPropertyName("attributes")] + public List Attributes { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponse.cs new file mode 100644 index 00000000..9735cb3a --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponse.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the result of browsing the releases linked to another MusicBrainz entity. +/// +internal sealed record MusicBrainzReleaseBrowseResponse +{ + /// + /// Gets the releases returned by the browse request. + /// + [JsonPropertyName("releases")] + public List Releases { get; init; } = []; + + /// + /// Gets the total number of releases linked to the browsed entity. + /// + [JsonPropertyName("release-count")] + public int ReleaseCount { get; init; } + + /// + /// Gets the offset of the returned releases. + /// + [JsonPropertyName("release-offset")] + public int ReleaseOffset { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponse.cs new file mode 100644 index 00000000..fd4722c7 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponse.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a release event of a MusicBrainz release. +/// +internal sealed record MusicBrainzReleaseEventResponse +{ + /// + /// Gets the date of the release event. + /// + [JsonPropertyName("date")] + public string? Date { get; init; } + + /// + /// Gets the area of the release event. + /// + [JsonPropertyName("area")] + public MusicBrainzAreaResponse? Area { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponse.cs new file mode 100644 index 00000000..50e8e909 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponse.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a release group from the MusicBrainz API. +/// +internal sealed record MusicBrainzReleaseGroupResponse +{ + /// + /// Gets the MusicBrainz identifier of the release group. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the title of the release group. + /// + [JsonPropertyName("title")] + public string? Title { get; init; } + + /// + /// Gets the disambiguation comment of the release group. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the primary type of the release group. + /// + [JsonPropertyName("primary-type")] + public string? PrimaryType { get; init; } + + /// + /// Gets the secondary types of the release group. + /// + [JsonPropertyName("secondary-types")] + public List SecondaryTypes { get; init; } = []; + + /// + /// Gets the date the release group was first released. + /// + [JsonPropertyName("first-release-date")] + public string? FirstReleaseDate { get; init; } + + /// + /// Gets the artist credit of the release group. + /// + [JsonPropertyName("artist-credit")] + public List ArtistCredit { get; init; } = []; + + /// + /// Gets the releases of the release group. + /// + [JsonPropertyName("releases")] + public List Releases { get; init; } = []; + + /// + /// Gets the tags of the release group. + /// + [JsonPropertyName("tags")] + public List Tags { get; init; } = []; + + /// + /// Gets the genres of the release group. + /// + [JsonPropertyName("genres")] + public List Genres { get; init; } = []; + + /// + /// Gets the aggregated rating of the release group. + /// + [JsonPropertyName("rating")] + public MusicBrainzRatingResponse? Rating { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponse.cs new file mode 100644 index 00000000..eafa8cf9 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponse.cs @@ -0,0 +1,30 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a release group search from the MusicBrainz API. +/// +internal sealed record MusicBrainzReleaseGroupSearchResponse +{ + /// + /// Gets the total number of matching release groups. + /// + [JsonPropertyName("count")] + public int Count { get; init; } + + /// + /// Gets the offset of the returned release groups. + /// + [JsonPropertyName("offset")] + public int Offset { get; init; } + + /// + /// Gets the matching release groups. + /// + [JsonPropertyName("release-groups")] + public List ReleaseGroups { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseResponse.cs new file mode 100644 index 00000000..529b7373 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseResponse.cs @@ -0,0 +1,120 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a release from the MusicBrainz API. +/// +internal sealed record MusicBrainzReleaseResponse +{ + /// + /// Gets the MusicBrainz identifier of the release. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the title of the release. + /// + [JsonPropertyName("title")] + public string? Title { get; init; } + + /// + /// Gets the disambiguation comment of the release. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the status of the release (e.g., Official, Bootleg). + /// + [JsonPropertyName("status")] + public string? Status { get; init; } + + /// + /// Gets the date the release was issued. + /// + [JsonPropertyName("date")] + public string? Date { get; init; } + + /// + /// Gets the ISO 3166-1 alpha-2 code of the country the release was issued in. + /// + [JsonPropertyName("country")] + public string? Country { get; init; } + + /// + /// Gets the release events of the release. + /// + [JsonPropertyName("release-events")] + public List ReleaseEvents { get; init; } = []; + + /// + /// Gets the barcode of the release. + /// + [JsonPropertyName("barcode")] + public string? Barcode { get; init; } + + /// + /// Gets the outermost packaging of the release. + /// + [JsonPropertyName("packaging")] + public string? Packaging { get; init; } + + /// + /// Gets the language and script of the titles of the release. + /// + [JsonPropertyName("text-representation")] + public MusicBrainzTextRepresentationResponse? TextRepresentation { get; init; } + + /// + /// Gets the artist credit of the release. + /// + [JsonPropertyName("artist-credit")] + public List ArtistCredit { get; init; } = []; + + /// + /// Gets the release group the release belongs to. + /// + [JsonPropertyName("release-group")] + public MusicBrainzReleaseGroupResponse? ReleaseGroup { get; init; } + + /// + /// Gets the label information of the release. + /// + [JsonPropertyName("label-info")] + public List LabelInfo { get; init; } = []; + + /// + /// Gets the media of the release. + /// + [JsonPropertyName("media")] + public List Media { get; init; } = []; + + /// + /// Gets the ASIN (Amazon Standard Identification Number) of the release. + /// + [JsonPropertyName("asin")] + public string? Asin { get; init; } + + /// + /// Gets the tags of the release. + /// + [JsonPropertyName("tags")] + public List Tags { get; init; } = []; + + /// + /// Gets the genres of the release. + /// + [JsonPropertyName("genres")] + public List Genres { get; init; } = []; + + /// + /// Gets the relationships of the release to other entities (e.g., its producers and engineers). + /// + [JsonPropertyName("relations")] + public List Relations { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTagResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTagResponse.cs new file mode 100644 index 00000000..a14387ba --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTagResponse.cs @@ -0,0 +1,35 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a tag or a genre of a MusicBrainz entity. +/// +internal sealed record MusicBrainzTagResponse +{ + /// + /// Gets the MusicBrainz identifier of the genre, when the tag is a genre. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the name of the tag. + /// + [JsonPropertyName("name")] + public string? Name { get; init; } + + /// + /// Gets the disambiguation comment of the genre, when the tag is a genre. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the number of votes the tag received. + /// + [JsonPropertyName("count")] + public int Count { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponse.cs new file mode 100644 index 00000000..ab04f364 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponse.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for the language and script of the titles of a MusicBrainz release. +/// +internal sealed record MusicBrainzTextRepresentationResponse +{ + /// + /// Gets the ISO 639-3 language code of the release. + /// + [JsonPropertyName("language")] + public string? Language { get; init; } + + /// + /// Gets the ISO 15924 script code of the release. + /// + [JsonPropertyName("script")] + public string? Script { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTrackResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTrackResponse.cs new file mode 100644 index 00000000..0015672f --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTrackResponse.cs @@ -0,0 +1,47 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a track of a medium of a MusicBrainz release, including the recording it is a performance of. +/// +internal sealed record MusicBrainzTrackResponse +{ + /// + /// Gets the MusicBrainz identifier of the track. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the track number, as displayed on the medium (for example, "1" or "A1"). + /// + [JsonPropertyName("number")] + public string? Number { get; init; } + + /// + /// Gets the position of the track within its medium. + /// + [JsonPropertyName("position")] + public int Position { get; init; } + + /// + /// Gets the title of the track. + /// + [JsonPropertyName("title")] + public string? Title { get; init; } + + /// + /// Gets the length of the track in milliseconds. + /// + [JsonPropertyName("length")] + public long? Length { get; init; } + + /// + /// Gets the recording the track is a performance of. + /// + [JsonPropertyName("recording")] + public MusicBrainzRecordingResponse? Recording { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzUrlResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzUrlResponse.cs new file mode 100644 index 00000000..f7d4e06c --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzUrlResponse.cs @@ -0,0 +1,23 @@ +#region ========================================================================= USING ===================================================================================== +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a URL from the MusicBrainz API. +/// +internal sealed record MusicBrainzUrlResponse +{ + /// + /// Gets the MusicBrainz identifier of the URL. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the resource the URL points to. + /// + [JsonPropertyName("resource")] + public string? Resource { get; init; } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzWorkResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzWorkResponse.cs new file mode 100644 index 00000000..09c43be2 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzWorkResponse.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using System.Collections.Generic; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; + +/// +/// Represents a response for a work from the MusicBrainz API. +/// +internal sealed record MusicBrainzWorkResponse +{ + /// + /// Gets the MusicBrainz identifier of the work. + /// + [JsonPropertyName("id")] + public string? Id { get; init; } + + /// + /// Gets the title of the work. + /// + [JsonPropertyName("title")] + public string? Title { get; init; } + + /// + /// Gets the MusicBrainz type of the work. + /// + [JsonPropertyName("type")] + public string? Type { get; init; } + + /// + /// Gets the disambiguation comment of the work. + /// + [JsonPropertyName("disambiguation")] + public string? Disambiguation { get; init; } + + /// + /// Gets the languages of the work. + /// + [JsonPropertyName("languages")] + public List Languages { get; init; } = []; + + /// + /// Gets the ISWC (International Standard Musical Work Code) of the work. + /// + [JsonPropertyName("iswcs")] + public List Iswcs { get; init; } = []; + + /// + /// Gets the relationships of the work to other entities (e.g., its composers and lyricists). + /// + [JsonPropertyName("relations")] + public List Relations { get; init; } = []; + + /// + /// Gets the tags of the work. + /// + [JsonPropertyName("tags")] + public List Tags { get; init; } = []; + + /// + /// Gets the genres of the work. + /// + [JsonPropertyName("genres")] + public List Genres { get; init; } = []; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/DTO/Settings/MusicBrainzSettingsDto.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/DTO/Settings/MusicBrainzSettingsDto.cs new file mode 100644 index 00000000..2c97fbab --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/DTO/Settings/MusicBrainzSettingsDto.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using System; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; + +/// +/// Data transfer object for the settings that configure the MusicBrainz metadata plugin. +/// +internal sealed class MusicBrainzSettingsDto +{ + /// + /// Gets or sets the base URL of the MusicBrainz web service the requests are sent to. + /// Defaults to the public MusicBrainz web service, and can point to a self hosted mirror instead. + /// + public string BaseUrl { get; set; } = "https://musicbrainz.org/ws/2/"; + + /// + /// Gets or sets a value indicating whether the base URL is allowed to point at a private or local host, for a self hosted mirror on a local + /// network. Defaults to , so that a misconfigured base URL cannot silently reach a local service. + /// + public bool DoesAllowPrivateBaseUrl { get; set; } + + /// + /// Gets or sets the user agent sent with every request to the MusicBrainz API. + /// + public string UserAgent { get; set; } = "Lumina-MusicBrainz/1.0"; + + /// + /// Gets or sets the contact email sent with every request to the MusicBrainz API. + /// + public string? ContactEmail { get; set; } + + /// + /// Gets or sets the maximum number of results returned by a single search. + /// + public int SearchResultLimit { get; set; } = 10; + + /// + /// Gets or sets the maximum number of releases fetched for a single release group. + /// + public int ReleaseLookupLimit { get; set; } = 25; + + /// + /// Gets or sets the minimum interval between consecutive requests to the MusicBrainz API. + /// MusicBrainz requires client applications to make no more than one request per second. + /// + public TimeSpan MinimumRequestInterval { get; set; } = TimeSpan.FromSeconds(1.0); +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzHttpClient.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzHttpClient.cs new file mode 100644 index 00000000..70407049 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzHttpClient.cs @@ -0,0 +1,336 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core.Api; + +/// +/// HTTP client that calls the MusicBrainz web service and deserializes its JSON responses into typed response models. +/// +internal sealed class MusicBrainzHttpClient +{ + private readonly HttpClient _httpClient; + private readonly MusicBrainzSettingsProvider _settingsProvider; + private readonly MusicBrainzRequestThrottle _requestThrottle; + private readonly MusicBrainzResponseCache _responseCache; + + private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web) + { + NumberHandling = JsonNumberHandling.AllowReadingFromString + }; + + // Transient failures and rate limiting are retried with an exponential backoff, so a single hiccup does not mark an item as failed to enrich. + private const int MAXIMUM_ATTEMPT_COUNT = 4; + + /// + /// Initializes a new instance of the class. + /// + /// The used to send requests to the MusicBrainz web service. + /// The provider of the settings that configure the MusicBrainz web service requests. + /// The process-wide throttle that spaces out the requests sent to the MusicBrainz web service. + /// The process-wide cache that avoids fetching the same entity more than once during a run. + public MusicBrainzHttpClient(HttpClient httpClient, MusicBrainzSettingsProvider settingsProvider, MusicBrainzRequestThrottle requestThrottle, MusicBrainzResponseCache responseCache) + { + _httpClient = httpClient; + _settingsProvider = settingsProvider; + _requestThrottle = requestThrottle; + _responseCache = responseCache; + } + + /// + /// Looks up the artist identified by . + /// + /// The MusicBrainz identifier of the artist. + /// Cancellation token that can be used to stop the execution. + /// The artist, or when no artist was found. + public Task GetArtistAsync(Guid musicBrainzArtistId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync( + $"artist/{musicBrainzArtistId:D}?inc=aliases+tags+genres+url-rels+artist-rels+ratings&fmt=json", cancellationToken); + } + + /// + /// Searches MusicBrainz for artists matching the provided query. + /// + /// The search query. + /// The maximum number of results to return. + /// Cancellation token that can be used to stop the execution. + /// The list of matching artists. + public async Task> SearchArtistsAsync(string query, int limit, CancellationToken cancellationToken) + { + MusicBrainzArtistSearchResponse? response = await GetJsonOrNullAsync( + $"artist?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json", + cancellationToken).ConfigureAwait(false); + return response?.Artists ?? []; + } + + /// + /// Looks up the release group identified by . + /// + /// The MusicBrainz identifier of the release group. + /// Cancellation token that can be used to stop the execution. + /// The release group, or when no release group was found. + public Task GetReleaseGroupAsync(Guid musicBrainzReleaseGroupId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync( + $"release-group/{musicBrainzReleaseGroupId:D}?inc=artist-credits+tags+genres+ratings&fmt=json", cancellationToken); + } + + /// + /// Searches MusicBrainz for release groups matching the provided query. + /// + /// The search query. + /// The maximum number of results to return. + /// Cancellation token that can be used to stop the execution. + /// The list of matching release groups. + public async Task> SearchReleaseGroupsAsync(string query, int limit, CancellationToken cancellationToken) + { + MusicBrainzReleaseGroupSearchResponse? response = await GetJsonOrNullAsync( + $"release-group?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json", + cancellationToken).ConfigureAwait(false); + return response?.ReleaseGroups ?? []; + } + + /// + /// Looks up the release identified by . + /// + /// The MusicBrainz identifier of the release. + /// Cancellation token that can be used to stop the execution. + /// The release, or when no release was found. + public Task GetReleaseAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync( + $"release/{musicBrainzReleaseId:D}?inc=artist-credits+labels+release-groups+media+tags+genres+artist-rels&fmt=json", cancellationToken); + } + + /// + /// Browses the releases that belong to the release group identified by . + /// + /// The MusicBrainz identifier of the release group. + /// The maximum number of releases to return. + /// Cancellation token that can be used to stop the execution. + /// The list of releases of the release group. + public async Task> BrowseReleasesByReleaseGroupAsync(Guid musicBrainzReleaseGroupId, int limit, CancellationToken cancellationToken) + { + MusicBrainzReleaseBrowseResponse? response = await GetJsonOrNullAsync( + $"release?release-group={musicBrainzReleaseGroupId:D}&inc=artist-credits+labels+media&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json", + cancellationToken).ConfigureAwait(false); + return response?.Releases ?? []; + } + + /// + /// Looks up the recording identified by . + /// + /// The MusicBrainz identifier of the recording. + /// Cancellation token that can be used to stop the execution. + /// The recording, or when no recording was found. + public Task GetRecordingAsync(Guid musicBrainzRecordingId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync( + $"recording/{musicBrainzRecordingId:D}?inc=artist-credits+isrcs+releases+tags+genres+work-rels+artist-rels+ratings&fmt=json", cancellationToken); + } + + /// + /// Searches MusicBrainz for recordings matching the provided query. + /// + /// The search query. + /// The maximum number of results to return. + /// Cancellation token that can be used to stop the execution. + /// The list of matching recordings. + public async Task> SearchRecordingsAsync(string query, int limit, CancellationToken cancellationToken) + { + MusicBrainzRecordingSearchResponse? response = await GetJsonOrNullAsync( + $"recording?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json", + cancellationToken).ConfigureAwait(false); + return response?.Recordings ?? []; + } + + /// + /// Looks up the recordings that carry the provided ISRC. + /// + /// The ISRC to look up. + /// Cancellation token that can be used to stop the execution. + /// The list of recordings that carry the ISRC. + public async Task> GetRecordingsByIsrcAsync(string isrc, CancellationToken cancellationToken) + { + MusicBrainzRecordingListResponse? response = await GetJsonOrNullAsync( + $"isrc/{Uri.EscapeDataString(isrc)}?inc=artist-credits+isrcs+work-rels+artist-rels&fmt=json", cancellationToken).ConfigureAwait(false); + return response?.Recordings ?? []; + } + + /// + /// Looks up the work identified by , together with its credited contributors. + /// + /// The MusicBrainz identifier of the work. + /// Cancellation token that can be used to stop the execution. + /// The work, or when no work was found. + public Task GetWorkAsync(Guid musicBrainzWorkId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync( + $"work/{musicBrainzWorkId:D}?inc=artist-rels+tags+genres&fmt=json", cancellationToken); + } + + /// + /// Looks up the release identified by , together with its media, tracks, recordings and all the data needed + /// to enrich those tracks, so that every track of the release is enriched from a single request. + /// + /// The MusicBrainz identifier of the release. + /// Cancellation token that can be used to stop the execution. + /// The release, with its media, tracks and recordings, or when no release was found. + public Task GetReleaseWithRecordingsAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken) + { + return GetJsonOrNullAsync( + $"release/{musicBrainzReleaseId:D}?inc=recordings+isrcs+artist-credits+tags+genres+ratings+work-rels+recording-level-rels+work-level-rels+artist-rels+release-groups+labels+media&fmt=json", cancellationToken); + } + + /// + /// Gets the JSON resource at the given relative URL and deserializes it into . + /// + /// The type to deserialize the JSON response into. + /// The URL of the resource, relative to the base address. + /// Cancellation token that can be used to stop the execution. + /// The deserialized resource, or when the resource was not found. + /// Transient failures and rate limiting are handled by retrying the request up to three times. + private async Task GetJsonOrNullAsync(string relativeUrl, CancellationToken cancellationToken) + { + MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + string cacheKey = string.Concat(settings.BaseUrl, relativeUrl); + if (_responseCache.TryGet(cacheKey, out string? cachedJson) && cachedJson is not null) + return JsonSerializer.Deserialize(cachedJson, s_serializerOptions); + + using HttpResponseMessage response = await SendAsync(settings, relativeUrl, cancellationToken).ConfigureAwait(false); + // A 404 means the entity does not exist in MusicBrainz, which is a normal miss rather than an error, so it is reported as no result. + if (response.StatusCode == HttpStatusCode.NotFound) + return default; + response.EnsureSuccessStatusCode(); + + string json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + _responseCache.Set(cacheKey, json); + return JsonSerializer.Deserialize(json, s_serializerOptions); + } + + /// + /// Sends a GET request to the MusicBrainz web service, throttled to respect the configured minimum request interval unless the configured + /// base URL is not the real MusicBrainz service, in which case no rate limit is imposed. Transient failures, rate limiting and transport + /// exceptions are retried, preferring the delay requested by the web service when it is provided. + /// + /// The settings that configure the MusicBrainz web service requests. + /// The URL of the resource, relative to the base address. + /// Cancellation token that can be used to stop the execution. + /// The HTTP response message for the request. + private async Task SendAsync(MusicBrainzSettingsDto settings, string relativeUrl, CancellationToken cancellationToken) + { + EnsureRequestHeaders(settings); + // The rate limit is enforced by the MusicBrainz web service itself, so it is only observed when the requests actually reach it; a self hosted + // mirror, or any other configured base URL that is not the real service, is not limited by this process. + bool shouldThrottle = IsRealMusicBrainzService(settings.BaseUrl); + + // A fresh request is created for every attempt, because an HTTP request cannot be sent more than once, and the throttle is applied to every + // attempt, so that the retries of a failed request cannot burst past the rate limit of the real MusicBrainz web service. + for (int attempt = 1; ; attempt++) + { + if (shouldThrottle) + await _requestThrottle.WaitAsync(settings.MinimumRequestInterval, cancellationToken).ConfigureAwait(false); + + bool isLastAttempt = attempt >= MAXIMUM_ATTEMPT_COUNT; + HttpResponseMessage response; + try + { + HttpRequestMessage request = new(HttpMethod.Get, BuildRequestUri(settings.BaseUrl, relativeUrl)); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); + } + catch (HttpRequestException) when (!isLastAttempt) + { + await Task.Delay(GetRetryDelay(attempt, null), cancellationToken).ConfigureAwait(false); + continue; + } + + if (!isLastAttempt && (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500)) + { + TimeSpan retryDelay = GetRetryDelay(attempt, response); + // The response of a failed attempt is not returned, so it must be disposed here to release its connection. + response.Dispose(); + await Task.Delay(retryDelay, cancellationToken).ConfigureAwait(false); + continue; + } + + return response; + } + } + + /// + /// Gets the delay to wait before the next attempt, preferring the delay requested by the MusicBrainz web service when it is provided. + /// + /// The one based number of the attempt that just failed. + /// The response of the failed attempt, when the failure was a response rather than a transport exception. + /// The delay to wait before the next attempt. + private static TimeSpan GetRetryDelay(int attempt, HttpResponseMessage? response) + { + if (response?.Headers.RetryAfter is { } retryAfter) + { + if (retryAfter.Delta is TimeSpan delta) + return delta; + if (retryAfter.Date is DateTimeOffset date) + { + TimeSpan wait = date - DateTimeOffset.UtcNow; + if (wait > TimeSpan.Zero) + return wait; + } + } + return TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt)); + } + + /// + /// Determines whether the provided base URL points to the real MusicBrainz web service, which is the only one whose rate limit is observed. + /// + /// The base URL of the MusicBrainz web service the requests are sent to. + /// when the base URL points to the real MusicBrainz web service, otherwise . + private static bool IsRealMusicBrainzService(string baseUrl) + { + if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out Uri? baseUri)) + return false; + return baseUri.Host.Equals("musicbrainz.org", StringComparison.OrdinalIgnoreCase) + || baseUri.Host.EndsWith(".musicbrainz.org", StringComparison.OrdinalIgnoreCase); + } + + /// + /// Applies the request headers configured in the onto the underlying HTTP client, unless they are already set. + /// + /// The settings that configure the MusicBrainz web service requests. + private void EnsureRequestHeaders(MusicBrainzSettingsDto settings) + { + // The headers live on the underlying HttpClient, which is reused across the calls of this client, so they are applied only once. + if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0) + { + string userAgent = string.IsNullOrWhiteSpace(settings.ContactEmail) + ? settings.UserAgent + : $"{settings.UserAgent} ( {settings.ContactEmail} )"; + _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent); + } + } + + /// + /// Combines the configured base URL with the given relative URL into the absolute URI of a request. + /// + /// The base URL of the MusicBrainz web service the requests are sent to. + /// The URL of the resource, relative to the base URL. + /// The absolute URI of the request. + private static Uri BuildRequestUri(string baseUrl, string relativeUrl) + { + string normalizedBaseUrl = baseUrl.EndsWith('/') ? baseUrl : string.Concat(baseUrl, "/"); + return new Uri(new Uri(normalizedBaseUrl, UriKind.Absolute), relativeUrl); + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzRequestThrottle.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzRequestThrottle.cs new file mode 100644 index 00000000..43801c05 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzRequestThrottle.cs @@ -0,0 +1,49 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core.Api; + +/// +/// Spaces out the requests sent to the MusicBrainz web service, so the configured minimum request interval is respected across every caller in the process. +/// +internal sealed class MusicBrainzRequestThrottle +{ + private readonly SemaphoreSlim _gate = new(1, 1); + + // The timestamp of the last reserved request slot, shared process wide, so the configured interval is enforced between requests no matter + // which caller sends them. + private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue; + + /// + /// Waits until the minimum interval elapsed since the previous reserved request, then reserves the next request slot. + /// + /// The minimum amount of time that must elapse between two consecutive requests. + /// Cancellation token that can be used to stop the execution. + /// A task that completes once the caller may send its request. + public async Task WaitAsync(TimeSpan minimumRequestInterval, CancellationToken cancellationToken) + { + // The gate is held across the delay, so concurrent callers queue up and each one is released only once the interval elapsed since the + // previous reserved slot. + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + // A non positive interval means the callers are not spaced out at all, and it must not be added to the initial timestamp, which would underflow it. + if (minimumRequestInterval > TimeSpan.Zero) + { + DateTimeOffset earliestNextRequest = _lastRequestAt + minimumRequestInterval; + TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow; + if (delay > TimeSpan.Zero) + await Task.Delay(delay, cancellationToken).ConfigureAwait(false); + } + + _lastRequestAt = DateTimeOffset.UtcNow; + } + finally + { + _gate.Release(); + } + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzResponseCache.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzResponseCache.cs new file mode 100644 index 00000000..06b87f9c --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzResponseCache.cs @@ -0,0 +1,140 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core.Api; + +/// +/// In-memory cache of the responses returned by the MusicBrainz web service, keyed by the requested URL. +/// It removes the repeated lookups of the same entity during a run, and expires its entries after a bounded time. +/// +internal sealed class MusicBrainzResponseCache +{ + /// + /// The maximum number of responses the cache keeps. + /// + internal const int MAXIMUM_ENTRY_COUNT = 20_000; + + /// + /// The maximum total number of characters of the cached response bodies. + /// + internal const long MAXIMUM_CHARACTER_COUNT = 100_000_000; + + /// + /// The percentage of a budget that the cache is trimmed down to when it exceeds that budget. Trimming to a lower water mark keeps the + /// eviction from running on every write once a budget is reached. + /// + private const int TRIM_TARGET_PERCENT = 90; + + private static readonly TimeSpan s_timeToLive = TimeSpan.FromMinutes(15); + + private readonly int _maximumEntryCount; + private readonly long _maximumCharacterCount; + private readonly TimeSpan _timeToLive; + private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal); + + // The dictionary is thread safe on its own, but the character budget is a read modify write over it, so the size bookkeeping and the eviction + // are guarded by a lock, while reads stay lock free. + private readonly Lock _sizeGate = new(); + private long _cachedCharacterCount; + + // Monotonically increasing insertion stamp, used to evict the oldest entries first. + private long _sequence; + + /// + /// Initializes a new instance of the class with the default budgets and time to live. + /// + public MusicBrainzResponseCache() + { + _maximumEntryCount = MAXIMUM_ENTRY_COUNT; + _maximumCharacterCount = MAXIMUM_CHARACTER_COUNT; + _timeToLive = s_timeToLive; + } + + /// + /// Initializes a new instance of the class with the provided budgets and time to live. + /// + /// The maximum number of responses the cache keeps. + /// The maximum total number of characters of the cached response bodies. + /// The amount of time a cached response stays valid. + internal MusicBrainzResponseCache(int maximumEntryCount, long maximumCharacterCount, TimeSpan timeToLive) + { + _maximumEntryCount = maximumEntryCount; + _maximumCharacterCount = maximumCharacterCount; + _timeToLive = timeToLive; + } + + /// + /// Tries to get the cached response body for . + /// + /// The key of the cached response. + /// The cached response body, when found. + /// when an unexpired response was found, otherwise . + public bool TryGet(string key, out string? json) + { + // An expired entry is treated as a miss instead of being removed here, so readers never take the lock; a later write reclaims it. + if (_entries.TryGetValue(key, out CacheEntry? entry) && entry.ExpiresOnUtc > DateTime.UtcNow) + { + json = entry.Json; + return true; + } + json = null; + return false; + } + + /// + /// Adds or replaces the cached response body for , then trims the cache back to its budgets. + /// + /// The key of the cached response. + /// The response body to cache. + public void Set(string key, string json) + { + // A single response larger than the whole character budget can never be admitted, so it is rejected before it disturbs the cache. + if (json.Length > _maximumCharacterCount) + return; + + lock (_sizeGate) + { + if (_entries.TryRemove(key, out CacheEntry? existing)) + _cachedCharacterCount -= existing.Json.Length; + + _entries[key] = new CacheEntry(json, DateTime.UtcNow.Add(_timeToLive), ++_sequence); + _cachedCharacterCount += json.Length; + + if (_entries.Count > _maximumEntryCount || _cachedCharacterCount > _maximumCharacterCount) + TrimToBudget(); + } + } + + /// + /// Removes the expired entries, and then the oldest unexpired entries, until the cache is back within its entry count and character budgets. + /// + private void TrimToBudget() + { + DateTime utcNow = DateTime.UtcNow; + bool isOverEntryCount = _entries.Count > _maximumEntryCount; + bool isOverCharacterCount = _cachedCharacterCount > _maximumCharacterCount; + int entryTarget = Math.Max(1, _maximumEntryCount * TRIM_TARGET_PERCENT / 100); + long characterTarget = Math.Max(1, _maximumCharacterCount * TRIM_TARGET_PERCENT / 100); + + // Entries are evicted in insertion order, so the most recently cached responses survive; an expired entry is always removed, even when + // a budget was not exceeded, so the cache keeps reclaiming dead entries. + foreach (KeyValuePair candidate in _entries.OrderBy(entry => entry.Value.Sequence)) + { + bool isExpired = candidate.Value.ExpiresOnUtc <= utcNow; + bool needsEntryTrim = isOverEntryCount && _entries.Count > entryTarget; + bool needsCharacterTrim = isOverCharacterCount && _cachedCharacterCount > characterTarget; + if (!isExpired && !needsEntryTrim && !needsCharacterTrim) + break; + + if (_entries.TryRemove(candidate.Key, out CacheEntry? removed)) + _cachedCharacterCount -= removed.Json.Length; + } + } + + private sealed record CacheEntry(string Json, DateTime ExpiresOnUtc, long Sequence); +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs new file mode 100644 index 00000000..5b6a363a --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs @@ -0,0 +1,759 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Text.RegularExpressions; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core.Mapping; + +/// +/// Maps MusicBrainz web service responses into the application's media metadata DTOs. +/// +internal static partial class MusicBrainzMapper +{ + /// + /// The neutral cultures of the process, indexed by both their two letter and three letter ISO 639 codes. + /// Built once, because the available cultures do not change during the lifetime of the process. + /// + private static readonly IReadOnlyDictionary s_neutralCulturesByCode = BuildNeutralCultureLookup(); + + /// + /// Matches a four digit year. + /// + [GeneratedRegex(@"\b(?:1[0-9]{3}|20[0-9]{2}|2100)\b")] + private static partial Regex YearPattern(); + + /// + /// Maps a MusicBrainz artist response into artist metadata. + /// + /// The artist response to map. + /// The mapped artist metadata. + public static ArtistMetadataDto MapArtist(MusicBrainzArtistResponse artist) + { + (List contributors, string? website) = MapArtistRelations(artist.Relations); + return new ArtistMetadataDto( + Name: NullIfWhiteSpace(artist.Name), + SortName: NullIfWhiteSpace(artist.SortName), + Disambiguation: NullIfWhiteSpace(artist.Disambiguation), + Type: MapArtistType(artist.Type), + Gender: MapArtistGender(artist.Gender), + Country: NullIfWhiteSpace(artist.Country), + Area: MapArea(artist.Area), + BeginArea: MapArea(artist.BeginArea), + EndArea: MapArea(artist.EndArea), + LifeSpanBegin: ParseDate(artist.LifeSpan?.Begin).Date, + LifeSpanEnd: ParseDate(artist.LifeSpan?.End).Date, + IsEnded: artist.LifeSpan?.IsEnded ?? false, + Website: website, + MusicBrainzArtistId: ParseGuid(artist.Id), + Ipis: [.. artist.Ipis.Where(ipi => !string.IsNullOrWhiteSpace(ipi))], + Isnis: [.. artist.Isnis.Where(isni => !string.IsNullOrWhiteSpace(isni))], + Aliases: [.. artist.Aliases.Select(MapAlias)], + Genres: MapGenres(artist.Genres), + Tags: MapTags(artist.Tags), + Ratings: MapRating(artist.Rating), + Contributors: contributors); + } + + /// + /// Maps a MusicBrainz release group, and optionally one of its releases, into album metadata. + /// + /// The release group response to map. + /// The selected release of the release group, or when no release was selected. + /// The mapped album metadata. + public static AlbumMetadataDto MapAlbum(MusicBrainzReleaseGroupResponse releaseGroup, MusicBrainzReleaseResponse? release) + { + (DateOnly? originalDate, int? originalYear) = ParseDate(releaseGroup.FirstReleaseDate); + (DateOnly? reReleaseDate, int? reReleaseYear) = ParseDate(release?.Date); + if (reReleaseDate is not null && originalDate is not null && reReleaseDate.Value.Year == originalDate.Value.Year) + { + reReleaseDate = null; + reReleaseYear = null; + } + + string? releaseArtistId = releaseGroup.ArtistCredit.Select(credit => credit.Artist?.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id)) + ?? release?.ArtistCredit.Select(credit => credit.Artist?.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id)); + + List contributors = MapArtistCredit(releaseGroup.ArtistCredit); + if (contributors.Count == 0 && release is not null) + contributors = MapArtistCredit(release.ArtistCredit); + if (release is not null) + AddContributors(contributors, MapContributorsFromRelations(release.Relations)); + + List media = release?.Media ?? []; + int totalTracks = media.Sum(medium => medium.TrackCount); + // A MusicBrainz release can carry several labels and catalog numbers: the label stores the first one, while every catalog number is kept. + string? label = release?.LabelInfo.FirstOrDefault()?.Label?.Name; + List catalogNumbers = [.. (release?.LabelInfo ?? []) + .Select(labelInfo => NullIfWhiteSpace(labelInfo.CatalogNumber)) + .Where(catalogNumber => catalogNumber is not null) + .Select(catalogNumber => catalogNumber!) + .Distinct(StringComparer.OrdinalIgnoreCase)]; + + return new AlbumMetadataDto( + Title: NullIfWhiteSpace(releaseGroup.Title) ?? NullIfWhiteSpace(release?.Title), + OriginalTitle: null, + Description: null, + Disambiguation: NullIfWhiteSpace(releaseGroup.Disambiguation), + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: originalDate, + OriginalReleaseYear: originalYear, + ReReleaseDate: reReleaseDate, + ReReleaseYear: reReleaseYear, + ReleaseCountry: MapReleaseCountry(release?.Country), + ReleaseVersion: NullIfWhiteSpace(release?.Disambiguation)), + Language: MapLanguage(release?.TextRepresentation?.Language), + OriginalLanguage: null, + Tags: MapTags(releaseGroup.Tags), + Genres: MapGenres(releaseGroup.Genres), + Script: NullIfWhiteSpace(release?.TextRepresentation?.Script), + ReleaseTypes: MapReleaseTypes(releaseGroup.PrimaryType, releaseGroup.SecondaryTypes), + ReleaseStatus: MapReleaseStatus(release?.Status), + MediaFormat: MapMediaFormat(media.FirstOrDefault()?.Format), + Packaging: MapPackaging(release?.Packaging), + TotalDiscs: media.Count > 0 ? media.Count : null, + TotalTracks: totalTracks > 0 ? totalTracks : null, + Barcode: NullIfWhiteSpace(release?.Barcode), + CatalogNumbers: catalogNumbers, + Label: NullIfWhiteSpace(label), + ASIN: NullIfWhiteSpace(release?.Asin), + MusicBrainzReleaseId: ParseGuid(release?.Id), + MusicBrainzReleaseGroupId: ParseGuid(releaseGroup.Id), + MusicBrainzReleaseArtistId: ParseGuid(releaseArtistId), + Contributors: contributors, + Ratings: MapRating(releaseGroup.Rating), + ReleaseTitle: NullIfWhiteSpace(release?.Title)); + } + + /// + /// Maps a MusicBrainz recording, and optionally its work and release, into track metadata. + /// + /// The recording response to map. + /// The work the recording is an instance of, or when the recording has no work. + /// The release the recording appears on, or when it is not known. + /// The mapped track metadata. + public static AudioMetadataDto MapTrack(MusicBrainzRecordingResponse recording, MusicBrainzWorkResponse? work, MusicBrainzReleaseResponse? release) + { + (DateOnly? releaseDate, int? releaseYear) = ParseDate(recording.FirstReleaseDate); + // A recording embedded in a release lookup does not carry its own first release date, so the date of the release the track appears on is used + // instead, rather than leaving the track without any release date at all. + if (releaseYear is null) + (releaseDate, releaseYear) = ParseDate(release?.Date); + + List contributors = MapArtistCredit(recording.ArtistCredit); + AddContributors(contributors, MapContributorsFromRelations(recording.Relations)); + if (work is not null) + AddContributors(contributors, MapContributorsFromRelations(work.Relations)); + + return new AudioMetadataDto( + Title: NullIfWhiteSpace(recording.Title), + OriginalTitle: null, + Description: null, + Disambiguation: NullIfWhiteSpace(recording.Disambiguation), + ReleaseInfo: new ReleaseInfoDto( + OriginalReleaseDate: releaseDate, + OriginalReleaseYear: releaseYear, + ReReleaseDate: null, + ReReleaseYear: null, + ReleaseCountry: null, + ReleaseVersion: null), + Language: MapLanguage(release?.TextRepresentation?.Language), + OriginalLanguage: null, + Tags: MapTags(recording.Tags), + Genres: MapGenres(recording.Genres), + Script: NullIfWhiteSpace(release?.TextRepresentation?.Script), + Key: null, + Bpm: null, + IsVideo: recording.IsVideo ?? false, + Work: work is null ? null : MapWork(work), + Isrcs: [.. recording.Isrcs.Where(isrc => !string.IsNullOrWhiteSpace(isrc)).Select(isrc => new IsrcDto(isrc))], + Moods: null, + DurationInSeconds: recording.Length is long length && length > 0 ? (int)(length / 1000) : null, + SampleRate: null, + Channels: null, + BitDepth: null, + AudioCodec: null, + Bitrate: null, + MusicBrainzRecordingId: ParseGuid(recording.Id), + MusicBrainzTrackId: null, + Contributors: contributors, + Ratings: MapRating(recording.Rating)); + } + + /// + /// Maps a MusicBrainz work into a work DTO. + /// + /// The work response to map. + /// The mapped work. + public static MusicWorkDto MapWork(MusicBrainzWorkResponse work) + { + return new MusicWorkDto( + MusicBrainzWorkId: ParseGuid(work.Id), + Title: NullIfWhiteSpace(work.Title), + Type: NullIfWhiteSpace(work.Type), + Languages: [.. work.Languages.Select(MapLanguage).Where(language => language is not null).Select(language => language!)], + Iswcs: [.. work.Iswcs.Where(iswc => !string.IsNullOrWhiteSpace(iswc))]); + } + + /// + /// Maps a MusicBrainz area into an area DTO. + /// + /// The area response to map. + /// The mapped area, or when no area is provided. + public static MusicAreaDto? MapArea(MusicBrainzAreaResponse? area) + { + if (area is null) + return null; + + string? isoCode = area.Iso3166Part1Codes.FirstOrDefault() ?? area.Iso3166Part2Codes.FirstOrDefault(); + return new MusicAreaDto( + MusicBrainzAreaId: ParseGuid(area.Id), + Name: NullIfWhiteSpace(area.Name), + SortName: NullIfWhiteSpace(area.SortName), + Disambiguation: NullIfWhiteSpace(area.Disambiguation), + Type: NullIfWhiteSpace(area.Type), + Iso3166Code: NullIfWhiteSpace(isoCode)); + } + + /// + /// Maps a MusicBrainz alias into an alias DTO. + /// + /// The alias response to map. + /// The mapped alias. + private static MusicArtistAliasDto MapAlias(MusicBrainzAliasResponse alias) + { + return new MusicArtistAliasDto( + Name: NullIfWhiteSpace(alias.Name), + SortName: NullIfWhiteSpace(alias.SortName), + Type: NullIfWhiteSpace(alias.Type), + Locale: NullIfWhiteSpace(alias.Locale), + IsPrimary: alias.IsPrimary ?? false, + BeginDate: ParseDate(alias.Begin).Date, + EndDate: ParseDate(alias.End).Date, + IsEnded: alias.IsEnded ?? false); + } + + /// + /// Maps the genres of a MusicBrainz entity into genre DTOs. + /// + /// The genre responses to map. + /// The mapped genre DTOs. + private static List MapGenres(IReadOnlyCollection genres) + { + return [.. genres + .Where(genre => !string.IsNullOrWhiteSpace(genre.Name)) + .Select(genre => new GenreDto(genre.Name)) + .DistinctBy(genre => genre.Name, StringComparer.OrdinalIgnoreCase)]; + } + + /// + /// Maps the tags of a MusicBrainz entity into tag DTOs. + /// + /// The tag responses to map. + /// The mapped tag DTOs. + private static List MapTags(IReadOnlyCollection tags) + { + return [.. tags + .Where(tag => !string.IsNullOrWhiteSpace(tag.Name)) + .Select(tag => new TagDto(tag.Name)) + .DistinctBy(tag => tag.Name, StringComparer.OrdinalIgnoreCase)]; + } + + /// + /// Maps the rating of a MusicBrainz entity into a rating DTO. + /// + /// The rating response to map. + /// The mapped rating DTO, or an empty list when no rating is provided. + private static List MapRating(MusicBrainzRatingResponse? rating) + { + if (rating is null || (rating.Value is null && rating.VotesCount is null)) + return []; + return [new AudioRatingDto(rating.Value, 5m, AudioRatingSource.MusicBrainz, rating.VotesCount)]; + } + + /// + /// Maps an ISO 639-3 language code into a language DTO. + /// + /// The code to map. + /// The mapped language, or when the code is empty. + private static LanguageInfoDto? MapLanguage(string? rawCode) + { + if (string.IsNullOrWhiteSpace(rawCode)) + return null; + + string code = rawCode.Trim().ToLowerInvariant(); + // A language code can list several languages, such as "eng/ara"; the first one is the language of the release. + string primaryCode = code.Split('/').Select(part => part.Trim()).FirstOrDefault(part => part.Length > 0) ?? code; + + // These ISO 639-3 codes describe a language absence rather than a culture, so they cannot be resolved through a culture. + switch (primaryCode) + { + case "zxx": + return new LanguageInfoDto(primaryCode, "No linguistic content", null); + case "mul": + return new LanguageInfoDto(primaryCode, "Multiple languages", null); + case "und": + return new LanguageInfoDto(primaryCode, "Undetermined", null); + default: + break; + } + + // Only neutral cultures are matched, because a specific culture would resolve to an arbitrary regional name such as "German (Austria)". + return s_neutralCulturesByCode.TryGetValue(primaryCode, out CultureInfo? culture) + ? new LanguageInfoDto(culture.TwoLetterISOLanguageName, culture.EnglishName, culture.NativeName) + : new LanguageInfoDto(primaryCode, primaryCode, null); + } + + /// + /// Builds the lookup of the process' neutral cultures, indexed by both their two letter and three letter ISO 639 codes. + /// + /// The neutral cultures, indexed by their ISO 639 codes. + private static IReadOnlyDictionary BuildNeutralCultureLookup() + { + Dictionary culturesByCode = new(StringComparer.OrdinalIgnoreCase); + foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.NeutralCultures)) + { + // A culture without a two letter ISO 639 code is not a language, so it is skipped; the two letter code is the one carried by the DTOs. + if (culture.TwoLetterISOLanguageName.Length != 2) + continue; + culturesByCode.TryAdd(culture.ThreeLetterISOLanguageName, culture); + culturesByCode.TryAdd(culture.TwoLetterISOLanguageName, culture); + } + return culturesByCode; + } + + /// + /// Maps the artist credit of a MusicBrainz entity into attributed performing contributors. + /// + /// The artist credit to map. + /// The mapped contributors. + private static List MapArtistCredit(IReadOnlyCollection artistCredit) + { + List contributors = []; + foreach (MusicBrainzArtistCreditResponse credit in artistCredit) + { + string? name = NullIfWhiteSpace(credit.Name) ?? NullIfWhiteSpace(credit.Artist?.Name); + if (name is null) + continue; + AddContributor(contributors, name, MediaContributorRole.Performer); + } + return contributors; + } + + /// + /// Maps the artist relations of a MusicBrainz entity into contributors, excluding the URL relations. + /// + /// The relations to map. + /// The mapped contributors. + private static List MapContributorsFromRelations(IReadOnlyCollection relations) + { + List contributors = []; + foreach (MusicBrainzRelationResponse relation in relations) + { + if (!string.Equals(relation.TargetType, "artist", StringComparison.OrdinalIgnoreCase)) + continue; + + string? name = NullIfWhiteSpace(relation.Artist?.Name); + if (name is null) + continue; + AddContributor(contributors, name, MapRole(relation.Type, relation.Attributes)); + } + return contributors; + } + + /// + /// Maps the relations of an artist into its contributing members, and its official homepage. + /// + /// The relations of the artist. + /// The mapped contributors, and the official homepage of the artist. + private static (List Contributors, string? Website) MapArtistRelations(IReadOnlyCollection relations) + { + List contributors = []; + string? website = null; + foreach (MusicBrainzRelationResponse relation in relations) + { + if (string.Equals(relation.TargetType, "url", StringComparison.OrdinalIgnoreCase)) + { + if (website is null && string.Equals(relation.Type, "official homepage", StringComparison.OrdinalIgnoreCase)) + website = NullIfWhiteSpace(relation.Url?.Resource); + continue; + } + + if (!string.Equals(relation.TargetType, "artist", StringComparison.OrdinalIgnoreCase)) + continue; + + string? name = NullIfWhiteSpace(relation.Artist?.Name); + if (name is null) + continue; + AddContributor(contributors, name, MapRole(relation.Type, relation.Attributes)); + } + return (contributors, website); + } + + /// + /// Adds a contributor to the provided list, unless an identical name and role pair is already present. + /// + /// The contributors collected so far. + /// The display name of the contributor. + /// The role the contributor played. + private static void AddContributor(List contributors, string displayName, MediaContributorRole role) + { + if (contributors.Any(contributor => + string.Equals(contributor.Name?.DisplayName, displayName, StringComparison.OrdinalIgnoreCase) && + contributor.Role == role)) + return; + contributors.Add(new MediaContributorDto(new MediaContributorNameDto(displayName, null), role)); + } + + /// + /// Adds the contributors to , skipping the duplicate name and role pairs. + /// + /// The contributors collected so far. + /// The contributors to add. + private static void AddContributors(List contributors, IReadOnlyCollection incoming) + { + foreach (MediaContributorDto contributor in incoming) + { + if (contributor.Name?.DisplayName is not string displayName) + continue; + AddContributor(contributors, displayName, contributor.Role ?? MediaContributorRole.Other); + } + } + + /// + /// Maps a MusicBrainz relationship type, and its attributes, into a canonical media contributor role. + /// + /// The relationship type to map. + /// The attributes of the relationship. + /// The mapped contributor role. + private static MediaContributorRole MapRole(string? relationType, IReadOnlyCollection attributes) + { + // An instrument attribute is more specific than the generic relationship type, so it is preferred. + foreach (string attribute in attributes) + { + MediaContributorRole? attributed = MapInstrument(attribute); + if (attributed is not null) + return attributed.Value; + } + + if (string.IsNullOrWhiteSpace(relationType)) + return MediaContributorRole.Other; + + string type = relationType.Trim().ToLowerInvariant(); + if (type.Contains("executive producer", StringComparison.Ordinal)) + return MediaContributorRole.ExecutiveProducer; + if (type.Contains("producer", StringComparison.Ordinal)) + return MediaContributorRole.Producer; + if (type.Contains("remixer", StringComparison.Ordinal)) + return MediaContributorRole.Remixer; + if (type.Contains("mix", StringComparison.Ordinal)) + return MediaContributorRole.Mixer; + if (type.Contains("engineer", StringComparison.Ordinal) || type.Contains("mastering", StringComparison.Ordinal)) + return MediaContributorRole.Engineer; + if (type.Contains("composer", StringComparison.Ordinal)) + return MediaContributorRole.Composer; + if (type.Contains("writer", StringComparison.Ordinal)) + return MediaContributorRole.Author; + if (type.Contains("lyricist", StringComparison.Ordinal)) + return MediaContributorRole.Lyricist; + if (type.Contains("librettist", StringComparison.Ordinal)) + return MediaContributorRole.Lyricist; + if (type.Contains("arranger", StringComparison.Ordinal)) + return MediaContributorRole.Arranger; + if (type.Contains("conductor", StringComparison.Ordinal)) + return MediaContributorRole.Conductor; + if (type.Contains("orchestrator", StringComparison.Ordinal)) + return MediaContributorRole.Orchestrator; + if (type.Contains("backing vocals", StringComparison.Ordinal)) + return MediaContributorRole.BackingVocals; + if (type.Contains("vocal", StringComparison.Ordinal)) + return MediaContributorRole.Vocals; + if (type.Contains("member of band", StringComparison.Ordinal) || type.Contains("performer", StringComparison.Ordinal) || type.Contains("orchestra", StringComparison.Ordinal) || type.Contains("choir", StringComparison.Ordinal)) + return MediaContributorRole.Performer; + return MediaContributorRole.Other; + } + + /// + /// Maps a MusicBrainz instrument attribute into a canonical media contributor role. + /// + /// The instrument attribute to map. + /// The mapped contributor role, or when the attribute is not an instrument. + private static MediaContributorRole? MapInstrument(string? attribute) + { + if (string.IsNullOrWhiteSpace(attribute)) + return null; + + string value = attribute.Trim().ToLowerInvariant(); + if (value.Contains("backing vocal", StringComparison.Ordinal)) + return MediaContributorRole.BackingVocals; + if (value.Contains("vocal", StringComparison.Ordinal)) + return MediaContributorRole.Vocals; + if (value.Contains("bass guitar", StringComparison.Ordinal)) + return MediaContributorRole.BassGuitar; + if (value.Contains("guitar", StringComparison.Ordinal)) + return MediaContributorRole.Guitar; + if (value.Contains("drum", StringComparison.Ordinal)) + return MediaContributorRole.Drums; + if (value.Contains("percussion", StringComparison.Ordinal)) + return MediaContributorRole.Percussion; + if (value.Contains("keyboard", StringComparison.Ordinal)) + return MediaContributorRole.Keyboards; + if (value.Contains("piano", StringComparison.Ordinal)) + return MediaContributorRole.Piano; + if (value.Contains("synthesizer", StringComparison.Ordinal) || value.Contains("synth", StringComparison.Ordinal)) + return MediaContributorRole.Synthesizer; + if (value.Contains("string", StringComparison.Ordinal) || value.Contains("violin", StringComparison.Ordinal) || value.Contains("cello", StringComparison.Ordinal) || value.Contains("viola", StringComparison.Ordinal)) + return MediaContributorRole.Strings; + if (value.Contains("brass", StringComparison.Ordinal) || value.Contains("trumpet", StringComparison.Ordinal) || value.Contains("trombone", StringComparison.Ordinal) || value.Contains("horn", StringComparison.Ordinal)) + return MediaContributorRole.Brass; + if (value.Contains("woodwind", StringComparison.Ordinal) || value.Contains("flute", StringComparison.Ordinal) || value.Contains("saxophone", StringComparison.Ordinal) || value.Contains("clarinet", StringComparison.Ordinal)) + return MediaContributorRole.Woodwinds; + return null; + } + + /// + /// Maps a MusicBrainz artist type into the application enum. + /// + /// The artist type to map. + /// The mapped artist type, or when the type is unknown. + private static MusicArtistType? MapArtistType(string? type) + { + if (string.IsNullOrWhiteSpace(type)) + return null; + return type.Trim().ToLowerInvariant() switch + { + "person" => MusicArtistType.Person, + "group" => MusicArtistType.Group, + "orchestra" => MusicArtistType.Orchestra, + "choir" => MusicArtistType.Choir, + "character" => MusicArtistType.Character, + "other" => MusicArtistType.Other, + _ => null + }; + } + + /// + /// Maps a MusicBrainz gender into the application enum. + /// + /// The gender to map. + /// The mapped gender, or when the gender is unknown. + private static MusicArtistGender? MapArtistGender(string? gender) + { + if (string.IsNullOrWhiteSpace(gender)) + return null; + return gender.Trim().ToLowerInvariant() switch + { + "male" => MusicArtistGender.Male, + "female" => MusicArtistGender.Female, + "other" => MusicArtistGender.Other, + "not applicable" => MusicArtistGender.NotApplicable, + _ => null + }; + } + + /// + /// Maps the primary and secondary types of a release group into the application enum. + /// + /// The primary type of the release group. + /// The secondary types of the release group. + /// The mapped release types. + private static List MapReleaseTypes(string? primaryType, IReadOnlyCollection secondaryTypes) + { + List releaseTypes = []; + MusicReleaseType? primary = MapReleaseType(primaryType); + if (primary is not null) + releaseTypes.Add(primary.Value); + + foreach (string secondaryType in secondaryTypes) + { + MusicReleaseType? mapped = MapReleaseType(secondaryType); + if (mapped is not null && !releaseTypes.Contains(mapped.Value)) + releaseTypes.Add(mapped.Value); + } + return releaseTypes; + } + + /// + /// Maps a single MusicBrainz release type into the application enum. + /// + /// The release type to map. + /// The mapped release type, or when the type is unknown. + private static MusicReleaseType? MapReleaseType(string? type) + { + if (string.IsNullOrWhiteSpace(type)) + return null; + return type.Trim().ToLowerInvariant() switch + { + "album" => MusicReleaseType.Album, + "single" => MusicReleaseType.Single, + "ep" => MusicReleaseType.Ep, + "broadcast" => MusicReleaseType.Broadcast, + "other" => MusicReleaseType.Other, + "compilation" => MusicReleaseType.Compilation, + "live" => MusicReleaseType.Live, + "soundtrack" => MusicReleaseType.Soundtrack, + "spokenword" => MusicReleaseType.SpokenWord, + "audio drama" => MusicReleaseType.AudioDrama, + "audiobook" => MusicReleaseType.AudioBook, + "demo" => MusicReleaseType.Demo, + "dj-mix" => MusicReleaseType.DjMix, + "field recording" => MusicReleaseType.FieldRecording, + "interview" => MusicReleaseType.Interview, + "mixtape/street" => MusicReleaseType.Mixtape, + "remix" => MusicReleaseType.Remix, + _ => null + }; + } + + /// + /// Maps a MusicBrainz release status into the application enum. + /// + /// The release status to map. + /// The mapped release status, or when the status is unknown. + private static MusicReleaseStatus? MapReleaseStatus(string? status) + { + if (string.IsNullOrWhiteSpace(status)) + return null; + return status.Trim().ToLowerInvariant() switch + { + "official" => MusicReleaseStatus.Official, + "promotion" => MusicReleaseStatus.Promotion, + "bootleg" => MusicReleaseStatus.Bootleg, + "pseudo-release" => MusicReleaseStatus.PseudoRelease, + "withdrawn" => MusicReleaseStatus.Withdrawn, + "cancelled" => MusicReleaseStatus.Cancelled, + "expunged" => MusicReleaseStatus.Expunged, + _ => null + }; + } + + /// + /// Maps a MusicBrainz medium format into the application enum. + /// + /// The format to map. + /// The mapped media format, or when the format is unknown. + private static MusicMediaFormat? MapMediaFormat(string? format) + { + if (string.IsNullOrWhiteSpace(format)) + return null; + return format.Trim().ToLowerInvariant() switch + { + "cd" => MusicMediaFormat.CD, + "vinyl" => MusicMediaFormat.Vinyl, + "12\" vinyl" => MusicMediaFormat.Inch12Vinyl, + "10\" vinyl" => MusicMediaFormat.Inch10Vinyl, + "7\" vinyl" => MusicMediaFormat.Inch7Vinyl, + "digital media" => MusicMediaFormat.DigitalMedia, + "cassette" => MusicMediaFormat.Cassette, + "dvd" => MusicMediaFormat.DVD, + "dvd-video" => MusicMediaFormat.DVDVideo, + "dvd-audio" => MusicMediaFormat.DVDAudio, + "sacd" => MusicMediaFormat.SACD, + "hybrid sacd" => MusicMediaFormat.HybridSACD, + "blu-ray" => MusicMediaFormat.BluRay, + "minidisc" => MusicMediaFormat.MiniDisc, + "8cm cd" => MusicMediaFormat.Cm8CD, + "dat" => MusicMediaFormat.DAT, + "other" => MusicMediaFormat.Other, + _ => MusicMediaFormat.Other + }; + } + + /// + /// Maps a MusicBrainz release packaging into the application enum. + /// + /// The packaging to map. + /// The mapped packaging, or when the packaging is unknown. + private static MusicReleasePackaging? MapPackaging(string? packaging) + { + if (string.IsNullOrWhiteSpace(packaging)) + return null; + return packaging.Trim().ToLowerInvariant() switch + { + "book" => MusicReleasePackaging.Book, + "box" => MusicReleasePackaging.Box, + "cardboard/paper sleeve" => MusicReleasePackaging.CardboardPaperSleeve, + "cassette case" => MusicReleasePackaging.CassetteCase, + "clamshell case" => MusicReleasePackaging.ClamshellCase, + "digibook" => MusicReleasePackaging.Digibook, + "digifile" => MusicReleasePackaging.Digifile, + "digipak" => MusicReleasePackaging.Digipak, + "discbox slider" => MusicReleasePackaging.DiscboxSlider, + "fatbox" => MusicReleasePackaging.Fatbox, + "gatefold cover" => MusicReleasePackaging.GatefoldCover, + "jewel case" => MusicReleasePackaging.JewelCase, + "keep case" => MusicReleasePackaging.KeepCase, + "longbox" => MusicReleasePackaging.Longbox, + "metal tin" => MusicReleasePackaging.MetalTin, + "plastic sleeve" => MusicReleasePackaging.PlasticSleeve, + "slidepack" => MusicReleasePackaging.Slidepack, + "slim jewel case" => MusicReleasePackaging.SlimJewelCase, + "slipcase" => MusicReleasePackaging.Slipcase, + "snap case" => MusicReleasePackaging.SnapCase, + "snappack" => MusicReleasePackaging.SnapPack, + "super jewel box" => MusicReleasePackaging.SuperJewelBox, + "none" => MusicReleasePackaging.None, + "other" => MusicReleasePackaging.Other, + _ => MusicReleasePackaging.Other + }; + } + + /// + /// Maps an ISO 3166-1 alpha-2 country code into the application enum. + /// + /// The country code to map. + /// The mapped release country, or when the code is unknown. + private static ReleaseCountry? MapReleaseCountry(string? country) + { + if (string.IsNullOrWhiteSpace(country)) + return null; + return Enum.TryParse(country.Trim(), ignoreCase: true, out ReleaseCountry releaseCountry) ? releaseCountry : null; + } + + /// + /// Parses a MusicBrainz identifier into a . + /// + /// The MusicBrainz identifier to parse. + /// The parsed identifier, or when the value is not a valid identifier. + private static Guid? ParseGuid(string? value) + { + return Guid.TryParse(value, out Guid parsed) ? parsed : null; + } + + /// + /// Parses a MusicBrainz date string into a date and a year. + /// + /// The date string to parse. + /// The parsed date and year, or values when the string could not be parsed. + private static (DateOnly? Date, int? Year) ParseDate(string? value) + { + if (string.IsNullOrWhiteSpace(value)) + return (null, null); + + if (DateOnly.TryParse(value.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly exact)) + return (exact, exact.Year); + + Match yearMatch = YearPattern().Match(value); + return yearMatch.Success && int.TryParse(yearMatch.Value, CultureInfo.InvariantCulture, out int year) ? (null, year) : (null, null); + } + + /// + /// Returns the trimmed value, or when the value is empty or white space. + /// + /// The value to process. + /// The trimmed value, or . + private static string? NullIfWhiteSpace(string? value) + { + return string.IsNullOrWhiteSpace(value) ? null : value.Trim(); + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzAlbumMetadataProvider.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzAlbumMetadataProvider.cs new file mode 100644 index 00000000..ccdef688 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzAlbumMetadataProvider.cs @@ -0,0 +1,206 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Mapping; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core; + +/// +/// Provides album metadata from MusicBrainz by resolving lookups into album metadata DTOs. +/// A MusicBrainz release group is the logical album, while one of its releases is selected as the edition the local files match. +/// +internal sealed class MusicBrainzAlbumMetadataProvider : IMetadataProvider +{ + private readonly MusicBrainzHttpClient _musicBrainzHttpClient; + private readonly MusicBrainzSettingsProvider _settingsProvider; + + /// + /// Gets the display name of the metadata provider. + /// + public string Name => "MusicBrainz"; + + /// + /// Gets the media library types this metadata provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. + /// + public bool RequiresWebAccess => true; + + /// + /// Initializes a new instance of the class. + /// + /// The HTTP client used to call the MusicBrainz web service. + /// The provider of the settings that configure the MusicBrainz web service requests. + public MusicBrainzAlbumMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider) + { + _musicBrainzHttpClient = musicBrainzHttpClient; + _settingsProvider = settingsProvider; + } + + /// + /// Searches for the metadata of the album described by . + /// + /// The lookup describing the album to search for. + /// Cancellation token that can be used to stop the execution. + /// The collection of album metadata candidates found. + public async Task> GetSearchResultsAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(lookup.Title)) + return []; + + MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + IReadOnlyList releaseGroups = await _musicBrainzHttpClient + .SearchReleaseGroupsAsync(BuildReleaseGroupQuery(lookup.Title, lookup.ArtistName), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false); + + List candidates = []; + foreach (MusicBrainzReleaseGroupResponse releaseGroup in releaseGroups) + if (!string.IsNullOrWhiteSpace(releaseGroup.Title)) + candidates.Add(MusicBrainzMapper.MapAlbum(releaseGroup, null)); + + return candidates; + } + + /// + /// Gets the metadata of the album described by . + /// + /// The lookup describing the album to get the metadata for. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the album, or when no album was found. + public async Task GetMetadataAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken) + { + MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + MusicBrainzReleaseResponse? release = null; + MusicBrainzReleaseGroupResponse? releaseGroup = null; + + // A release identifier pins the exact edition, so it is fetched first, and its release group is then resolved for the album level fields. + // The release is fetched together with its recordings, so that the track level enrichment of the same release is served from the response cache. + if (lookup.MusicBrainzReleaseId is not null) + release = await _musicBrainzHttpClient.GetReleaseWithRecordingsAsync(lookup.MusicBrainzReleaseId.Value, cancellationToken).ConfigureAwait(false); + + Guid? releaseGroupId = lookup.MusicBrainzReleaseGroupId; + if (releaseGroupId is null && release?.ReleaseGroup?.Id is string releaseGroupIdValue && Guid.TryParse(releaseGroupIdValue, out Guid parsedReleaseGroupId)) + releaseGroupId = parsedReleaseGroupId; + + if (releaseGroupId is not null) + releaseGroup = await _musicBrainzHttpClient.GetReleaseGroupAsync(releaseGroupId.Value, cancellationToken).ConfigureAwait(false); + + // Without any identifier, the album is searched by title and artist, and the first match is resolved in full. + if (release is null && releaseGroup is null && !string.IsNullOrWhiteSpace(lookup.Title)) + { + IReadOnlyList results = await _musicBrainzHttpClient + .SearchReleaseGroupsAsync(BuildReleaseGroupQuery(lookup.Title, lookup.ArtistName), 1, cancellationToken).ConfigureAwait(false); + MusicBrainzReleaseGroupResponse? searchResult = results.Count > 0 ? results[0] : null; + if (searchResult?.Id is string searchResultId && Guid.TryParse(searchResultId, out Guid parsedSearchResultId)) + releaseGroup = await _musicBrainzHttpClient.GetReleaseGroupAsync(parsedSearchResultId, cancellationToken).ConfigureAwait(false); + } + + if (releaseGroup is null) + return release is null ? null : MusicBrainzMapper.MapAlbum(new MusicBrainzReleaseGroupResponse { Id = release.ReleaseGroup?.Id, Title = release.Title }, release); + + // When the exact release was not pinned by the lookup, the best edition of the release group is selected. + if (release is null && releaseGroup.Id is string releaseGroupIdentifier && Guid.TryParse(releaseGroupIdentifier, out Guid releaseGroupGuid)) + { + IReadOnlyList releases = await _musicBrainzHttpClient + .BrowseReleasesByReleaseGroupAsync(releaseGroupGuid, settings.ReleaseLookupLimit, cancellationToken).ConfigureAwait(false); + release = SelectRelease(releases, lookup); + } + + return MusicBrainzMapper.MapAlbum(releaseGroup, release); + } + + /// + /// Selects the release of a release group that best matches the lookup, favoring official releases and those released in the lookup year. + /// + /// The releases to select from. + /// The lookup the selected release must match. + /// The best matching release, or when no release was provided. + private static MusicBrainzReleaseResponse? SelectRelease(IReadOnlyList releases, AlbumMetadataLookupDto lookup) + { + // Only a release whose tracklist matches the local album is selected, so that an edition of the release group that does not correspond to the + // local files is never attached to the album; without a known local track count, no release can be confidently matched, so none is selected. + if (lookup.TrackCount is not int trackCount) + return null; + + List matchingReleases = [.. releases.Where(release => release.Media.Sum(medium => medium.TrackCount) == trackCount)]; + if (matchingReleases.Count == 0) + return null; + + return matchingReleases + .Select((release, index) => new + { + Release = release, + Index = index, + Score = ScoreRelease(release, lookup) + }) + .OrderByDescending(item => item.Score) + .ThenBy(item => item.Index) + .Select(item => item.Release) + .First(); + } + + /// + /// Scores a release against the lookup to rank how well it matches. + /// + /// The release to score. + /// The lookup the release must match. + /// The match score of the release, where a higher score is a better match. + private static int ScoreRelease(MusicBrainzReleaseResponse release, AlbumMetadataLookupDto lookup) + { + int score = 0; + if (string.Equals(release.Status, "Official", StringComparison.OrdinalIgnoreCase)) + score += 10_000; + + if (lookup.ReleaseYear is int wantedYear && TryGetYear(release.Date) is int releaseYear && releaseYear == wantedYear) + score += 1_000; + + if (!string.IsNullOrWhiteSpace(release.Barcode)) + score += 100; + if (release.LabelInfo.Count > 0) + score += 50; + if (release.Media.Count > 0) + score += 10; + return score; + } + + /// + /// Gets the year of a MusicBrainz date string. + /// + /// The date string to read. + /// The year of the date, or when it could not be read. + private static int? TryGetYear(string? date) + { + if (string.IsNullOrWhiteSpace(date)) + return null; + string year = date.Length >= 4 ? date[..4] : date; + return int.TryParse(year, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed) ? parsed : null; + } + + /// + /// Builds the MusicBrainz release group search query for the provided title and artist. + /// + /// The title of the release group. + /// The name of the artist, if applicable. + /// The built search query. + private static string BuildReleaseGroupQuery(string title, string? artistName) + { + string query = $"releasegroup:\"{title.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\""; + if (!string.IsNullOrWhiteSpace(artistName)) + query += $" AND artist:\"{artistName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\""; + return query; + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzArtistMetadataProvider.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzArtistMetadataProvider.cs new file mode 100644 index 00000000..30ef2ff9 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzArtistMetadataProvider.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Mapping; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core; + +/// +/// Provides music artist metadata from MusicBrainz by resolving lookups into artist metadata DTOs. +/// +internal sealed class MusicBrainzArtistMetadataProvider : IMetadataProvider +{ + private readonly MusicBrainzHttpClient _musicBrainzHttpClient; + private readonly MusicBrainzSettingsProvider _settingsProvider; + + /// + /// Gets the display name of the metadata provider. + /// + public string Name => "MusicBrainz"; + + /// + /// Gets the media library types this metadata provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. + /// + public bool RequiresWebAccess => true; + + /// + /// Initializes a new instance of the class. + /// + /// The HTTP client used to call the MusicBrainz web service. + /// The provider of the settings that configure the MusicBrainz web service requests. + public MusicBrainzArtistMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider) + { + _musicBrainzHttpClient = musicBrainzHttpClient; + _settingsProvider = settingsProvider; + } + + /// + /// Searches for the metadata of the artist described by . + /// + /// The lookup describing the artist to search for. + /// Cancellation token that can be used to stop the execution. + /// The collection of artist metadata candidates found. + public async Task> GetSearchResultsAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(lookup.Name)) + return []; + + MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + IReadOnlyList artists = await _musicBrainzHttpClient + .SearchArtistsAsync(lookup.Name.Trim(), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false); + + List candidates = []; + foreach (MusicBrainzArtistResponse artist in artists) + if (!string.IsNullOrWhiteSpace(artist.Name)) + candidates.Add(MusicBrainzMapper.MapArtist(artist)); + return candidates; + } + + /// + /// Gets the metadata of the artist described by . + /// + /// The lookup describing the artist to get the metadata for. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the artist, or when no artist was found. + public async Task GetMetadataAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken) + { + // A MusicBrainz identifier is the most precise lookup, so it is used first, if present. + if (lookup.MusicBrainzArtistId is not null) + { + MusicBrainzArtistResponse? artist = await _musicBrainzHttpClient.GetArtistAsync(lookup.MusicBrainzArtistId.Value, cancellationToken).ConfigureAwait(false); + return artist is null ? null : MusicBrainzMapper.MapArtist(artist); + } + + if (string.IsNullOrWhiteSpace(lookup.Name)) + return null; + + // Without an identifier, the artist is searched by name, and the first match is resolved in full. + IReadOnlyList artists = await _musicBrainzHttpClient + .SearchArtistsAsync(lookup.Name.Trim(), 1, cancellationToken).ConfigureAwait(false); + MusicBrainzArtistResponse? searchResult = artists.Count > 0 ? artists[0] : null; + if (searchResult?.Id is null) + return null; + + MusicBrainzArtistResponse? detailedArtist = System.Guid.TryParse(searchResult.Id, out System.Guid artistId) + ? await _musicBrainzHttpClient.GetArtistAsync(artistId, cancellationToken).ConfigureAwait(false) + : null; + return detailedArtist is null ? MusicBrainzMapper.MapArtist(searchResult) : MusicBrainzMapper.MapArtist(detailedArtist); + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzPlugin.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzPlugin.cs new file mode 100644 index 00000000..e582c0d9 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzPlugin.cs @@ -0,0 +1,97 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.MusicBrainz.Common.DependencyInjection; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core; + +/// +/// Plugin that provides music metadata retrieval from MusicBrainz. +/// +public sealed class MusicBrainzPlugin : IPlugin, IPluginServiceRegistrator +{ + /// + /// The unique identifier of the plugin. + /// + public static readonly Guid s_pluginId = new("f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3"); + + /// + /// Gets the unique identifier of the plugin. + /// + public Guid Id => s_pluginId; + + /// + /// Gets the display name of the plugin. + /// + public string Name => "MusicBrainz Metadata"; + + /// + /// Gets the author of the plugin. + /// + public string Author => "Lumina"; + + /// + /// Gets the version of the plugin. + /// + public Version Version => new(1, 0, 0); + + /// + /// Gets the description of the plugin. + /// + public string Description => "Retrieves artist, album and track metadata from MusicBrainz."; + + /// + /// Gets the settings schema of the plugin. + /// + /// The settings descriptors of the plugin. + public IReadOnlyList GetSettingsSchema() + { + return + [ + new PluginSettingDescriptorDto( + Key: MusicBrainzSettingsKeys.BASE_URL, + Label: "Base URL", + Type: PluginSettingType.Text, + DefaultValue: "https://musicbrainz.org/ws/2/"), + new PluginSettingDescriptorDto( + Key: MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL, + Label: "Allow LAN/Private Base URL", + Type: PluginSettingType.Boolean, + DefaultValue: "false"), + new PluginSettingDescriptorDto( + Key: MusicBrainzSettingsKeys.CONTACT_EMAIL, + Label: "Contact Email", + Type: PluginSettingType.Text), + new PluginSettingDescriptorDto( + Key: MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT, + Label: "Search Result Limit", + Type: PluginSettingType.Number, + DefaultValue: "10"), + new PluginSettingDescriptorDto( + Key: MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT, + Label: "Release Lookup Limit", + Type: PluginSettingType.Number, + DefaultValue: "25"), + new PluginSettingDescriptorDto( + Key: MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, + Label: "Minimum Request Interval (seconds)", + Type: PluginSettingType.Number, + DefaultValue: "1.0") + ]; + } + + /// + /// Registers the services required by the plugin. + /// + /// The service collection to register the services into. + public void RegisterServices(IServiceCollection services) + { + services.AddMusicBrainzMetadataProviders(pluginId: Id); + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzTrackMetadataProvider.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzTrackMetadataProvider.cs new file mode 100644 index 00000000..25a0c763 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzTrackMetadataProvider.cs @@ -0,0 +1,270 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Mapping; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core; + +/// +/// Provides track metadata from MusicBrainz by resolving lookups into audio metadata DTOs. +/// +internal sealed class MusicBrainzTrackMetadataProvider : IMetadataProvider +{ + private readonly MusicBrainzHttpClient _musicBrainzHttpClient; + private readonly MusicBrainzSettingsProvider _settingsProvider; + + /// + /// Gets the display name of the metadata provider. + /// + public string Name => "MusicBrainz"; + + /// + /// Gets the media library types this metadata provider supports. + /// + public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music]; + + /// + /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata. + /// + public bool RequiresWebAccess => true; + + /// + /// Initializes a new instance of the class. + /// + /// The HTTP client used to call the MusicBrainz web service. + /// The provider of the settings that configure the MusicBrainz web service requests. + public MusicBrainzTrackMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider) + { + _musicBrainzHttpClient = musicBrainzHttpClient; + _settingsProvider = settingsProvider; + } + + /// + /// Searches for the metadata of the track described by . + /// + /// The lookup describing the track to search for. + /// Cancellation token that can be used to stop the execution. + /// The collection of track metadata candidates found. + public async Task> GetSearchResultsAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(lookup.Title)) + return []; + + MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false); + IReadOnlyList recordings = await _musicBrainzHttpClient + .SearchRecordingsAsync(BuildRecordingQuery(lookup), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false); + + List candidates = []; + foreach (MusicBrainzRecordingResponse recording in recordings) + if (!string.IsNullOrWhiteSpace(recording.Title)) + candidates.Add(MusicBrainzMapper.MapTrack(recording, null, null)); + return candidates; + } + + /// + /// Gets the metadata of the track described by . + /// + /// The lookup describing the track to get the metadata for. + /// Cancellation token that can be used to stop the execution. + /// The metadata of the track, or when no track was found. + public async Task GetMetadataAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken) + { + // When the release the track belongs to is known, the release is fetched once, with all its recordings, and the track is resolved from its + // tracklist; the recording of that response already carries its work, so every track of the release is enriched from a single request. + if (lookup.MusicBrainzReleaseId is not null) + { + MusicBrainzReleaseResponse? release = await _musicBrainzHttpClient.GetReleaseWithRecordingsAsync(lookup.MusicBrainzReleaseId.Value, cancellationToken).ConfigureAwait(false); + MusicBrainzTrackResponse? releaseTrack = release is null ? null : FindTrack(release, lookup); + if (releaseTrack?.Recording is not null) + { + MusicBrainzWorkResponse? inlineWork = await ResolveFallbackWorkAsync(ResolveInlineWork(releaseTrack.Recording), lookup, cancellationToken).ConfigureAwait(false); + return MusicBrainzMapper.MapTrack(releaseTrack.Recording, inlineWork, release); + } + } + + MusicBrainzRecordingResponse? recording = null; + + // A recording identifier is the most precise lookup, so it is used next, if present. + if (lookup.MusicBrainzRecordingId is not null) + recording = await _musicBrainzHttpClient.GetRecordingAsync(lookup.MusicBrainzRecordingId.Value, cancellationToken).ConfigureAwait(false); + + // An ISRC lookup returns the recordings that carry the code, the first of which is then resolved in full. + if (recording is null && !string.IsNullOrWhiteSpace(lookup.Isrc)) + { + IReadOnlyList recordings = await _musicBrainzHttpClient + .GetRecordingsByIsrcAsync(lookup.Isrc.Trim(), cancellationToken).ConfigureAwait(false); + MusicBrainzRecordingResponse? match = recordings.FirstOrDefault(); + recording = await ResolveRecordingAsync(match, cancellationToken).ConfigureAwait(false); + } + + // Without an identifier or a code, the track is searched, and the first match is resolved in full. + if (recording is null && !string.IsNullOrWhiteSpace(lookup.Title)) + { + IReadOnlyList recordings = await _musicBrainzHttpClient + .SearchRecordingsAsync(BuildRecordingQuery(lookup), 1, cancellationToken).ConfigureAwait(false); + recording = await ResolveRecordingAsync(recordings.FirstOrDefault(), cancellationToken).ConfigureAwait(false); + } + + if (recording is null) + return null; + + MusicBrainzWorkResponse? work = await ResolveWorkAsync(recording, cancellationToken).ConfigureAwait(false); + work = await ResolveFallbackWorkAsync(work, lookup, cancellationToken).ConfigureAwait(false); + MusicBrainzReleaseResponse? resolvedRelease = await ResolveReleaseAsync(recording, cancellationToken).ConfigureAwait(false); + return MusicBrainzMapper.MapTrack(recording, work, resolvedRelease); + } + + /// + /// Falls back to the work identifier of the tags when MusicBrainz did not link the recording to a work. + /// + /// The work resolved from MusicBrainz, if any. + /// The lookup describing the local track. + /// Cancellation token that can be used to stop the execution. + /// The provided work, the work resolved from the work identifier of the tags, or when neither is available. + private async Task ResolveFallbackWorkAsync(MusicBrainzWorkResponse? work, TrackMetadataLookupDto lookup, CancellationToken cancellationToken) + { + // The title of the tags means the work of the tags is already complete, so it is kept as is and MusicBrainz is not queried again for it. + if (work is not null || lookup.MusicBrainzWorkId is not Guid musicBrainzWorkId || !string.IsNullOrWhiteSpace(lookup.WorkTitle)) + return work; + return await _musicBrainzHttpClient.GetWorkAsync(musicBrainzWorkId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Finds the track of that matches the provided , matching the recording identifier first, + /// then the disc and track numbers, then the title, and finally the duration. + /// + /// The release whose tracklist is searched. + /// The lookup describing the local track. + /// The matching track, or when no track matched. + private static MusicBrainzTrackResponse? FindTrack(MusicBrainzReleaseResponse release, TrackMetadataLookupDto lookup) + { + // The recording identifier is the most precise match, so it is used first, if present. + if (lookup.MusicBrainzRecordingId is Guid musicBrainzRecordingId) + { + foreach (MusicBrainzMediumResponse medium in release.Media) + foreach (MusicBrainzTrackResponse track in medium.Tracks) + if (track.Recording?.Id is string recordingId && Guid.TryParse(recordingId, out Guid trackRecordingId) && trackRecordingId == musicBrainzRecordingId) + return track; + } + + List candidates = []; + foreach (MusicBrainzMediumResponse medium in release.Media) + { + if (lookup.DiscNumber is int discNumber && medium.Position != discNumber) + continue; + foreach (MusicBrainzTrackResponse track in medium.Tracks) + { + if (lookup.TrackNumber is int trackNumber && track.Position != trackNumber) + continue; + candidates.Add(track); + } + } + if (candidates.Count <= 1) + return candidates.Count == 1 ? candidates[0] : null; + + // The disc and track numbers were not enough to single the track out, so the title is used next, and the duration breaks any remaining tie. + if (!string.IsNullOrWhiteSpace(lookup.Title)) + { + List titledCandidates = [.. candidates.Where(candidate => string.Equals(candidate.Title, lookup.Title, StringComparison.OrdinalIgnoreCase))]; + if (titledCandidates.Count == 1) + return titledCandidates[0]; + if (titledCandidates.Count > 1) + candidates = titledCandidates; + } + if (candidates.Count > 1 && lookup.DurationInSeconds is int duration) + return candidates.OrderBy(candidate => Math.Abs((candidate.Length ?? 0) / 1000 - duration)).First(); + return candidates[0]; + } + + /// + /// Gets the work the provided is a performance of, from the relations already embedded in the response. + /// + /// The recording whose work is resolved. + /// The embedded work, or when the recording has no work. + private static MusicBrainzWorkResponse? ResolveInlineWork(MusicBrainzRecordingResponse recording) + { + return recording.Relations + .Where(relation => string.Equals(relation.TargetType, "work", StringComparison.OrdinalIgnoreCase)) + .Select(relation => relation.Work) + .FirstOrDefault(work => work is not null); + } + + /// + /// Resolves the full recording of the provided search or ISRC lookup result. + /// + /// The partial recording to resolve. + /// Cancellation token that can be used to stop the execution. + /// The full recording, or when the recording could not be resolved. + private async Task ResolveRecordingAsync(MusicBrainzRecordingResponse? recording, CancellationToken cancellationToken) + { + if (recording?.Id is null || !Guid.TryParse(recording.Id, out Guid recordingId)) + return recording; + + return await _musicBrainzHttpClient.GetRecordingAsync(recordingId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Resolves the work the provided recording is an instance of, together with its credited contributors. + /// + /// The recording whose work is resolved. + /// Cancellation token that can be used to stop the execution. + /// The work of the recording, or when the recording has no work. + private async Task ResolveWorkAsync(MusicBrainzRecordingResponse recording, CancellationToken cancellationToken) + { + string? workId = recording.Relations + .Where(relation => string.Equals(relation.TargetType, "work", StringComparison.OrdinalIgnoreCase)) + .Select(relation => relation.Work?.Id) + .FirstOrDefault(id => !string.IsNullOrWhiteSpace(id)); + + if (workId is null || !Guid.TryParse(workId, out Guid parsedWorkId)) + return recording.Relations + .Where(relation => string.Equals(relation.TargetType, "work", StringComparison.OrdinalIgnoreCase)) + .Select(relation => relation.Work) + .FirstOrDefault(work => work is not null); + + return await _musicBrainzHttpClient.GetWorkAsync(parsedWorkId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Resolves the release the provided recording appears on, for the release level language and script. + /// + /// The recording whose release is resolved. + /// Cancellation token that can be used to stop the execution. + /// The release of the recording, or when the recording does not reference a release. + private async Task ResolveReleaseAsync(MusicBrainzRecordingResponse recording, CancellationToken cancellationToken) + { + string? releaseId = recording.Releases.Select(release => release.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id)); + if (releaseId is null || !Guid.TryParse(releaseId, out Guid parsedReleaseId)) + return null; + + return await _musicBrainzHttpClient.GetReleaseAsync(parsedReleaseId, cancellationToken).ConfigureAwait(false); + } + + /// + /// Builds the MusicBrainz recording search query for the provided lookup. + /// + /// The lookup describing the track. + /// The built search query. + private static string BuildRecordingQuery(TrackMetadataLookupDto lookup) + { + List parts = []; + if (!string.IsNullOrWhiteSpace(lookup.Title)) + parts.Add($"recording:\"{lookup.Title.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\""); + if (!string.IsNullOrWhiteSpace(lookup.ArtistName)) + parts.Add($"artist:\"{lookup.ArtistName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\""); + if (!string.IsNullOrWhiteSpace(lookup.ReleaseName)) + parts.Add($"release:\"{lookup.ReleaseName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\""); + return string.Join(" AND ", parts); + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsKeys.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsKeys.cs new file mode 100644 index 00000000..2ddd79e1 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsKeys.cs @@ -0,0 +1,37 @@ +namespace Lumina.Plugins.MusicBrainz.Core.Settings; + +/// +/// Keys of the settings of the MusicBrainz metadata plugin, shared by the settings schema and the settings loader. +/// +internal static class MusicBrainzSettingsKeys +{ + /// + /// The key of the setting defining the base URL of the MusicBrainz web service. + /// + internal const string BASE_URL = "BaseUrl"; + + /// + /// The key of the setting that allows the base URL to point at a private or local host, for a self hosted mirror on a local network. + /// + internal const string DOES_ALLOW_PRIVATE_BASE_URL = "DoesAllowPrivateBaseUrl"; + + /// + /// The key of the setting defining the contact email sent to the MusicBrainz API. + /// + internal const string CONTACT_EMAIL = "ContactEmail"; + + /// + /// The key of the setting defining the maximum number of results returned by a single search. + /// + internal const string SEARCH_RESULT_LIMIT = "SearchResultLimit"; + + /// + /// The key of the setting defining the maximum number of releases fetched for a single release group. + /// + internal const string RELEASE_LOOKUP_LIMIT = "ReleaseLookupLimit"; + + /// + /// The key of the setting defining the minimum interval between consecutive requests to the MusicBrainz API, in seconds. + /// + internal const string MINIMUM_REQUEST_INTERVAL_SECONDS = "MinimumRequestIntervalSeconds"; +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsProvider.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsProvider.cs new file mode 100644 index 00000000..95830b04 --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsProvider.cs @@ -0,0 +1,210 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Core.Settings; + +/// +/// Provides the runtime settings of the MusicBrainz metadata plugin, overlaying the settings persisted by the host over the configured defaults. +/// +internal sealed class MusicBrainzSettingsProvider +{ + private readonly IPluginSettingsStore? _settingsStore; + private readonly Guid _pluginId; + private readonly MusicBrainzSettingsDto _defaults; + + // The resolved settings are read on every request, so the resolved instance is published through Volatile to keep the common, already + // resolved path lock free; the gate is only needed by the first callers that race to resolve it. + private readonly SemaphoreSlim _gate = new(1, 1); + private MusicBrainzSettingsDto? _runtimeSettings; + + /// + /// Initializes a new instance of the class. + /// + /// The store of the settings persisted by the host, or when no store is available. + /// The unique identifier of the plugin whose settings are read. + /// The runtime settings with the default values and the optional configuration callback already applied. + public MusicBrainzSettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, MusicBrainzSettingsDto defaults) + { + _settingsStore = settingsStore; + _pluginId = pluginId; + _defaults = defaults; + } + + /// + /// Gets the runtime settings of the plugin, reading and applying the settings persisted by the host on the first call. + /// + /// Cancellation token that can be used to stop the execution. + /// The runtime settings of the plugin. + public async Task GetAsync(CancellationToken cancellationToken) + { + // Lock free first check: reading through Volatile guarantees that a fully resolved instance published by another thread is observed intact. + MusicBrainzSettingsDto? runtimeSettings = Volatile.Read(ref _runtimeSettings); + if (runtimeSettings is not null) + return runtimeSettings; + + // Only the first callers reach this point, and the gate serializes them, so the settings store is queried exactly once. + await _gate.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + // Second check inside the gate: another caller may have resolved the settings while this one was waiting for it. + runtimeSettings = Volatile.Read(ref _runtimeSettings); + if (runtimeSettings is null) + { + // The defaults are cloned so that applying the persisted settings never mutates the instance shared with the other scopes. + runtimeSettings = Clone(_defaults); + if (_settingsStore is not null) + { + IReadOnlyDictionary? storedSettings = await _settingsStore.GetSettingsAsync(_pluginId, cancellationToken).ConfigureAwait(false); + if (storedSettings is not null) + Apply(runtimeSettings, storedSettings); + } + + // Publishing through Volatile makes the fully built instance visible to the lock free readers above. + Volatile.Write(ref _runtimeSettings, runtimeSettings); + } + + return runtimeSettings; + } + finally + { + _gate.Release(); + } + } + + /// + /// Overlays the persisted settings onto the provided runtime settings, keeping the default values of the settings that were not persisted. + /// + /// The runtime settings onto which the persisted settings are applied. + /// The settings persisted by the host, keyed by setting key. + private static void Apply(MusicBrainzSettingsDto settings, IReadOnlyDictionary storedSettings) + { + // The private host opt-in must be resolved first, because it governs whether a private base URL is accepted below. + if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL, out string? doesAllowPrivateBaseUrl) && + bool.TryParse(doesAllowPrivateBaseUrl, out bool doesAllowPrivateBaseUrlValue)) + settings.DoesAllowPrivateBaseUrl = doesAllowPrivateBaseUrlValue; + + if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.BASE_URL, out string? baseUrl) && + Uri.TryCreate(baseUrl?.Trim(), UriKind.Absolute, out Uri? parsedBaseUrl) && + (parsedBaseUrl.Scheme == Uri.UriSchemeHttp || parsedBaseUrl.Scheme == Uri.UriSchemeHttps) && + (settings.DoesAllowPrivateBaseUrl || IsPublicHost(parsedBaseUrl.Host))) + settings.BaseUrl = parsedBaseUrl.AbsoluteUri; + + if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.CONTACT_EMAIL, out string? contactEmail)) + { + string? trimmedContactEmail = string.IsNullOrWhiteSpace(contactEmail) ? null : contactEmail.Trim(); + settings.ContactEmail = trimmedContactEmail is not null && IsSafeContactEmail(trimmedContactEmail) ? trimmedContactEmail : null; + } + + if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT, out string? searchResultLimit) && + int.TryParse(searchResultLimit, NumberStyles.Integer, CultureInfo.InvariantCulture, out int searchResultLimitValue)) + settings.SearchResultLimit = Math.Max(1, searchResultLimitValue); + + if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT, out string? releaseLookupLimit) && + int.TryParse(releaseLookupLimit, NumberStyles.Integer, CultureInfo.InvariantCulture, out int releaseLookupLimitValue)) + settings.ReleaseLookupLimit = Math.Max(1, releaseLookupLimitValue); + + if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, out string? minimumRequestInterval) && + double.TryParse(minimumRequestInterval, NumberStyles.Float, CultureInfo.InvariantCulture, out double minimumRequestIntervalValue)) + settings.MinimumRequestInterval = TimeSpan.FromSeconds(Math.Max(0, minimumRequestIntervalValue)); + } + + /// + /// Determines whether the host of the persisted base URL is a public host, so the setting cannot be used to reach a local or private service. + /// + /// The host of the persisted base URL. + /// when the host is public, otherwise . + /// + /// A host name is accepted as is, because it cannot be classified without resolving it, which is deliberately not done here. + /// A private or local host is accepted when is enabled, which supports self hosted + /// mirrors on a local network. + /// + private static bool IsPublicHost(string host) + { + if (string.IsNullOrWhiteSpace(host)) + return false; + + // Uri.Host surrounds an IPv6 literal with brackets, which IPAddress.TryParse does not accept. + string normalizedHost = host.Trim('[', ']'); + if (string.Equals(normalizedHost, "localhost", StringComparison.OrdinalIgnoreCase)) + return false; + + if (!IPAddress.TryParse(normalizedHost, out IPAddress? address)) + return true; + + if (address.IsIPv4MappedToIPv6) + address = address.MapToIPv4(); + + if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) + return false; + + if (address.AddressFamily == AddressFamily.InterNetwork) + { + byte[] octets = address.GetAddressBytes(); + // The unspecified, private, loopback, link local and carrier grade NAT ranges are rejected, as they are the common targets of an SSRF. + return octets[0] switch + { + 0 => false, + 10 => false, + 100 when octets[1] is >= 64 and <= 127 => false, + 127 => false, + 169 when octets[1] == 254 => false, + 172 when octets[1] is >= 16 and <= 31 => false, + 192 when octets[1] == 168 => false, + _ => true + }; + } + + if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal) + return false; + + byte[] addressBytes = address.GetAddressBytes(); + // The fc00::/7 unique local range is rejected, matching the private IPv4 ranges. + if ((addressBytes[0] & 0xFE) == 0xFC) + return false; + + return true; + } + + /// + /// Determines whether the persisted contact email only contains characters that are safe inside the request user agent header. + /// + /// The persisted contact email. + /// when the email is safe, otherwise . + private static bool IsSafeContactEmail(string contactEmail) + { + // The email is embedded in the User-Agent header, and an invalid character there throws when the header is parsed, which would break every request of the plugin, + // so anything outside a conservative email charset is rejected. + foreach (char character in contactEmail) + if (!char.IsAsciiLetterOrDigit(character) && character is not ('@' or '.' or '_' or '-' or '+')) + return false; + return true; + } + + /// + /// Creates a copy of the given runtime settings. + /// + /// The runtime settings to copy. + /// A copy of the given runtime settings. + private static MusicBrainzSettingsDto Clone(MusicBrainzSettingsDto source) + { + return new MusicBrainzSettingsDto + { + BaseUrl = source.BaseUrl, + DoesAllowPrivateBaseUrl = source.DoesAllowPrivateBaseUrl, + UserAgent = source.UserAgent, + ContactEmail = source.ContactEmail, + SearchResultLimit = source.SearchResultLimit, + ReleaseLookupLimit = source.ReleaseLookupLimit, + MinimumRequestInterval = source.MinimumRequestInterval + }; + } +} diff --git a/plugins/Lumina.Plugins.MusicBrainz/Lumina.Plugins.MusicBrainz.csproj b/plugins/Lumina.Plugins.MusicBrainz/Lumina.Plugins.MusicBrainz.csproj new file mode 100644 index 00000000..bed7d79c --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Lumina.Plugins.MusicBrainz.csproj @@ -0,0 +1,34 @@ + + + net10.0 + disable + enable + $(SolutionDir)..\bin\plugins\ + false + true + true + $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904 + true + + + + + + + + + + + + + + + false + runtime + + + + + + + diff --git a/plugins/Lumina.Plugins.MusicBrainz/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.MusicBrainz/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..e4c7f52a --- /dev/null +++ b/plugins/Lumina.Plugins.MusicBrainz/Properties/AssemblyInfo.cs @@ -0,0 +1,6 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.Fixtures")] +[assembly: InternalsVisibleTo("Lumina.Presentation.Api.SecurityTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAliasResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAliasResponseFixture.cs new file mode 100644 index 00000000..bf3e9d50 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAliasResponseFixture.cs @@ -0,0 +1,80 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzAliasResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The name of the alias. + /// Whether the name should be included, or forced to . + /// Optional. The sort name of the alias. + /// Whether the sort name should be included, or forced to . + /// Optional. The type of the alias. + /// Whether the type should be included, or forced to . + /// Optional. The locale the alias is used in. + /// Whether the locale should be included, or forced to . + /// Optional. Whether this is the primary alias. + /// Whether the primary flag should be included, or forced to . + /// Optional. The begin date of the alias. + /// Whether the begin date should be included, or forced to . + /// Optional. The end date of the alias. + /// Whether the end date should be included, or forced to . + /// Optional. Whether the alias has ended. + /// Whether the ended flag should be included, or forced to . + /// A configured instance. + public MusicBrainzAliasResponse Create( + string? name = null, + bool includeName = true, + string? sortName = null, + bool includeSortName = true, + string? type = null, + bool includeType = true, + string? locale = null, + bool includeLocale = true, + bool? isPrimary = null, + bool includePrimary = true, + string? begin = null, + bool includeBegin = true, + string? end = null, + bool includeEnd = true, + bool? isEnded = null, + bool includeEnded = true) + { + return new MusicBrainzAliasResponse + { + Name = includeName ? name ?? _faker.Name.FullName() : null, + SortName = includeSortName ? sortName ?? _faker.Name.FullName() : null, + Type = includeType ? type ?? _faker.PickRandom("Artist name", "Legal name") : null, + Locale = includeLocale ? locale ?? _faker.PickRandom("en", "de", "fr") : null, + IsPrimary = includePrimary ? isPrimary ?? _faker.Random.Bool() : null, + Begin = includeBegin ? begin ?? _faker.Date.Past(50).ToString("yyyy-MM-dd") : null, + End = includeEnd ? end ?? _faker.Date.Past(5).ToString("yyyy-MM-dd") : null, + IsEnded = includeEnded ? isEnded ?? _faker.Random.Bool() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAreaResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAreaResponseFixture.cs new file mode 100644 index 00000000..865b2068 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAreaResponseFixture.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzAreaResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the area. + /// Whether the identifier should be included, or forced to . + /// Optional. The name of the area. + /// Whether the name should be included, or forced to . + /// Optional. The sort name of the area. + /// Whether the sort name should be included, or forced to . + /// Optional. The disambiguation comment of the area. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The MusicBrainz type of the area. + /// Whether the type should be included, or forced to . + /// Optional. The ISO 3166-1 codes of the area. + /// Optional. The ISO 3166-2 codes of the area. + /// A configured instance. + public MusicBrainzAreaResponse Create( + string? id = null, + bool includeId = true, + string? name = null, + bool includeName = true, + string? sortName = null, + bool includeSortName = true, + string? disambiguation = null, + bool includeDisambiguation = true, + string? type = null, + bool includeType = true, + List? iso3166Part1Codes = null, + List? iso3166Part2Codes = null) + { + return new MusicBrainzAreaResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Name = includeName ? name ?? _faker.Address.Country() : null, + SortName = includeSortName ? sortName ?? _faker.Address.Country() : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + Type = includeType ? type ?? _faker.PickRandom("Country", "City", "Area") : null, + Iso3166Part1Codes = iso3166Part1Codes ?? [_faker.Address.CountryCode()], + Iso3166Part2Codes = iso3166Part2Codes ?? [_faker.Random.String2(5, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")] + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseFixture.cs new file mode 100644 index 00000000..a813a61b --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseFixture.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzArtistCreditResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzArtistResponseFixture _musicBrainzArtistResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The credited name of the artist. + /// Whether the name should be included, or forced to . + /// Optional. The join phrase that follows the credit. + /// Whether the join phrase should be included, or forced to . + /// Optional. The artist the credit refers to. + /// Whether the artist should be included, or forced to . + /// A configured instance. + public MusicBrainzArtistCreditResponse Create( + string? name = null, + bool includeName = true, + string? joinPhrase = null, + bool includeJoinPhrase = true, + MusicBrainzArtistResponse? artist = null, + bool includeArtist = true) + { + string? resolvedName = includeName ? name ?? _faker.Name.FullName() : null; + return new MusicBrainzArtistCreditResponse + { + Name = resolvedName, + JoinPhrase = includeJoinPhrase ? joinPhrase ?? _faker.PickRandom(" & ", " feat. ", ", ") : null, + Artist = includeArtist ? artist ?? _musicBrainzArtistResponseFixture.Create(name: resolvedName) : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistResponseFixture.cs new file mode 100644 index 00000000..aac8125e --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistResponseFixture.cs @@ -0,0 +1,124 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzArtistResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzAreaResponseFixture _musicBrainzAreaResponseFixture = new(); + private readonly MusicBrainzAliasResponseFixture _musicBrainzAliasResponseFixture = new(); + private readonly MusicBrainzRelationResponseFixture _musicBrainzRelationResponseFixture = new(); + private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new(); + private readonly MusicBrainzLifeSpanResponseFixture _musicBrainzLifeSpanResponseFixture = new(); + private readonly MusicBrainzRatingResponseFixture _musicBrainzRatingResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the artist. + /// Whether the identifier should be included, or forced to . + /// Optional. The name of the artist. + /// Whether the name should be included, or forced to . + /// Optional. The sort name of the artist. + /// Whether the sort name should be included, or forced to . + /// Optional. The disambiguation comment of the artist. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The MusicBrainz type of the artist. + /// Whether the type should be included, or forced to . + /// Optional. The gender of the artist. + /// Whether the gender should be included, or forced to . + /// Optional. The ISO 3166-1 alpha-2 code of the country of the artist. + /// Whether the country should be included, or forced to . + /// Optional. The area the artist is primarily identified with. + /// Whether the area should be included, or forced to . + /// Optional. The area the artist began in. + /// Whether the begin area should be included, or forced to . + /// Optional. The area the artist ended in. + /// Whether the end area should be included, or forced to . + /// Optional. The life span of the artist. + /// Whether the life span should be included, or forced to . + /// Optional. The ISNI codes of the artist. + /// Optional. The IPI codes of the artist. + /// Optional. The alternative names of the artist. + /// Optional. The tags of the artist. + /// Optional. The genres of the artist. + /// Optional. The relationships of the artist to other entities. + /// Optional. The aggregated rating of the artist. + /// Whether the rating should be included, or forced to . + /// A configured instance. + public MusicBrainzArtistResponse Create( + string? id = null, + bool includeId = true, + string? name = null, + bool includeName = true, + string? sortName = null, + bool includeSortName = true, + string? disambiguation = null, + bool includeDisambiguation = true, + string? type = null, + bool includeType = true, + string? gender = null, + bool includeGender = true, + string? country = null, + bool includeCountry = true, + MusicBrainzAreaResponse? area = null, + bool includeArea = false, + MusicBrainzAreaResponse? beginArea = null, + bool includeBeginArea = false, + MusicBrainzAreaResponse? endArea = null, + bool includeEndArea = false, + MusicBrainzLifeSpanResponse? lifeSpan = null, + bool includeLifeSpan = false, + List? isnis = null, + List? ipis = null, + List? aliases = null, + List? tags = null, + List? genres = null, + List? relations = null, + MusicBrainzRatingResponse? rating = null, + bool includeRating = false) + { + return new MusicBrainzArtistResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Name = includeName ? name ?? _faker.Name.FullName() : null, + SortName = includeSortName ? sortName ?? _faker.Name.FullName() : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + Type = includeType ? type ?? _faker.PickRandom("Person", "Group", "Orchestra") : null, + Gender = includeGender ? gender ?? _faker.PickRandom("Male", "Female") : null, + Country = includeCountry ? country ?? _faker.Address.CountryCode() : null, + Area = includeArea ? area ?? _musicBrainzAreaResponseFixture.Create() : null, + BeginArea = includeBeginArea ? beginArea ?? _musicBrainzAreaResponseFixture.Create() : null, + EndArea = includeEndArea ? endArea ?? _musicBrainzAreaResponseFixture.Create() : null, + LifeSpan = includeLifeSpan ? lifeSpan ?? _musicBrainzLifeSpanResponseFixture.Create() : null, + Isnis = isnis ?? [_faker.Random.String2(16, "0123456789")], + Ipis = ipis ?? [_faker.Random.String2(11, "0123456789")], + Aliases = aliases ?? [.. _musicBrainzAliasResponseFixture.CreateMany(2)], + Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Relations = relations ?? [.. _musicBrainzRelationResponseFixture.CreateMany(2)], + Rating = includeRating ? rating ?? _musicBrainzRatingResponseFixture.Create() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseFixture.cs new file mode 100644 index 00000000..41612d35 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzArtistSearchResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzArtistResponseFixture _musicBrainzArtistResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The total number of matching artists. + /// Optional. The offset of the returned artists. + /// Optional. The matching artists. + /// A configured instance. + public MusicBrainzArtistSearchResponse Create( + int? count = null, + int? offset = null, + List? artists = null) + { + List resolvedArtists = artists ?? [.. _musicBrainzArtistResponseFixture.CreateMany(2)]; + return new MusicBrainzArtistSearchResponse + { + Count = count ?? resolvedArtists.Count, + Offset = offset ?? _faker.Random.Int(0, 100), + Artists = resolvedArtists + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseFixture.cs new file mode 100644 index 00000000..d6e16399 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzLabelInfoResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzLabelResponseFixture _musicBrainzLabelResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The catalog number assigned by the label. + /// Whether the catalog number should be included, or forced to . + /// Optional. The label that issued the release. + /// Whether the label should be included, or forced to . + /// A configured instance. + public MusicBrainzLabelInfoResponse Create( + string? catalogNumber = null, + bool includeCatalogNumber = true, + MusicBrainzLabelResponse? label = null, + bool includeLabel = true) + { + return new MusicBrainzLabelInfoResponse + { + CatalogNumber = includeCatalogNumber ? catalogNumber ?? _faker.Random.AlphaNumeric(8).ToUpperInvariant() : null, + Label = includeLabel ? label ?? _musicBrainzLabelResponseFixture.Create() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelResponseFixture.cs new file mode 100644 index 00000000..438c0390 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelResponseFixture.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzLabelResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the label. + /// Whether the identifier should be included, or forced to . + /// Optional. The name of the label. + /// Whether the name should be included, or forced to . + /// Optional. The disambiguation comment of the label. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The label code of the label. + /// Whether the label code should be included, or forced to . + /// A configured instance. + public MusicBrainzLabelResponse Create( + string? id = null, + bool includeId = true, + string? name = null, + bool includeName = true, + string? disambiguation = null, + bool includeDisambiguation = true, + int? labelCode = null, + bool includeLabelCode = true) + { + return new MusicBrainzLabelResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Name = includeName ? name ?? _faker.Company.CompanyName() : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + LabelCode = includeLabelCode ? labelCode ?? _faker.Random.Int(1, 9999) : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseFixture.cs new file mode 100644 index 00000000..b5bb5346 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseFixture.cs @@ -0,0 +1,55 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzLifeSpanResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The begin date of the life span. + /// Whether the begin date should be included, or forced to . + /// Optional. The end date of the life span. + /// Whether the end date should be included, or forced to . + /// Optional. Whether the life span has ended. + /// Whether the ended flag should be included, or forced to . + /// A configured instance. + public MusicBrainzLifeSpanResponse Create( + string? begin = null, + bool includeBegin = true, + string? end = null, + bool includeEnd = true, + bool? isEnded = null, + bool includeEnded = true) + { + return new MusicBrainzLifeSpanResponse + { + Begin = includeBegin ? begin ?? _faker.Date.Past(60).ToString("yyyy-MM-dd") : null, + End = includeEnd ? end ?? _faker.Date.Past(5).ToString("yyyy-MM-dd") : null, + IsEnded = includeEnded ? isEnded ?? _faker.Random.Bool() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzMediumResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzMediumResponseFixture.cs new file mode 100644 index 00000000..55ca6bf6 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzMediumResponseFixture.cs @@ -0,0 +1,61 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzMediumResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzTrackResponseFixture _musicBrainzTrackResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The position of the medium within its release. + /// Optional. The title of the medium. + /// Whether the title should be included, or forced to . + /// Optional. The format of the medium. + /// Whether the format should be included, or forced to . + /// Optional. The number of tracks of the medium. + /// Optional. The tracks of the medium. + /// A configured instance. + public MusicBrainzMediumResponse Create( + int? position = null, + string? title = null, + bool includeTitle = true, + string? format = null, + bool includeFormat = true, + int? trackCount = null, + List? tracks = null) + { + List resolvedTracks = tracks ?? [.. _musicBrainzTrackResponseFixture.CreateMany(2)]; + return new MusicBrainzMediumResponse + { + Position = position ?? _faker.Random.Int(1, 4), + Title = includeTitle ? title ?? _faker.Lorem.Sentence(2) : null, + Format = includeFormat ? format ?? _faker.PickRandom("CD", "Vinyl", "Digital Media") : null, + TrackCount = trackCount ?? resolvedTracks.Count, + Tracks = resolvedTracks + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(index => Create(position: index + 1))]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRatingResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRatingResponseFixture.cs new file mode 100644 index 00000000..4dd684ff --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRatingResponseFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzRatingResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The average rating value. + /// Whether the value should be included, or forced to . + /// Optional. The number of votes that contributed to the rating. + /// Whether the votes count should be included, or forced to . + /// A configured instance. + public MusicBrainzRatingResponse Create( + decimal? value = null, + bool includeValue = true, + int? votesCount = null, + bool includeVotesCount = true) + { + return new MusicBrainzRatingResponse + { + Value = includeValue ? value ?? _faker.Random.Decimal(1m, 5m) : null, + VotesCount = includeVotesCount ? votesCount ?? _faker.Random.Int(1, 500) : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseFixture.cs new file mode 100644 index 00000000..5556e4e5 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseFixture.cs @@ -0,0 +1,41 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzRecordingListResponseFixture +{ + private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The recordings that carry the looked up ISRC. + /// A configured instance. + public MusicBrainzRecordingListResponse Create(List? recordings = null) + { + return new MusicBrainzRecordingListResponse + { + Recordings = recordings ?? [.. _musicBrainzRecordingResponseFixture.CreateMany(2)] + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseFixture.cs new file mode 100644 index 00000000..07a2e22a --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseFixture.cs @@ -0,0 +1,98 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// The releases of the recording default to an empty list, because a recording embedded in a release does not carry them. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzRecordingResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzArtistCreditResponseFixture _musicBrainzArtistCreditResponseFixture = new(); + private readonly MusicBrainzRelationResponseFixture _musicBrainzRelationResponseFixture = new(); + private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new(); + private readonly MusicBrainzRatingResponseFixture _musicBrainzRatingResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the recording. + /// Whether the identifier should be included, or forced to . + /// Optional. The title of the recording. + /// Whether the title should be included, or forced to . + /// Optional. The disambiguation comment of the recording. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The length of the recording in milliseconds. + /// Whether the length should be included, or forced to . + /// Optional. Whether the recording is a video recording. + /// Whether the video flag should be included, or forced to . + /// Optional. The date the recording was first released. + /// Whether the first release date should be included, or forced to . + /// Optional. The artist credit of the recording. + /// Optional. The ISRCs of the recording. + /// Optional. The releases the recording appears on. + /// Optional. The tags of the recording. + /// Optional. The genres of the recording. + /// Optional. The relationships of the recording to other entities. + /// Optional. The aggregated rating of the recording. + /// Whether the rating should be included, or forced to . + /// A configured instance. + public MusicBrainzRecordingResponse Create( + string? id = null, + bool includeId = true, + string? title = null, + bool includeTitle = true, + string? disambiguation = null, + bool includeDisambiguation = true, + long? length = null, + bool includeLength = true, + bool? isVideo = null, + bool includeVideo = true, + string? firstReleaseDate = null, + bool includeFirstReleaseDate = true, + List? artistCredit = null, + List? isrcs = null, + List? releases = null, + List? tags = null, + List? genres = null, + List? relations = null, + MusicBrainzRatingResponse? rating = null, + bool includeRating = false) + { + return new MusicBrainzRecordingResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Title = includeTitle ? title ?? _faker.Lorem.Sentence(3) : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + Length = includeLength ? length ?? _faker.Random.Long(30_000, 600_000) : null, + IsVideo = includeVideo ? isVideo ?? _faker.Random.Bool() : null, + FirstReleaseDate = includeFirstReleaseDate ? firstReleaseDate ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null, + ArtistCredit = artistCredit ?? [.. _musicBrainzArtistCreditResponseFixture.CreateMany(2)], + Isrcs = isrcs ?? [$"US{_faker.Random.AlphaNumeric(10).ToUpperInvariant()}"], + Releases = releases ?? [], + Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Relations = relations ?? [.. _musicBrainzRelationResponseFixture.CreateMany(2)], + Rating = includeRating ? rating ?? _musicBrainzRatingResponseFixture.Create() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseFixture.cs new file mode 100644 index 00000000..a2f2750f --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzRecordingSearchResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The total number of matching recordings. + /// Optional. The offset of the returned recordings. + /// Optional. The matching recordings. + /// A configured instance. + public MusicBrainzRecordingSearchResponse Create( + int? count = null, + int? offset = null, + List? recordings = null) + { + List resolvedRecordings = recordings ?? [.. _musicBrainzRecordingResponseFixture.CreateMany(2)]; + return new MusicBrainzRecordingSearchResponse + { + Count = count ?? resolvedRecordings.Count, + Offset = offset ?? _faker.Random.Int(0, 100), + Recordings = resolvedRecordings + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRelationResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRelationResponseFixture.cs new file mode 100644 index 00000000..b8e7afea --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRelationResponseFixture.cs @@ -0,0 +1,85 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// The nested artist, work and url targets are optional, because a relation usually targets only one of them. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzRelationResponseFixture +{ + private readonly Faker _faker = new(); + + // The artist and work fixtures each compose a relation fixture of their own, so holding them eagerly here would recurse forever; they are + // therefore created on first use. The URL fixture has no such dependency, so it is held directly. + private readonly Lazy _musicBrainzArtistResponseFixture = new(() => new MusicBrainzArtistResponseFixture()); + private readonly Lazy _musicBrainzWorkResponseFixture = new(() => new MusicBrainzWorkResponseFixture()); + private readonly MusicBrainzUrlResponseFixture _musicBrainzUrlResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The type of the relationship. + /// Whether the type should be included, or forced to . + /// Optional. The MusicBrainz identifier of the type of the relationship. + /// Whether the type identifier should be included, or forced to . + /// Optional. The direction of the relationship. + /// Whether the direction should be included, or forced to . + /// Optional. The type of the entity the relationship targets. + /// Whether the target type should be included, or forced to . + /// Optional. The artist the relationship targets. + /// Whether the artist should be included, or forced to . + /// Optional. The work the relationship targets. + /// Whether the work should be included, or forced to . + /// Optional. The URL the relationship targets. + /// Whether the URL should be included, or forced to . + /// Optional. The attributes of the relationship. + /// A configured instance. + public MusicBrainzRelationResponse Create( + string? type = null, + bool includeType = true, + string? typeId = null, + bool includeTypeId = true, + string? direction = null, + bool includeDirection = true, + string? targetType = null, + bool includeTargetType = true, + MusicBrainzArtistResponse? artist = null, + bool includeArtist = false, + MusicBrainzWorkResponse? work = null, + bool includeWork = false, + MusicBrainzUrlResponse? url = null, + bool includeUrl = false, + List? attributes = null) + { + return new MusicBrainzRelationResponse + { + Type = includeType ? type ?? _faker.PickRandom("producer", "composer", "performer") : null, + TypeId = includeTypeId ? typeId ?? Guid.NewGuid().ToString() : null, + Direction = includeDirection ? direction ?? "backward" : null, + TargetType = includeTargetType ? targetType ?? "artist" : null, + Artist = includeArtist ? artist ?? _musicBrainzArtistResponseFixture.Value.Create() : null, + Work = includeWork ? work ?? _musicBrainzWorkResponseFixture.Value.Create() : null, + Url = includeUrl ? url ?? _musicBrainzUrlResponseFixture.Create() : null, + Attributes = attributes ?? [] + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseFixture.cs new file mode 100644 index 00000000..490996ec --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzReleaseBrowseResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzReleaseResponseFixture _musicBrainzReleaseResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The releases returned by the browse request. + /// Optional. The total number of releases linked to the browsed entity. + /// Optional. The offset of the returned releases. + /// A configured instance. + public MusicBrainzReleaseBrowseResponse Create( + List? releases = null, + int? releaseCount = null, + int? releaseOffset = null) + { + List resolvedReleases = releases ?? [.. _musicBrainzReleaseResponseFixture.CreateMany(2)]; + return new MusicBrainzReleaseBrowseResponse + { + Releases = resolvedReleases, + ReleaseCount = releaseCount ?? resolvedReleases.Count, + ReleaseOffset = releaseOffset ?? _faker.Random.Int(0, 100) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseFixture.cs new file mode 100644 index 00000000..3817e8b9 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzReleaseEventResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzAreaResponseFixture _musicBrainzAreaResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The date of the release event. + /// Whether the date should be included, or forced to . + /// Optional. The area of the release event. + /// Whether the area should be included, or forced to . + /// A configured instance. + public MusicBrainzReleaseEventResponse Create( + string? date = null, + bool includeDate = true, + MusicBrainzAreaResponse? area = null, + bool includeArea = true) + { + return new MusicBrainzReleaseEventResponse + { + Date = includeDate ? date ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null, + Area = includeArea ? area ?? _musicBrainzAreaResponseFixture.Create() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseFixture.cs new file mode 100644 index 00000000..30cf9ff3 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseFixture.cs @@ -0,0 +1,89 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// The releases of the release group default to an empty list, because they are only returned by a dedicated browse request. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzReleaseGroupResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzArtistCreditResponseFixture _musicBrainzArtistCreditResponseFixture = new(); + private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new(); + private readonly MusicBrainzRatingResponseFixture _musicBrainzRatingResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the release group. + /// Whether the identifier should be included, or forced to . + /// Optional. The title of the release group. + /// Whether the title should be included, or forced to . + /// Optional. The disambiguation comment of the release group. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The primary type of the release group. + /// Whether the primary type should be included, or forced to . + /// Optional. The secondary types of the release group. + /// Optional. The date the release group was first released. + /// Whether the first release date should be included, or forced to . + /// Optional. The artist credit of the release group. + /// Optional. The releases of the release group. + /// Optional. The tags of the release group. + /// Optional. The genres of the release group. + /// Optional. The aggregated rating of the release group. + /// Whether the rating should be included, or forced to . + /// A configured instance. + public MusicBrainzReleaseGroupResponse Create( + string? id = null, + bool includeId = true, + string? title = null, + bool includeTitle = true, + string? disambiguation = null, + bool includeDisambiguation = true, + string? primaryType = null, + bool includePrimaryType = true, + List? secondaryTypes = null, + string? firstReleaseDate = null, + bool includeFirstReleaseDate = true, + List? artistCredit = null, + List? releases = null, + List? tags = null, + List? genres = null, + MusicBrainzRatingResponse? rating = null, + bool includeRating = false) + { + return new MusicBrainzReleaseGroupResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Title = includeTitle ? title ?? _faker.Commerce.ProductName() : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + PrimaryType = includePrimaryType ? primaryType ?? _faker.PickRandom("Album", "Single", "EP") : null, + SecondaryTypes = secondaryTypes ?? [], + FirstReleaseDate = includeFirstReleaseDate ? firstReleaseDate ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null, + ArtistCredit = artistCredit ?? [.. _musicBrainzArtistCreditResponseFixture.CreateMany(2)], + Releases = releases ?? [], + Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Rating = includeRating ? rating ?? _musicBrainzRatingResponseFixture.Create() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseFixture.cs new file mode 100644 index 00000000..cb1afb9a --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseFixture.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzReleaseGroupSearchResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzReleaseGroupResponseFixture _musicBrainzReleaseGroupResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The total number of matching release groups. + /// Optional. The offset of the returned release groups. + /// Optional. The matching release groups. + /// A configured instance. + public MusicBrainzReleaseGroupSearchResponse Create( + int? count = null, + int? offset = null, + List? releaseGroups = null) + { + List resolvedReleaseGroups = releaseGroups ?? [.. _musicBrainzReleaseGroupResponseFixture.CreateMany(2)]; + return new MusicBrainzReleaseGroupSearchResponse + { + Count = count ?? resolvedReleaseGroups.Count, + Offset = offset ?? _faker.Random.Int(0, 100), + ReleaseGroups = resolvedReleaseGroups + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseFixture.cs new file mode 100644 index 00000000..11da2c2f --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseFixture.cs @@ -0,0 +1,123 @@ +#region ========================================================================= USING ===================================================================================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzReleaseResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzArtistCreditResponseFixture _musicBrainzArtistCreditResponseFixture = new(); + private readonly MusicBrainzReleaseGroupResponseFixture _musicBrainzReleaseGroupResponseFixture = new(); + private readonly MusicBrainzLabelInfoResponseFixture _musicBrainzLabelInfoResponseFixture = new(); + private readonly MusicBrainzMediumResponseFixture _musicBrainzMediumResponseFixture = new(); + private readonly MusicBrainzReleaseEventResponseFixture _musicBrainzReleaseEventResponseFixture = new(); + private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new(); + private readonly MusicBrainzTextRepresentationResponseFixture _musicBrainzTextRepresentationResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the release. + /// Whether the identifier should be included, or forced to . + /// Optional. The title of the release. + /// Whether the title should be included, or forced to . + /// Optional. The disambiguation comment of the release. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The status of the release. + /// Whether the status should be included, or forced to . + /// Optional. The date the release was issued. + /// Whether the date should be included, or forced to . + /// Optional. The ISO 3166-1 alpha-2 code of the country the release was issued in. + /// Whether the country should be included, or forced to . + /// Optional. The release events of the release. + /// Optional. The barcode of the release. + /// Whether the barcode should be included, or forced to . + /// Optional. The outermost packaging of the release. + /// Whether the packaging should be included, or forced to . + /// Optional. The language and script of the titles of the release. + /// Whether the text representation should be included, or forced to . + /// Optional. The artist credit of the release. + /// Optional. The release group the release belongs to. + /// Whether the release group should be included, or forced to . + /// Optional. The label information of the release. + /// Optional. The media of the release. + /// Optional. The ASIN of the release. + /// Whether the ASIN should be included, or forced to . + /// Optional. The tags of the release. + /// Optional. The genres of the release. + /// Optional. The relationships of the release to other entities. + /// A configured instance. + public MusicBrainzReleaseResponse Create( + string? id = null, + bool includeId = true, + string? title = null, + bool includeTitle = true, + string? disambiguation = null, + bool includeDisambiguation = true, + string? status = null, + bool includeStatus = true, + string? date = null, + bool includeDate = true, + string? country = null, + bool includeCountry = true, + List? releaseEvents = null, + string? barcode = null, + bool includeBarcode = true, + string? packaging = null, + bool includePackaging = true, + MusicBrainzTextRepresentationResponse? textRepresentation = null, + bool includeTextRepresentation = true, + List? artistCredit = null, + MusicBrainzReleaseGroupResponse? releaseGroup = null, + bool includeReleaseGroup = true, + List? labelInfo = null, + List? media = null, + string? asin = null, + bool includeAsin = true, + List? tags = null, + List? genres = null, + List? relations = null) + { + return new MusicBrainzReleaseResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Title = includeTitle ? title ?? _faker.Commerce.ProductName() : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + Status = includeStatus ? status ?? _faker.PickRandom("Official", "Promotion", "Bootleg") : null, + Date = includeDate ? date ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null, + Country = includeCountry ? country ?? _faker.Address.CountryCode() : null, + ReleaseEvents = releaseEvents ?? [.. _musicBrainzReleaseEventResponseFixture.CreateMany(1)], + Barcode = includeBarcode ? barcode ?? _faker.Random.AlphaNumeric(12) : null, + Packaging = includePackaging ? packaging ?? _faker.PickRandom("Jewel Case", "Digipak") : null, + TextRepresentation = includeTextRepresentation ? textRepresentation ?? _musicBrainzTextRepresentationResponseFixture.Create() : null, + ArtistCredit = artistCredit ?? [.. _musicBrainzArtistCreditResponseFixture.CreateMany(2)], + ReleaseGroup = includeReleaseGroup ? releaseGroup ?? _musicBrainzReleaseGroupResponseFixture.Create() : null, + LabelInfo = labelInfo ?? [.. _musicBrainzLabelInfoResponseFixture.CreateMany(1)], + Media = media ?? [.. _musicBrainzMediumResponseFixture.CreateMany(1)], + Asin = includeAsin ? asin ?? _faker.Random.AlphaNumeric(10) : null, + Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Relations = relations ?? [] + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTagResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTagResponseFixture.cs new file mode 100644 index 00000000..d3eb53cc --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTagResponseFixture.cs @@ -0,0 +1,58 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzTagResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of a genre tag. + /// Whether the identifier should be included, or forced to . + /// Optional. The name of the tag. + /// Whether the name should be included, or forced to . + /// Optional. The disambiguation comment of a genre tag. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The number of votes the tag received. + /// A configured instance. + public MusicBrainzTagResponse Create( + string? id = null, + bool includeId = true, + string? name = null, + bool includeName = true, + string? disambiguation = null, + bool includeDisambiguation = true, + int? count = null) + { + return new MusicBrainzTagResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Name = includeName ? name ?? _faker.Lorem.Word() : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + Count = count ?? _faker.Random.Int(0, 100) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseFixture.cs new file mode 100644 index 00000000..68787c3b --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzTextRepresentationResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The ISO 639-3 language code of the release. + /// Whether the language should be included, or forced to . + /// Optional. The ISO 15924 script code of the release. + /// Whether the script should be included, or forced to . + /// A configured instance. + public MusicBrainzTextRepresentationResponse Create( + string? language = null, + bool includeLanguage = true, + string? script = null, + bool includeScript = true) + { + return new MusicBrainzTextRepresentationResponse + { + Language = includeLanguage ? language ?? _faker.PickRandom("eng", "deu", "fra") : null, + Script = includeScript ? script ?? _faker.PickRandom("Latn", "Cyrl", "Arab") : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTrackResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTrackResponseFixture.cs new file mode 100644 index 00000000..745a2db1 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTrackResponseFixture.cs @@ -0,0 +1,71 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzTrackResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the track. + /// Whether the identifier should be included, or forced to . + /// Optional. The track number, as displayed on the medium. + /// Whether the number should be included, or forced to . + /// Optional. The position of the track within its medium. + /// Optional. The title of the track. + /// Whether the title should be included, or forced to . + /// Optional. The length of the track in milliseconds. + /// Whether the length should be included, or forced to . + /// Optional. The recording the track is a performance of. + /// Whether the recording should be included, or forced to . + /// A configured instance. + public MusicBrainzTrackResponse Create( + string? id = null, + bool includeId = true, + string? number = null, + bool includeNumber = true, + int? position = null, + string? title = null, + bool includeTitle = true, + long? length = null, + bool includeLength = true, + MusicBrainzRecordingResponse? recording = null, + bool includeRecording = true) + { + int resolvedPosition = position ?? _faker.Random.Int(1, 30); + string? resolvedTitle = includeTitle ? title ?? _faker.Lorem.Sentence(3) : null; + return new MusicBrainzTrackResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Number = includeNumber ? number ?? resolvedPosition.ToString() : null, + Position = resolvedPosition, + Title = resolvedTitle, + Length = includeLength ? length ?? _faker.Random.Long(30_000, 600_000) : null, + Recording = includeRecording ? recording ?? _musicBrainzRecordingResponseFixture.Create(title: resolvedTitle) : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(index => Create(position: index + 1))]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzUrlResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzUrlResponseFixture.cs new file mode 100644 index 00000000..08602a9b --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzUrlResponseFixture.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzUrlResponseFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the URL. + /// Whether the identifier should be included, or forced to . + /// Optional. The resource the URL points to. + /// Whether the resource should be included, or forced to . + /// A configured instance. + public MusicBrainzUrlResponse Create( + string? id = null, + bool includeId = true, + string? resource = null, + bool includeResource = true) + { + return new MusicBrainzUrlResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Resource = includeResource ? resource ?? _faker.Internet.Url() : null + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzWorkResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzWorkResponseFixture.cs new file mode 100644 index 00000000..09311696 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzWorkResponseFixture.cs @@ -0,0 +1,77 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; + +/// +/// Fixture class for the record. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzWorkResponseFixture +{ + private readonly Faker _faker = new(); + private readonly MusicBrainzRelationResponseFixture _musicBrainzRelationResponseFixture = new(); + private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The MusicBrainz identifier of the work. + /// Whether the identifier should be included, or forced to . + /// Optional. The title of the work. + /// Whether the title should be included, or forced to . + /// Optional. The MusicBrainz type of the work. + /// Whether the type should be included, or forced to . + /// Optional. The disambiguation comment of the work. + /// Whether the disambiguation should be included, or forced to . + /// Optional. The languages of the work. + /// Optional. The ISWCs of the work. + /// Optional. The relationships of the work to other entities. + /// Optional. The tags of the work. + /// Optional. The genres of the work. + /// A configured instance. + public MusicBrainzWorkResponse Create( + string? id = null, + bool includeId = true, + string? title = null, + bool includeTitle = true, + string? type = null, + bool includeType = true, + string? disambiguation = null, + bool includeDisambiguation = true, + List? languages = null, + List? iswcs = null, + List? relations = null, + List? tags = null, + List? genres = null) + { + return new MusicBrainzWorkResponse + { + Id = includeId ? id ?? Guid.NewGuid().ToString() : null, + Title = includeTitle ? title ?? _faker.Lorem.Sentence(3) : null, + Type = includeType ? type ?? _faker.PickRandom("Song", "Aria", "Symphony") : null, + Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null, + Languages = languages ?? [_faker.PickRandom("eng", "deu", "fra")], + Iswcs = iswcs ?? [$"T-{_faker.Random.Int(100, 999)}.{_faker.Random.Int(100, 999)}.{_faker.Random.Int(100, 999)}-{_faker.Random.Int(1, 9)}"], + Relations = relations ?? [.. _musicBrainzRelationResponseFixture.CreateMany(2)], + Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)], + Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)] + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/DTO/Settings/MusicBrainzSettingsDtoFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/DTO/Settings/MusicBrainzSettingsDtoFixture.cs new file mode 100644 index 00000000..c1b2abae --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/DTO/Settings/MusicBrainzSettingsDtoFixture.cs @@ -0,0 +1,63 @@ +#region ========================================================================= USING ===================================================================================== +using Bogus; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings; + +/// +/// Fixture class for the class. +/// +[ExcludeFromCodeCoverage] +internal sealed class MusicBrainzSettingsDtoFixture +{ + private readonly Faker _faker = new(); + + /// + /// Creates a new instance with randomized test data. + /// + /// Optional. The base URL of the MusicBrainz web service. + /// Optional. Whether the base URL may point at a private or local host. + /// Optional. The user agent sent with every request. + /// Optional. The contact email sent to the MusicBrainz API. + /// Whether the contact email should be included, or forced to . + /// Optional. The maximum number of results returned by a single search. + /// Optional. The maximum number of releases fetched for a single release group. + /// Optional. The minimum interval between consecutive requests. + /// A configured instance. + public MusicBrainzSettingsDto Create( + string? baseUrl = null, + bool? doesAllowPrivateBaseUrl = null, + string? userAgent = null, + string? contactEmail = null, + bool includeContactEmail = true, + int? searchResultLimit = null, + int? releaseLookupLimit = null, + TimeSpan? minimumRequestInterval = null) + { + return new MusicBrainzSettingsDto + { + BaseUrl = baseUrl ?? _faker.Internet.Url(), + DoesAllowPrivateBaseUrl = doesAllowPrivateBaseUrl ?? _faker.Random.Bool(), + UserAgent = userAgent ?? $"Lumina-MusicBrainz/{_faker.Random.Int(1, 9)}.{_faker.Random.Int(0, 9)}", + ContactEmail = includeContactEmail ? contactEmail ?? _faker.Internet.Email() : null, + SearchResultLimit = searchResultLimit ?? _faker.Random.Int(1, 100), + ReleaseLookupLimit = releaseLookupLimit ?? _faker.Random.Int(1, 100), + MinimumRequestInterval = minimumRequestInterval ?? TimeSpan.FromSeconds(_faker.Random.Double(0, 5)) + }; + } + + /// + /// Creates multiple instances with randomized test data. + /// + /// Number of instances to create. + /// List of configured instances. + public List CreateMany(int count = 3) + { + return [.. Enumerable.Range(0, count).Select(_ => Create())]; + } +} diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Lumina.Plugins.MusicBrainz.Fixtures.csproj b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Lumina.Plugins.MusicBrainz.Fixtures.csproj new file mode 100644 index 00000000..e07d39a7 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Lumina.Plugins.MusicBrainz.Fixtures.csproj @@ -0,0 +1,25 @@ + + + + net10.0 + disable + enable + $(SolutionDir)..\bin\api\ + + false + false + false + + + + + + + + + + + + + + diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..7f795b30 --- /dev/null +++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Properties/AssemblyInfo.cs @@ -0,0 +1,22 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Lumina.Plugins.MusicBrainz.Fixtures")] +[assembly: AssemblyProduct("Lumina.Plugins.MusicBrainz.Fixtures")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72")] + +[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.UnitTests")] +[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.IntegrationTests")] +[assembly: InternalsVisibleTo("Lumina.Presentation.Api.SecurityTests")] +[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/DependencyInjection/MusicBrainzServicesTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/DependencyInjection/MusicBrainzServicesTests.cs new file mode 100644 index 00000000..cb5dca74 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/DependencyInjection/MusicBrainzServicesTests.cs @@ -0,0 +1,147 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.MusicBrainz.Common.DependencyInjection; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.Core; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.DependencyInjection; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzServicesTests +{ + [Fact] + public void AddMusicBrainzMetadataProviders_WhenServicesIsNull_ShouldThrowArgumentNullException() + { + // Arrange + IServiceCollection services = null!; + + // Act + Action act = () => services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid()); + + // Assert + Assert.Throws(act); + } + + [Fact] + public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldReturnTheSameServiceCollection() + { + // Arrange + ServiceCollection services = new(); + + // Act + IServiceCollection result = services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid()); + + // Assert + Assert.Same(services, result); + } + + [Fact] + public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheThreeMetadataProvidersForKeyedResolution() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddMusicBrainzMetadataProviders(pluginId: pluginId); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.Equal(3, serviceProvider.GetKeyedServices(pluginId).Count()); + Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid())); + } + + [Fact] + public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheSettingsProviderAsScoped() + { + // Arrange + ServiceCollection services = new(); + + // Act + services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid()); + + // Assert + ServiceDescriptor settingsProviderDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzSettingsProvider)); + Assert.Equal(ServiceLifetime.Scoped, settingsProviderDescriptor.Lifetime); + } + + [Fact] + public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheThrottleAndTheResponseCacheAsSingletons() + { + // Arrange + ServiceCollection services = new(); + + // Act + services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid()); + + // Assert + ServiceDescriptor throttleDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzRequestThrottle)); + ServiceDescriptor responseCacheDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzResponseCache)); + Assert.Equal(ServiceLifetime.Singleton, throttleDescriptor.Lifetime); + Assert.Equal(ServiceLifetime.Singleton, responseCacheDescriptor.Lifetime); + } + + [Fact] + public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheHttpClient() + { + // Arrange + ServiceCollection services = new(); + + // Act + services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid()); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.NotNull(serviceProvider.GetService()); + } + + [Fact] + public async Task AddMusicBrainzMetadataProviders_WhenASettingsCallbackIsProvided_ShouldApplyItToTheDefaults() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddMusicBrainzMetadataProviders(pluginId: pluginId, settings => settings.BaseUrl = "http://custom.example/ws/2/"); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + using (IServiceScope scope = serviceProvider.CreateScope()) + { + MusicBrainzSettingsProvider settingsProvider = scope.ServiceProvider.GetRequiredService(); + MusicBrainzSettingsDto settings = await settingsProvider.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("http://custom.example/ws/2/", settings.BaseUrl); + } + } + + [Fact] + public void AddMusicBrainzMetadataProviders_WhenCalledTwice_ShouldNotDuplicateTheTryAddServices() + { + // Arrange + Guid pluginId = Guid.NewGuid(); + ServiceCollection services = new(); + + // Act + services.AddMusicBrainzMetadataProviders(pluginId: pluginId); + services.AddMusicBrainzMetadataProviders(pluginId: pluginId); + + // Assert + // The settings provider, the throttle and the response cache are registered with TryAdd, so a second call must not add them again. + Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzRequestThrottle)); + Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzResponseCache)); + Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzSettingsProvider)); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAliasResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAliasResponseTests.cs new file mode 100644 index 00000000..6be62d2e --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAliasResponseTests.cs @@ -0,0 +1,75 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzAliasResponseTests +{ + [Fact] + public void IsEnded_WhenTheMusicBrainzApiReturnsNull_ShouldDeserializeAsNull() + { + // Arrange + // the MusicBrainz search API can return a null ended flag for aliases, which used to break deserialization into a non-nullable boolean + const string JSON = """{"name":"Rammstein","ended":null}"""; + + // Act + MusicBrainzAliasResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Null(response.IsEnded); + } + + [Fact] + public void IsEnded_WhenTheMusicBrainzApiReturnsTrue_ShouldDeserializeAsTrue() + { + // Arrange + const string JSON = """{"name":"Rammstein","ended":true}"""; + + // Act + MusicBrainzAliasResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.True(response.IsEnded); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "name": "Alias Name", + "sort-name": "Alias Sort Name", + "type": "Artist name", + "locale": "en", + "primary": true, + "begin": "1994-01-01", + "end": "2020-12-31", + "ended": true + } + """; + + // Act + MusicBrainzAliasResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("Alias Name", response.Name); + Assert.Equal("Alias Sort Name", response.SortName); + Assert.Equal("Artist name", response.Type); + Assert.Equal("en", response.Locale); + Assert.True(response.IsPrimary); + Assert.Equal("1994-01-01", response.Begin); + Assert.Equal("2020-12-31", response.End); + Assert.True(response.IsEnded); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAreaResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAreaResponseTests.cs new file mode 100644 index 00000000..d5f084a6 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAreaResponseTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzAreaResponseTests +{ + [Fact] + public void SortNameTypeAndIsoCodes_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """ + { + "id": "c0e0e0e0-0000-0000-0000-000000000000", + "name": "United Kingdom", + "sort-name": "United Kingdom", + "type": "Country", + "iso-3166-1-codes": [ "GB" ], + "iso-3166-2-codes": [ "GB-ENG" ] + } + """; + + // Act + MusicBrainzAreaResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("United Kingdom", response.SortName); + Assert.Equal("Country", response.Type); + Assert.Equal("GB", Assert.Single(response.Iso3166Part1Codes)); + Assert.Equal("GB-ENG", Assert.Single(response.Iso3166Part2Codes)); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "area-id", + "name": "United Kingdom", + "sort-name": "United Kingdom", + "disambiguation": "The United Kingdom of Great Britain", + "type": "Country", + "iso-3166-1-codes": [ "GB" ], + "iso-3166-2-codes": [ "GB-ENG" ] + } + """; + + // Act + MusicBrainzAreaResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("area-id", response.Id); + Assert.Equal("United Kingdom", response.Name); + Assert.Equal("United Kingdom", response.SortName); + Assert.Equal("The United Kingdom of Great Britain", response.Disambiguation); + Assert.Equal("Country", response.Type); + Assert.Equal("GB", Assert.Single(response.Iso3166Part1Codes)); + Assert.Equal("GB-ENG", Assert.Single(response.Iso3166Part2Codes)); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseTests.cs new file mode 100644 index 00000000..72083a42 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzArtistCreditResponseTests +{ + [Fact] + public void NameJoinPhraseAndArtist_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"name":"Freddie Mercury","joinphrase":" & ","artist":{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","name":"Freddie Mercury"}}"""; + + // Act + MusicBrainzArtistCreditResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("Freddie Mercury", response.Name); + Assert.Equal(" & ", response.JoinPhrase); + Assert.NotNull(response.Artist); + Assert.Equal("Freddie Mercury", response.Artist.Name); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "name": "Freddie Mercury", + "joinphrase": " & ", + "artist": { "id": "artist-id", "name": "Freddie Mercury" } + } + """; + + // Act + MusicBrainzArtistCreditResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("Freddie Mercury", response.Name); + Assert.Equal(" & ", response.JoinPhrase); + Assert.NotNull(response.Artist); + Assert.Equal("artist-id", response.Artist.Id); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistResponseTests.cs new file mode 100644 index 00000000..70353349 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistResponseTests.cs @@ -0,0 +1,103 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzArtistResponseTests +{ + [Fact] + public void SortNameTypeCountryAndCodes_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """ + { + "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", + "name": "Queen", + "sort-name": "Queen", + "type": "Group", + "gender": null, + "country": "GB", + "life-span": { "begin": "1970", "ended": false }, + "ipis": [ "00000000000" ], + "isnis": [ "0000000000000000" ] + } + """; + + // Act + MusicBrainzArtistResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("Queen", response.SortName); + Assert.Equal("Group", response.Type); + Assert.Equal("GB", response.Country); + Assert.Equal("00000000000", Assert.Single(response.Ipis)); + Assert.Equal("0000000000000000", Assert.Single(response.Isnis)); + Assert.NotNull(response.LifeSpan); + Assert.Equal("1970", response.LifeSpan.Begin); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "artist-id", + "name": "Queen", + "sort-name": "Queen", + "disambiguation": "UK rock band", + "type": "Group", + "gender": "Male", + "country": "GB", + "area": { "id": "area-id", "name": "United Kingdom" }, + "begin-area": { "id": "begin-area-id", "name": "London" }, + "end-area": { "id": "end-area-id", "name": "Montreux" }, + "life-span": { "begin": "1970", "end": "1991", "ended": true }, + "isnis": [ "isni-1" ], + "ipis": [ "ipi-1" ], + "aliases": [ { "name": "Queen alias" } ], + "tags": [ { "name": "rock", "count": 5 } ], + "genres": [ { "id": "genre-id", "name": "Rock" } ], + "relations": [ { "type": "member of band", "artist": { "id": "member-id", "name": "Freddie Mercury" } } ], + "rating": { "value": 4.5, "votes-count": 10 } + } + """; + + // Act + MusicBrainzArtistResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("artist-id", response.Id); + Assert.Equal("Queen", response.Name); + Assert.Equal("Queen", response.SortName); + Assert.Equal("UK rock band", response.Disambiguation); + Assert.Equal("Group", response.Type); + Assert.Equal("Male", response.Gender); + Assert.Equal("GB", response.Country); + Assert.NotNull(response.Area); + Assert.Equal("United Kingdom", response.Area.Name); + Assert.NotNull(response.BeginArea); + Assert.Equal("London", response.BeginArea.Name); + Assert.NotNull(response.EndArea); + Assert.Equal("Montreux", response.EndArea.Name); + Assert.NotNull(response.LifeSpan); + Assert.Equal("1970", response.LifeSpan.Begin); + Assert.Equal("isni-1", Assert.Single(response.Isnis)); + Assert.Equal("ipi-1", Assert.Single(response.Ipis)); + Assert.Equal("Queen alias", Assert.Single(response.Aliases).Name); + Assert.Equal("rock", Assert.Single(response.Tags).Name); + Assert.Equal("Rock", Assert.Single(response.Genres).Name); + Assert.Equal("member of band", Assert.Single(response.Relations).Type); + Assert.NotNull(response.Rating); + Assert.Equal(4.5m, response.Rating.Value); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseTests.cs new file mode 100644 index 00000000..67f8f072 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzArtistSearchResponseTests +{ + [Fact] + public void CountOffsetAndArtists_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"count":1,"offset":0,"artists":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","name":"Queen"}]}"""; + + // Act + MusicBrainzArtistSearchResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(1, response.Count); + Assert.Equal(0, response.Offset); + Assert.Equal("Queen", Assert.Single(response.Artists).Name); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "count": 2, + "offset": 1, + "artists": [ { "id": "artist-id", "name": "Queen" } ] + } + """; + + // Act + MusicBrainzArtistSearchResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(2, response.Count); + Assert.Equal(1, response.Offset); + Assert.Equal("artist-id", Assert.Single(response.Artists).Id); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseTests.cs new file mode 100644 index 00000000..a3400d05 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseTests.cs @@ -0,0 +1,51 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzLabelInfoResponseTests +{ + [Fact] + public void CatalogNumberAndLabel_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"catalog-number":"EMC 4008","label":{"id":"f0e0e0e0-0000-0000-0000-000000000000","name":"EMI"}}"""; + + // Act + MusicBrainzLabelInfoResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("EMC 4008", response.CatalogNumber); + Assert.NotNull(response.Label); + Assert.Equal("EMI", response.Label.Name); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "catalog-number": "EMC 4008", + "label": { "id": "label-id", "name": "EMI" } + } + """; + + // Act + MusicBrainzLabelInfoResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("EMC 4008", response.CatalogNumber); + Assert.NotNull(response.Label); + Assert.Equal("EMI", response.Label.Name); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelResponseTests.cs new file mode 100644 index 00000000..71b21dc3 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelResponseTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzLabelResponseTests +{ + [Fact] + public void NameDisambiguationAndLabelCode_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"id":"f0e0e0e0-0000-0000-0000-000000000000","name":"EMI","disambiguation":"EMI Records Ltd.","label-code":1234}"""; + + // Act + MusicBrainzLabelResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("EMI", response.Name); + Assert.Equal("EMI Records Ltd.", response.Disambiguation); + Assert.Equal(1234, response.LabelCode); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "label-id", + "name": "EMI", + "disambiguation": "EMI Records Ltd.", + "label-code": 1234 + } + """; + + // Act + MusicBrainzLabelResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("label-id", response.Id); + Assert.Equal("EMI", response.Name); + Assert.Equal("EMI Records Ltd.", response.Disambiguation); + Assert.Equal(1234, response.LabelCode); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseTests.cs new file mode 100644 index 00000000..38ee4e0c --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseTests.cs @@ -0,0 +1,65 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzLifeSpanResponseTests +{ + [Fact] + public void IsEnded_WhenTheMusicBrainzApiReturnsNull_ShouldDeserializeAsNull() + { + // Arrange + // the MusicBrainz search API returns a null ended flag for artists whose end status is unknown, which used to break deserialization into a non-nullable boolean + const string JSON = """{"begin":"1994-01","ended":null}"""; + + // Act + MusicBrainzLifeSpanResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Null(response.IsEnded); + } + + [Fact] + public void IsEnded_WhenTheMusicBrainzApiReturnsTrue_ShouldDeserializeAsTrue() + { + // Arrange + const string JSON = """{"begin":"1970-06-27","ended":true}"""; + + // Act + MusicBrainzLifeSpanResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.True(response.IsEnded); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "begin": "1970-06-27", + "end": "1991-11-24", + "ended": true + } + """; + + // Act + MusicBrainzLifeSpanResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("1970-06-27", response.Begin); + Assert.Equal("1991-11-24", response.End); + Assert.True(response.IsEnded); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzMediumResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzMediumResponseTests.cs new file mode 100644 index 00000000..1c8ebda1 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzMediumResponseTests.cs @@ -0,0 +1,57 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzMediumResponseTests +{ + [Fact] + public void PositionFormatAndTrackCount_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"position":1,"title":"Disc 1","format":"CD","track-count":12}"""; + + // Act + MusicBrainzMediumResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(1, response.Position); + Assert.Equal("Disc 1", response.Title); + Assert.Equal("CD", response.Format); + Assert.Equal(12, response.TrackCount); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "position": 2, + "title": "Disc 2", + "format": "Vinyl", + "track-count": 8, + "tracks": [ { "id": "track-id", "number": "A1", "position": 1, "title": "Death on Two Legs" } ] + } + """; + + // Act + MusicBrainzMediumResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(2, response.Position); + Assert.Equal("Disc 2", response.Title); + Assert.Equal("Vinyl", response.Format); + Assert.Equal(8, response.TrackCount); + Assert.Equal("track-id", Assert.Single(response.Tracks).Id); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRatingResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRatingResponseTests.cs new file mode 100644 index 00000000..675a12a2 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRatingResponseTests.cs @@ -0,0 +1,66 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzRatingResponseTests +{ + private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web) + { + NumberHandling = JsonNumberHandling.AllowReadingFromString + }; + + [Fact] + public void ValueAndVotesCount_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"value":4.5,"votes-count":10}"""; + + // Act + MusicBrainzRatingResponse? response = JsonSerializer.Deserialize(JSON, s_serializerOptions); + + // Assert + Assert.NotNull(response); + Assert.Equal(4.5m, response.Value); + Assert.Equal(10, response.VotesCount); + } + + [Fact] + public void ValueAndVotesCount_WhenTheMusicBrainzApiReturnsStrings_ShouldStillDeserializeThem() + { + // Arrange + // The MusicBrainz search API sometimes returns the rating numbers as strings. + const string JSON = """{"value":"4.5","votes-count":"10"}"""; + + // Act + MusicBrainzRatingResponse? response = JsonSerializer.Deserialize(JSON, s_serializerOptions); + + // Assert + Assert.NotNull(response); + Assert.Equal(4.5m, response.Value); + Assert.Equal(10, response.VotesCount); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """{"value":4.5,"votes-count":10}"""; + + // Act + MusicBrainzRatingResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(4.5m, response.Value); + Assert.Equal(10, response.VotesCount); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseTests.cs new file mode 100644 index 00000000..195f7f68 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseTests.cs @@ -0,0 +1,50 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzRecordingListResponseTests +{ + [Fact] + public void Recordings_WhenReturnedByTheMusicBrainzIsrcLookup_ShouldDeserialize() + { + // Arrange + const string JSON = """{"recordings":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs","isrcs":["GBUM71029604"]}]}"""; + + // Act + MusicBrainzRecordingListResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + MusicBrainzRecordingResponse recording = Assert.Single(response.Recordings); + Assert.Equal("Death on Two Legs", recording.Title); + Assert.Equal("GBUM71029604", Assert.Single(recording.Isrcs)); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "recordings": [ { "id": "recording-id", "title": "Death on Two Legs", "isrcs": [ "GBUM71029604" ] } ] + } + """; + + // Act + MusicBrainzRecordingListResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + MusicBrainzRecordingResponse recording = Assert.Single(response.Recordings); + Assert.Equal("recording-id", recording.Id); + Assert.Equal("Death on Two Legs", recording.Title); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseTests.cs new file mode 100644 index 00000000..857e7fe7 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseTests.cs @@ -0,0 +1,86 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzRecordingResponseTests +{ + [Fact] + public void IsVideo_WhenTheMusicBrainzApiReturnsNull_ShouldDeserializeAsNull() + { + // Arrange + // The MusicBrainz search API returns a null video flag for most recordings, which used to break deserialization into a non-nullable boolean. + const string JSON = """{"id":"8778bb30-2f72-4bc8-8b71-cdbe084036c3","title":"A Kind of Magic","video":null}"""; + + // Act + MusicBrainzRecordingResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Null(response.IsVideo); + } + + [Fact] + public void IsVideo_WhenTheMusicBrainzApiReturnsFalse_ShouldDeserializeAsFalse() + { + // Arrange + const string JSON = """{"id":"8778bb30-2f72-4bc8-8b71-cdbe084036c3","title":"A Kind of Magic","video":false}"""; + + // Act + MusicBrainzRecordingResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.False(response.IsVideo); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "recording-id", + "title": "Bohemian Rhapsody", + "disambiguation": "album version", + "length": 354000, + "video": true, + "first-release-date": "1975-10-31", + "artist-credit": [ { "name": "Queen", "artist": { "id": "artist-id", "name": "Queen" } } ], + "isrcs": [ "GBUM71029604" ], + "releases": [ { "id": "release-id", "title": "A Night at the Opera" } ], + "tags": [ { "name": "rock", "count": 5 } ], + "genres": [ { "id": "genre-id", "name": "Rock" } ], + "relations": [ { "type": "performance", "work": { "id": "work-id", "title": "Bohemian Rhapsody" } } ], + "rating": { "value": 4.5, "votes-count": 10 } + } + """; + + // Act + MusicBrainzRecordingResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("recording-id", response.Id); + Assert.Equal("Bohemian Rhapsody", response.Title); + Assert.Equal("album version", response.Disambiguation); + Assert.Equal(354000, response.Length); + Assert.True(response.IsVideo); + Assert.Equal("1975-10-31", response.FirstReleaseDate); + Assert.Equal("Queen", Assert.Single(response.ArtistCredit).Name); + Assert.Equal("GBUM71029604", Assert.Single(response.Isrcs)); + Assert.Equal("release-id", Assert.Single(response.Releases).Id); + Assert.Equal("rock", Assert.Single(response.Tags).Name); + Assert.Equal("Rock", Assert.Single(response.Genres).Name); + Assert.Equal("performance", Assert.Single(response.Relations).Type); + Assert.NotNull(response.Rating); + Assert.Equal(4.5m, response.Rating.Value); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseTests.cs new file mode 100644 index 00000000..b9ebb79d --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzRecordingSearchResponseTests +{ + [Fact] + public void CountOffsetAndRecordings_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"count":1,"offset":0,"recordings":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs"}]}"""; + + // Act + MusicBrainzRecordingSearchResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(1, response.Count); + Assert.Equal(0, response.Offset); + Assert.Equal("Death on Two Legs", Assert.Single(response.Recordings).Title); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "count": 3, + "offset": 2, + "recordings": [ { "id": "recording-id", "title": "Death on Two Legs" } ] + } + """; + + // Act + MusicBrainzRecordingSearchResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(3, response.Count); + Assert.Equal(2, response.Offset); + Assert.Equal("recording-id", Assert.Single(response.Recordings).Id); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRelationResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRelationResponseTests.cs new file mode 100644 index 00000000..08e90b41 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRelationResponseTests.cs @@ -0,0 +1,77 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzRelationResponseTests +{ + [Fact] + public void TypeTargetTypeArtistAndAttributes_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """ + { + "type": "producer", + "type-id": "d0e0e0e0-0000-0000-0000-000000000000", + "direction": "backward", + "target-type": "artist", + "artist": { "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", "name": "Roy Thomas Baker" }, + "attributes": [ "producer" ] + } + """; + + // Act + MusicBrainzRelationResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("producer", response.Type); + Assert.Equal("backward", response.Direction); + Assert.Equal("artist", response.TargetType); + Assert.NotNull(response.Artist); + Assert.Equal("Roy Thomas Baker", response.Artist.Name); + Assert.Equal("producer", Assert.Single(response.Attributes)); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "type": "producer", + "type-id": "type-id", + "direction": "backward", + "target-type": "artist", + "artist": { "id": "artist-id", "name": "Roy Thomas Baker" }, + "work": { "id": "work-id", "title": "Bohemian Rhapsody" }, + "url": { "id": "url-id", "resource": "https://example.com/" }, + "attributes": [ "producer" ] + } + """; + + // Act + MusicBrainzRelationResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("producer", response.Type); + Assert.Equal("type-id", response.TypeId); + Assert.Equal("backward", response.Direction); + Assert.Equal("artist", response.TargetType); + Assert.NotNull(response.Artist); + Assert.Equal("Roy Thomas Baker", response.Artist.Name); + Assert.NotNull(response.Work); + Assert.Equal("Bohemian Rhapsody", response.Work.Title); + Assert.NotNull(response.Url); + Assert.Equal("https://example.com/", response.Url.Resource); + Assert.Equal("producer", Assert.Single(response.Attributes)); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseTests.cs new file mode 100644 index 00000000..4f4a5711 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzReleaseBrowseResponseTests +{ + [Fact] + public void ReleaseCountReleaseOffsetAndReleases_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"release-count":5,"release-offset":2,"releases":[{"id":"11111111-1111-1111-1111-111111111111","title":"A Night at the Opera"}]}"""; + + // Act + MusicBrainzReleaseBrowseResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(5, response.ReleaseCount); + Assert.Equal(2, response.ReleaseOffset); + Assert.Equal("A Night at the Opera", Assert.Single(response.Releases).Title); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "releases": [ { "id": "release-id", "title": "A Night at the Opera" } ], + "release-count": 5, + "release-offset": 2 + } + """; + + // Act + MusicBrainzReleaseBrowseResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("release-id", Assert.Single(response.Releases).Id); + Assert.Equal(5, response.ReleaseCount); + Assert.Equal(2, response.ReleaseOffset); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseTests.cs new file mode 100644 index 00000000..4d594ba5 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzReleaseEventResponseTests +{ + [Fact] + public void DateAndArea_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"date":"1975-11-21","area":{"id":"c0e0e0e0-0000-0000-0000-000000000000","name":"United Kingdom","iso-3166-1-codes":["GB"]}}"""; + + // Act + MusicBrainzReleaseEventResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("1975-11-21", response.Date); + Assert.NotNull(response.Area); + Assert.Equal("United Kingdom", response.Area.Name); + Assert.Equal("GB", Assert.Single(response.Area.Iso3166Part1Codes)); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "date": "1975-11-21", + "area": { "id": "area-id", "name": "United Kingdom" } + } + """; + + // Act + MusicBrainzReleaseEventResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("1975-11-21", response.Date); + Assert.NotNull(response.Area); + Assert.Equal("area-id", response.Area.Id); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseTests.cs new file mode 100644 index 00000000..39a0ce75 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseTests.cs @@ -0,0 +1,79 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzReleaseGroupResponseTests +{ + [Fact] + public void PrimaryTypeSecondaryTypesAndFirstReleaseDate_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """ + { + "id": "22222222-2222-2222-2222-222222222222", + "title": "A Night at the Opera", + "primary-type": "Album", + "secondary-types": [ "Live" ], + "first-release-date": "1975-11-21", + "artist-credit": [ { "name": "Queen", "artist": { "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35" } } ] + } + """; + + // Act + MusicBrainzReleaseGroupResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("Album", response.PrimaryType); + Assert.Equal("Live", Assert.Single(response.SecondaryTypes)); + Assert.Equal("1975-11-21", response.FirstReleaseDate); + Assert.Equal("Queen", Assert.Single(response.ArtistCredit).Name); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "release-group-id", + "title": "A Night at the Opera", + "disambiguation": "1975 album", + "primary-type": "Album", + "secondary-types": [ "Live" ], + "first-release-date": "1975-11-21", + "artist-credit": [ { "name": "Queen", "artist": { "id": "artist-id" } } ], + "releases": [ { "id": "release-id", "title": "A Night at the Opera" } ], + "tags": [ { "name": "rock", "count": 5 } ], + "genres": [ { "id": "genre-id", "name": "Rock" } ], + "rating": { "value": 4.5, "votes-count": 10 } + } + """; + + // Act + MusicBrainzReleaseGroupResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("release-group-id", response.Id); + Assert.Equal("A Night at the Opera", response.Title); + Assert.Equal("1975 album", response.Disambiguation); + Assert.Equal("Album", response.PrimaryType); + Assert.Equal("Live", Assert.Single(response.SecondaryTypes)); + Assert.Equal("1975-11-21", response.FirstReleaseDate); + Assert.Equal("Queen", Assert.Single(response.ArtistCredit).Name); + Assert.Equal("release-id", Assert.Single(response.Releases).Id); + Assert.Equal("rock", Assert.Single(response.Tags).Name); + Assert.Equal("Rock", Assert.Single(response.Genres).Name); + Assert.NotNull(response.Rating); + Assert.Equal(4.5m, response.Rating.Value); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseTests.cs new file mode 100644 index 00000000..57aef8ce --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseTests.cs @@ -0,0 +1,52 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzReleaseGroupSearchResponseTests +{ + [Fact] + public void CountOffsetAndReleaseGroups_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"count":2,"offset":1,"release-groups":[{"id":"22222222-2222-2222-2222-222222222222","title":"A Night at the Opera"}]}"""; + + // Act + MusicBrainzReleaseGroupSearchResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(2, response.Count); + Assert.Equal(1, response.Offset); + Assert.Equal("A Night at the Opera", Assert.Single(response.ReleaseGroups).Title); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "count": 2, + "offset": 1, + "release-groups": [ { "id": "release-group-id", "title": "A Night at the Opera" } ] + } + """; + + // Act + MusicBrainzReleaseGroupSearchResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal(2, response.Count); + Assert.Equal(1, response.Offset); + Assert.Equal("release-group-id", Assert.Single(response.ReleaseGroups).Id); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseTests.cs new file mode 100644 index 00000000..273ec302 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseTests.cs @@ -0,0 +1,135 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzReleaseResponseTests +{ + [Fact] + public void Media_WhenTheRequestIncludesRecordings_ShouldDeserializeTheTracksAndTheirRecordingsWithTheirWorks() + { + // Arrange + // The recordings included in a release lookup already carry the fields the per track lookups return, including the work of each recording. + const string JSON = """ + { + "id": "1e14b2d6-8652-3dcc-b60b-4fb5fe79e024", + "title": "A Night at the Opera", + "media": [ + { + "position": 1, + "track-count": 1, + "tracks": [ + { + "id": "b1e2c3d4-0000-0000-0000-000000000000", + "number": "1", + "position": 1, + "title": "Death on Two Legs", + "length": 223293, + "recording": { + "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", + "title": "Death on Two Legs (Dedicated To...)", + "video": null, + "isrcs": [ "GBUM71029604" ], + "relations": [ + { + "target-type": "work", + "type": "performance", + "work": { + "id": "d0e0e0e0-0000-0000-0000-000000000000", + "title": "Death on Two Legs", + "type": "Song", + "languages": [ "eng" ], + "iswcs": [ "T-010.154.482-4" ] + } + } + ] + } + } + ] + } + ] + } + """; + + // Act + MusicBrainzReleaseResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + MusicBrainzMediumResponse medium = Assert.Single(response.Media); + Assert.Equal(1, medium.TrackCount); + MusicBrainzTrackResponse track = Assert.Single(medium.Tracks); + Assert.Equal(1, track.Position); + Assert.NotNull(track.Recording); + Assert.Equal("cb6c5931-436c-38c5-9d24-044f37d1fe35", track.Recording.Id); + Assert.Equal("Death on Two Legs (Dedicated To...)", track.Recording.Title); + Assert.Null(track.Recording.IsVideo); + Assert.Equal("GBUM71029604", Assert.Single(track.Recording.Isrcs)); + MusicBrainzRelationResponse relation = Assert.Single(track.Recording.Relations); + Assert.NotNull(relation.Work); + Assert.Equal("Death on Two Legs", relation.Work.Title); + Assert.Equal("eng", Assert.Single(relation.Work.Languages)); + Assert.Equal("T-010.154.482-4", Assert.Single(relation.Work.Iswcs)); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "release-id", + "title": "A Night at the Opera", + "disambiguation": "1975 album", + "status": "Official", + "date": "1975-11-21", + "country": "GB", + "release-events": [ { "date": "1975-11-21", "area": { "id": "area-id", "name": "United Kingdom" } } ], + "barcode": "0094639819524", + "packaging": "Jewel Case", + "text-representation": { "language": "eng", "script": "Latn" }, + "artist-credit": [ { "name": "Queen", "artist": { "id": "artist-id", "name": "Queen" } } ], + "release-group": { "id": "release-group-id", "title": "A Night at the Opera" }, + "label-info": [ { "catalog-number": "EMC 4008", "label": { "id": "label-id", "name": "EMI" } } ], + "media": [ { "position": 1, "title": "Disc 1", "format": "CD", "track-count": 12 } ], + "asin": "B000000000", + "tags": [ { "name": "rock", "count": 5 } ], + "genres": [ { "id": "genre-id", "name": "Rock" } ], + "relations": [ { "type": "producer", "artist": { "id": "artist-id", "name": "Roy Thomas Baker" } } ] + } + """; + + // Act + MusicBrainzReleaseResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("release-id", response.Id); + Assert.Equal("A Night at the Opera", response.Title); + Assert.Equal("1975 album", response.Disambiguation); + Assert.Equal("Official", response.Status); + Assert.Equal("1975-11-21", response.Date); + Assert.Equal("GB", response.Country); + Assert.Equal("1975-11-21", Assert.Single(response.ReleaseEvents).Date); + Assert.Equal("0094639819524", response.Barcode); + Assert.Equal("Jewel Case", response.Packaging); + Assert.NotNull(response.TextRepresentation); + Assert.Equal("eng", response.TextRepresentation.Language); + Assert.Equal("Queen", Assert.Single(response.ArtistCredit).Name); + Assert.NotNull(response.ReleaseGroup); + Assert.Equal("A Night at the Opera", response.ReleaseGroup.Title); + Assert.Equal("EMC 4008", Assert.Single(response.LabelInfo).CatalogNumber); + Assert.Equal(1, Assert.Single(response.Media).Position); + Assert.Equal("B000000000", response.Asin); + Assert.Equal("rock", Assert.Single(response.Tags).Name); + Assert.Equal("Rock", Assert.Single(response.Genres).Name); + Assert.Equal("producer", Assert.Single(response.Relations).Type); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTagResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTagResponseTests.cs new file mode 100644 index 00000000..9093c38a --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTagResponseTests.cs @@ -0,0 +1,54 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzTagResponseTests +{ + [Fact] + public void NameCountAndDisambiguation_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"name":"rock","disambiguation":"genre","count":5}"""; + + // Act + MusicBrainzTagResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("rock", response.Name); + Assert.Equal("genre", response.Disambiguation); + Assert.Equal(5, response.Count); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "genre-id", + "name": "rock", + "disambiguation": "genre", + "count": 5 + } + """; + + // Act + MusicBrainzTagResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("genre-id", response.Id); + Assert.Equal("rock", response.Name); + Assert.Equal("genre", response.Disambiguation); + Assert.Equal(5, response.Count); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseTests.cs new file mode 100644 index 00000000..8f096aaf --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzTextRepresentationResponseTests +{ + [Fact] + public void LanguageAndScript_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"language":"eng","script":"Latn"}"""; + + // Act + MusicBrainzTextRepresentationResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("eng", response.Language); + Assert.Equal("Latn", response.Script); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """{"language":"eng","script":"Latn"}"""; + + // Act + MusicBrainzTextRepresentationResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("eng", response.Language); + Assert.Equal("Latn", response.Script); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTrackResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTrackResponseTests.cs new file mode 100644 index 00000000..a876e542 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzTrackResponseTests.cs @@ -0,0 +1,70 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzTrackResponseTests +{ + [Fact] + public void NumberPositionLengthAndRecording_WhenTheTrackCarriesARecording_ShouldDeserializeAllOfThem() + { + // Arrange + const string JSON = """ + { + "id": "b1e2c3d4-0000-0000-0000-000000000000", + "number": "A1", + "position": 2, + "title": "Death on Two Legs", + "length": 223293, + "recording": { "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", "title": "Death on Two Legs (Dedicated To...)" } + } + """; + + // Act + MusicBrainzTrackResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("A1", response.Number); + Assert.Equal(2, response.Position); + Assert.Equal(223293, response.Length); + Assert.NotNull(response.Recording); + Assert.Equal("cb6c5931-436c-38c5-9d24-044f37d1fe35", response.Recording.Id); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "track-id", + "number": "A1", + "position": 2, + "title": "Death on Two Legs", + "length": 223293, + "recording": { "id": "recording-id", "title": "Death on Two Legs (Dedicated To...)" } + } + """; + + // Act + MusicBrainzTrackResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("track-id", response.Id); + Assert.Equal("A1", response.Number); + Assert.Equal(2, response.Position); + Assert.Equal("Death on Two Legs", response.Title); + Assert.Equal(223293, response.Length); + Assert.NotNull(response.Recording); + Assert.Equal("recording-id", response.Recording.Id); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzUrlResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzUrlResponseTests.cs new file mode 100644 index 00000000..483fc72f --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzUrlResponseTests.cs @@ -0,0 +1,44 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzUrlResponseTests +{ + [Fact] + public void Resource_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"id":"e0e0e0e0-0000-0000-0000-000000000000","resource":"https://www.queenonline.com/"}"""; + + // Act + MusicBrainzUrlResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("e0e0e0e0-0000-0000-0000-000000000000", response.Id); + Assert.Equal("https://www.queenonline.com/", response.Resource); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """{"id":"url-id","resource":"https://www.queenonline.com/"}"""; + + // Act + MusicBrainzUrlResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("url-id", response.Id); + Assert.Equal("https://www.queenonline.com/", response.Resource); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzWorkResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzWorkResponseTests.cs new file mode 100644 index 00000000..28d13fd6 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzWorkResponseTests.cs @@ -0,0 +1,64 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzWorkResponseTests +{ + [Fact] + public void TypeLanguagesAndIswcs_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize() + { + // Arrange + const string JSON = """{"id":"d0e0e0e0-0000-0000-0000-000000000000","title":"Death on Two Legs","type":"Song","languages":["eng"],"iswcs":["T-010.154.482-4"]}"""; + + // Act + MusicBrainzWorkResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("Song", response.Type); + Assert.Equal("eng", Assert.Single(response.Languages)); + Assert.Equal("T-010.154.482-4", Assert.Single(response.Iswcs)); + } + + [Fact] + public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty() + { + // Arrange + const string JSON = """ + { + "id": "work-id", + "title": "Bohemian Rhapsody", + "type": "Song", + "disambiguation": "studio version", + "languages": [ "eng" ], + "iswcs": [ "T-010.154.482-4" ], + "relations": [ { "type": "composer", "artist": { "id": "artist-id", "name": "Freddie Mercury" } } ], + "tags": [ { "name": "rock", "count": 5 } ], + "genres": [ { "id": "genre-id", "name": "Rock" } ] + } + """; + + // Act + MusicBrainzWorkResponse? response = JsonSerializer.Deserialize(JSON); + + // Assert + Assert.NotNull(response); + Assert.Equal("work-id", response.Id); + Assert.Equal("Bohemian Rhapsody", response.Title); + Assert.Equal("Song", response.Type); + Assert.Equal("studio version", response.Disambiguation); + Assert.Equal("eng", Assert.Single(response.Languages)); + Assert.Equal("T-010.154.482-4", Assert.Single(response.Iswcs)); + Assert.Equal("composer", Assert.Single(response.Relations).Type); + Assert.Equal("rock", Assert.Single(response.Tags).Name); + Assert.Equal("Rock", Assert.Single(response.Genres).Name); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/TestHelpers/StubHttpMessageHandler.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/TestHelpers/StubHttpMessageHandler.cs new file mode 100644 index 00000000..096cb74d --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/TestHelpers/StubHttpMessageHandler.cs @@ -0,0 +1,60 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers; + +/// +/// Test HTTP message handler that answers every request with a canned response produced by a factory, and records the requests that were sent. +/// +[ExcludeFromCodeCoverage] +internal sealed class StubHttpMessageHandler : HttpMessageHandler +{ + private readonly Func _responseFactory; + private int _callCount; + + /// + /// Gets the requests that were sent through the handler. + /// + public List Requests { get; } = []; + + /// + /// Gets the number of requests that were sent through the handler. + /// + public int CallCount => _callCount; + + /// + /// Initializes a new instance of the class. + /// + /// The factory that produces the response of a request, given the request and its one based call index. + public StubHttpMessageHandler(Func responseFactory) + { + _responseFactory = responseFactory; + } + + /// + /// Sends the provided request, producing its response through the configured factory. + /// + /// The request to send. + /// Cancellation token that can be used to stop the execution. + /// The response produced for the request. + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + int callIndex = Interlocked.Increment(ref _callCount); + Requests.Add(request); + try + { + return Task.FromResult(_responseFactory(request, callIndex)); + } + catch (Exception exception) + { + // A response factory may throw to simulate a transport failure, which is surfaced as a faulted task. + return Task.FromException(exception); + } + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzHttpClientTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzHttpClientTests.cs new file mode 100644 index 00000000..ca3a0f9e --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzHttpClientTests.cs @@ -0,0 +1,578 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using Lumina.Plugins.MusicBrainz.Core; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core.Api; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzHttpClientTests +{ + private const string RECORDING_JSON = """{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs","video":null}"""; + + private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new(); + + [Fact] + public async Task GetRecordingAsync_WhenTheSameRecordingIsRequestedTwice_ShouldServeTheSecondRequestFromTheCache() + { + // Arrange + Guid recordingId = Guid.NewGuid(); + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero); + + // Act + MusicBrainzRecordingResponse? first = await client.GetRecordingAsync(recordingId, CancellationToken.None); + MusicBrainzRecordingResponse? second = await client.GetRecordingAsync(recordingId, CancellationToken.None); + + // Assert + Assert.NotNull(first); + Assert.NotNull(second); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheBaseUrlIsNotTheRealService_ShouldNotThrottleTheRequests() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost:5000/", TimeSpan.FromSeconds(1)); + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + stopwatch.Stop(); + + // Assert + // The configured minimum request interval is one second, but a base URL that is not the real MusicBrainz service is not throttled. + Assert.Equal(2, handler.CallCount); + Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(500)); + } + + [Theory] + [InlineData("https://musicbrainz.org/ws/2/")] // the real service + [InlineData("https://mirror.musicbrainz.org/ws/2/")] // a subdomain of the real service + public async Task GetRecordingAsync_WhenTheBaseUrlIsTheRealService_ShouldThrottleTheRequests(string baseUrl) + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, HttpClient _) = CreateClient(baseUrl, TimeSpan.FromMilliseconds(100)); + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + stopwatch.Stop(); + + // Assert + Assert.Equal(2, handler.CallCount); + Assert.True(stopwatch.Elapsed >= TimeSpan.FromMilliseconds(50), $"The elapsed time {stopwatch.Elapsed} was shorter than the expected throttle interval."); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheBaseUrlIsNotAnAbsoluteUri_ShouldThrow() + { + // Arrange + (MusicBrainzHttpClient client, _, _) = CreateClient("not-a-url", TimeSpan.Zero); + + // Act + Task Act() + { + return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheRequestIsNotAuthorized_ShouldReturnNull() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound)); + + // Act + MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldCancelTheOperation() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero); + + // Act + Task Act() + { + return client.GetRecordingAsync(Guid.NewGuid(), cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + } + + [Fact] + public async Task GetRecordingAsync_WhenTheFirstAttemptReturns503_ShouldRetryAndSucceed() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => callIndex == 1 + ? new HttpResponseMessage(HttpStatusCode.ServiceUnavailable) + : Json(RECORDING_JSON)); + + // Act + MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheFirstAttemptIsRateLimited_ShouldRetryAndSucceed() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => callIndex == 1 + ? new HttpResponseMessage(HttpStatusCode.TooManyRequests) + : Json(RECORDING_JSON)); + + // Act + MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheFirstAttemptThrowsATransportException_ShouldRetryAndSucceed() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => callIndex == 1 + ? throw new HttpRequestException("Transient failure.") + : Json(RECORDING_JSON)); + + // Act + MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetRecordingAsync_WhenEveryAttemptFails_ShouldThrowAfterExhaustingTheRetries() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => new HttpResponseMessage(HttpStatusCode.InternalServerError)); + + // Act + Task Act() + { + return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(4, handler.CallCount); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheContactEmailIsConfigured_ShouldIncludeItInTheUserAgent() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, contactEmail: "contact@example.com"); + + // Act + await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + string userAgent = handler.Requests[0].Headers.UserAgent.ToString(); + Assert.Contains("Lumina-Test/1.0", userAgent); + Assert.Contains("contact@example.com", userAgent); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheContactEmailIsNotConfigured_ShouldNotIncludeItInTheUserAgent() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero); + + // Act + await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + string userAgent = handler.Requests[0].Headers.UserAgent.ToString(); + Assert.Equal("Lumina-Test/1.0", userAgent); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheUserAgentIsAlreadySet_ShouldNotOverrideIt() + { + // Arrange + StubHttpMessageHandler handler = new((request, callIndex) => Json(RECORDING_JSON)); + HttpClient httpClient = new(handler); + httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Custom/9.9"); + MusicBrainzHttpClient client = CreateMusicBrainzHttpClient(httpClient, "http://localhost/", TimeSpan.Zero, null); + + // Act + await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.Equal("Custom/9.9", handler.Requests[0].Headers.UserAgent.ToString()); + } + + [Fact] + public async Task GetArtistAsync_WhenTheArtistExists_ShouldDeserializeIt() + { + // Arrange + const string ARTIST_JSON = """{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","name":"Queen","type":"Group"}"""; + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(ARTIST_JSON)); + + // Act + MusicBrainzArtistResponse? result = await client.GetArtistAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Queen", result.Name); + Assert.Contains("inc=aliases+tags+genres+url-rels+artist-rels+ratings", handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task SearchArtistsAsync_WhenTheSearchReturnsArtists_ShouldReturnThem() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"artists":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","name":"Queen"}]}"""; + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(SEARCH_JSON)); + + // Act + IReadOnlyList result = await client.SearchArtistsAsync("Queen", 10, CancellationToken.None); + + // Assert + Assert.Equal("Queen", Assert.Single(result).Name); + Assert.Contains("limit=10", handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task SearchArtistsAsync_WhenTheResponseBodyIsNull_ShouldReturnAnEmptyCollection() + { + // Arrange + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("null")); + + // Act + IReadOnlyList result = await client.SearchArtistsAsync("Queen", 10, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Theory] + [InlineData(0, "limit=1")] // a limit below the minimum is clamped up + [InlineData(200, "limit=100")] // a limit above the maximum is clamped down + [InlineData(50, "limit=50")] // a limit within the range is kept + public async Task SearchArtistsAsync_WhenTheLimitIsOutOfRange_ShouldClampIt(int requestedLimit, string expectedQuery) + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("""{"artists":[]}""")); + + // Act + await client.SearchArtistsAsync("Queen", requestedLimit, CancellationToken.None); + + // Assert + Assert.Contains(expectedQuery, handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task GetReleaseGroupAsync_WhenTheReleaseGroupExists_ShouldDeserializeIt() + { + // Arrange + const string RELEASE_GROUP_JSON = """{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"A Night at the Opera"}"""; + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(RELEASE_GROUP_JSON)); + + // Act + MusicBrainzReleaseGroupResponse? result = await client.GetReleaseGroupAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("A Night at the Opera", result.Title); + } + + [Fact] + public async Task SearchReleaseGroupsAsync_WhenTheSearchReturnsReleaseGroups_ShouldReturnThem() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"release-groups":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"A Night at the Opera"}]}"""; + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(SEARCH_JSON)); + + // Act + IReadOnlyList result = await client.SearchReleaseGroupsAsync("Opera", 10, CancellationToken.None); + + // Assert + Assert.Equal("A Night at the Opera", Assert.Single(result).Title); + } + + [Fact] + public async Task SearchReleaseGroupsAsync_WhenTheResponseBodyIsNull_ShouldReturnAnEmptyCollection() + { + // Arrange + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("null")); + + // Act + IReadOnlyList result = await client.SearchReleaseGroupsAsync("Opera", 10, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetReleaseAsync_WhenTheReleaseExists_ShouldDeserializeIt() + { + // Arrange + const string RELEASE_JSON = """{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"A Night at the Opera"}"""; + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(RELEASE_JSON)); + + // Act + MusicBrainzReleaseResponse? result = await client.GetReleaseAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("A Night at the Opera", result.Title); + } + + [Fact] + public async Task BrowseReleasesByReleaseGroupAsync_WhenReleasesExist_ShouldReturnThem() + { + // Arrange + const string BROWSE_JSON = """{"release-count":1,"releases":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"A Night at the Opera"}]}"""; + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(BROWSE_JSON)); + + // Act + IReadOnlyList result = await client.BrowseReleasesByReleaseGroupAsync(Guid.NewGuid(), 25, CancellationToken.None); + + // Assert + Assert.Equal("A Night at the Opera", Assert.Single(result).Title); + Assert.Contains("inc=artist-credits+labels+media", handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task BrowseReleasesByReleaseGroupAsync_WhenTheResponseBodyIsNull_ShouldReturnAnEmptyCollection() + { + // Arrange + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("null")); + + // Act + IReadOnlyList result = await client.BrowseReleasesByReleaseGroupAsync(Guid.NewGuid(), 25, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task SearchRecordingsAsync_WhenTheSearchReturnsRecordings_ShouldReturnThem() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"recordings":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs"}]}"""; + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(SEARCH_JSON)); + + // Act + IReadOnlyList result = await client.SearchRecordingsAsync("Death", 10, CancellationToken.None); + + // Assert + Assert.Equal("Death on Two Legs", Assert.Single(result).Title); + } + + [Fact] + public async Task SearchRecordingsAsync_WhenTheResponseBodyIsNull_ShouldReturnAnEmptyCollection() + { + // Arrange + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("null")); + + // Act + IReadOnlyList result = await client.SearchRecordingsAsync("Death", 10, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetRecordingsByIsrcAsync_WhenRecordingsExist_ShouldReturnThem() + { + // Arrange + const string ISRC_JSON = """{"recordings":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs"}]}"""; + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(ISRC_JSON)); + + // Act + IReadOnlyList result = await client.GetRecordingsByIsrcAsync("US1A2B3C4D5E", CancellationToken.None); + + // Assert + Assert.Equal("Death on Two Legs", Assert.Single(result).Title); + } + + [Fact] + public async Task GetRecordingsByIsrcAsync_WhenTheResponseBodyIsNull_ShouldReturnAnEmptyCollection() + { + // Arrange + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json("null")); + + // Act + IReadOnlyList result = await client.GetRecordingsByIsrcAsync("US1A2B3C4D5E", CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetWorkAsync_WhenTheWorkExists_ShouldDeserializeIt() + { + // Arrange + const string WORK_JSON = """{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs","type":"Song"}"""; + (MusicBrainzHttpClient client, _, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(WORK_JSON)); + + // Act + MusicBrainzWorkResponse? result = await client.GetWorkAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Death on Two Legs", result.Title); + } + + [Fact] + public async Task GetReleaseWithRecordingsAsync_WhenTheReleaseExists_ShouldDeserializeItsTracks() + { + // Arrange + const string RELEASE_JSON = """ + { + "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", + "title": "A Night at the Opera", + "media": [ { "position": 1, "track-count": 1, "tracks": [ { "position": 1, "title": "Death on Two Legs", "recording": { "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", "title": "Death on Two Legs" } } ] } ] + } + """; + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => Json(RELEASE_JSON)); + + // Act + MusicBrainzReleaseResponse? result = await client.GetReleaseWithRecordingsAsync(Guid.NewGuid(), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Contains("inc=recordings", handler.Requests[0].RequestUri!.Query); + Assert.Single(Assert.Single(result.Media).Tracks); + } + + [Fact] + public async Task GetRecordingAsync_WhenTheFirstAttemptIsRateLimitedWithRetryAfter_ShouldHonorTheRequestedDelay() + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, (request, callIndex) => + { + if (callIndex != 1) + return Json(RECORDING_JSON); + HttpResponseMessage rateLimited = new(HttpStatusCode.TooManyRequests); + rateLimited.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.Zero); + return rateLimited; + }); + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None); + stopwatch.Stop(); + + // Assert + Assert.NotNull(result); + Assert.Equal(2, handler.CallCount); + // The requested delay of zero is honored instead of the default five hundred millisecond backoff of the first retry. + Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(400), $"The elapsed time {stopwatch.Elapsed} shows the Retry-After header was ignored."); + } + + [Theory] + [InlineData("A & B")] // ampersand query separator + [InlineData("Title #fragment")] // fragment separator + [InlineData("A?B")] // query separator + [InlineData("../../secret")] // path traversal + [InlineData("A\" OR \"B")] // quote escape + public async Task SearchArtistsAsync_WhenTheQueryContainsReservedCharacters_ShouldKeepThemInsideTheQueryString(string searchTerm) + { + // Arrange + (MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://musicbrainz.example/ws/2/", TimeSpan.Zero, (request, callIndex) => Json("""{"artists":[]}""")); + + // Act + await client.SearchArtistsAsync(searchTerm, 10, CancellationToken.None); + + // Assert + Uri requestUri = handler.Requests[0].RequestUri!; + Assert.Equal("musicbrainz.example", requestUri.Host); + Assert.Equal("/ws/2/artist", requestUri.AbsolutePath); + Assert.Equal(string.Empty, requestUri.Fragment); + } + + /// + /// Creates a whose requests are answered by a stub handler, returning the recording JSON by default. + /// + /// The base URL of the MusicBrainz web service the client points to. + /// The minimum request interval configured for the client. + /// Optional. The factory that produces the response of a request. + /// Optional. The contact email configured for the client. + /// The created client, its stub handler and the underlying HTTP client. + private (MusicBrainzHttpClient Client, StubHttpMessageHandler Handler, HttpClient HttpClient) CreateClient( + string baseUrl, + TimeSpan minimumRequestInterval, + Func? responseFactory = null, + string? contactEmail = null) + { + StubHttpMessageHandler handler = new(responseFactory ?? ((request, callIndex) => Json(RECORDING_JSON))); + HttpClient httpClient = new(handler); + MusicBrainzHttpClient client = CreateMusicBrainzHttpClient(httpClient, baseUrl, minimumRequestInterval, contactEmail); + return (client, handler, httpClient); + } + + /// + /// Creates a around the provided . + /// + /// The underlying HTTP client. + /// The base URL of the MusicBrainz web service the client points to. + /// The minimum request interval configured for the client. + /// Optional. The contact email configured for the client. + /// The created client. + private MusicBrainzHttpClient CreateMusicBrainzHttpClient(HttpClient httpClient, string baseUrl, TimeSpan minimumRequestInterval, string? contactEmail) + { + MusicBrainzSettingsProvider settingsProvider = new(null, MusicBrainzPlugin.s_pluginId, _musicBrainzSettingsDtoFixture.Create( + baseUrl: baseUrl, + userAgent: "Lumina-Test/1.0", + contactEmail: contactEmail, + includeContactEmail: contactEmail is not null, + searchResultLimit: 10, + releaseLookupLimit: 25, + minimumRequestInterval: minimumRequestInterval)); + return new MusicBrainzHttpClient(httpClient, settingsProvider, new MusicBrainzRequestThrottle(), new MusicBrainzResponseCache()); + } + + /// + /// Creates an OK response with the provided JSON body. + /// + /// The JSON body of the response. + /// The created response. + private static HttpResponseMessage Json(string json) + { + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzRequestThrottleTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzRequestThrottleTests.cs new file mode 100644 index 00000000..bd9e287f --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzRequestThrottleTests.cs @@ -0,0 +1,106 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Core.Api; +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core.Api; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzRequestThrottleTests +{ + private readonly MusicBrainzRequestThrottle _sut = new(); + + [Fact] + public async Task WaitAsync_WhenTheMinimumIntervalHasNotElapsed_ShouldDelayTheSecondRequest() + { + // Arrange + TimeSpan minimumRequestInterval = TimeSpan.FromMilliseconds(200); + + // Act + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + Stopwatch stopwatch = Stopwatch.StartNew(); + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + stopwatch.Stop(); + + // Assert + // The second request must wait for the remainder of the interval, which is close to the configured interval. + Assert.True(stopwatch.Elapsed >= TimeSpan.FromMilliseconds(150), $"The elapsed time {stopwatch.Elapsed} was shorter than the expected minimum interval."); + } + + [Fact] + public async Task WaitAsync_WhenTheMinimumIntervalIsZero_ShouldNotDelayTheRequests() + { + // Arrange + TimeSpan minimumRequestInterval = TimeSpan.Zero; + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + stopwatch.Stop(); + + // Assert + Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(500), $"The elapsed time {stopwatch.Elapsed} shows an unexpected delay."); + } + + [Fact] + public async Task WaitAsync_WhenTheMinimumIntervalIsNegative_ShouldNotDelayTheRequests() + { + // Arrange + TimeSpan minimumRequestInterval = TimeSpan.FromSeconds(-1); + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + await _sut.WaitAsync(minimumRequestInterval, CancellationToken.None); + stopwatch.Stop(); + + // Assert + Assert.True(stopwatch.Elapsed < TimeSpan.FromMilliseconds(500), $"The elapsed time {stopwatch.Elapsed} shows an unexpected delay."); + } + + [Fact] + public async Task WaitAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldThrowOperationCanceledException() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + + // Act + Task Act() + { + return _sut.WaitAsync(TimeSpan.FromMilliseconds(100), cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + } + + [Fact] + public async Task WaitAsync_WhenCalledConcurrently_ShouldSpaceOutEveryRequest() + { + // Arrange + TimeSpan minimumRequestInterval = TimeSpan.FromMilliseconds(150); + + // Act + Stopwatch stopwatch = Stopwatch.StartNew(); + await Task.WhenAll( + _sut.WaitAsync(minimumRequestInterval, CancellationToken.None), + _sut.WaitAsync(minimumRequestInterval, CancellationToken.None), + _sut.WaitAsync(minimumRequestInterval, CancellationToken.None)); + stopwatch.Stop(); + + // Assert + // Three requests spaced by the interval take at least two intervals in total. + Assert.True(stopwatch.Elapsed >= TimeSpan.FromMilliseconds(250), $"The elapsed time {stopwatch.Elapsed} was shorter than the expected total interval."); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzResponseCacheTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzResponseCacheTests.cs new file mode 100644 index 00000000..14bb54d0 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzResponseCacheTests.cs @@ -0,0 +1,149 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.MusicBrainz.Core.Api; +using System; +using System.Diagnostics.CodeAnalysis; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core.Api; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzResponseCacheTests +{ + private readonly MusicBrainzResponseCache _sut = new(); + + [Fact] + public void TryGet_WhenTheKeyWasNeverCached_ShouldReturnFalse() + { + // Act + bool result = _sut.TryGet("missing", out string? json); + + // Assert + Assert.False(result); + Assert.Null(json); + } + + [Fact] + public void TryGet_WhenTheKeyWasCached_ShouldReturnTheCachedBody() + { + // Arrange + _sut.Set("key", "{\"id\":\"1\"}"); + + // Act + bool result = _sut.TryGet("key", out string? json); + + // Assert + Assert.True(result); + Assert.Equal("{\"id\":\"1\"}", json); + } + + [Fact] + public void Set_WhenTheKeyAlreadyExists_ShouldReplaceTheCachedBody() + { + // Arrange + _sut.Set("key", "a-longer-value"); + _sut.Set("key", "short"); + + // Act + bool result = _sut.TryGet("key", out string? json); + + // Assert + Assert.True(result); + Assert.Equal("short", json); + } + + [Fact] + public void Set_WhenTheValueFitsTheCharacterBudgetExactly_ShouldCacheIt() + { + // Arrange + MusicBrainzResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 3, timeToLive: TimeSpan.FromMinutes(1)); + + // Act + sut.Set("exact", "abc"); + + // Assert + Assert.True(sut.TryGet("exact", out string? json)); + Assert.Equal("abc", json); + } + + [Fact] + public void Set_WhenTheValueExceedsTheWholeCharacterBudget_ShouldNotCacheIt() + { + // Arrange + MusicBrainzResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 3, timeToLive: TimeSpan.FromMinutes(1)); + + // Act + sut.Set("oversized", "abcd"); + + // Assert + Assert.False(sut.TryGet("oversized", out _)); + } + + [Fact] + public void Set_WhenTheCharacterBudgetIsExceeded_ShouldEvictTheOldestEntryAndKeepTheNewestOne() + { + // Arrange + MusicBrainzResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 10, timeToLive: TimeSpan.FromMinutes(1)); + sut.Set("oldest", "1234567890"); + + // Act + sut.Set("newest", "x"); + + // Assert + Assert.False(sut.TryGet("oldest", out _)); + Assert.True(sut.TryGet("newest", out string? json)); + Assert.Equal("x", json); + } + + [Fact] + public void Set_WhenTheEntryCountBudgetIsExceeded_ShouldEvictTheOldestEntriesAndKeepTheNewestOne() + { + // Arrange + MusicBrainzResponseCache sut = new(maximumEntryCount: 3, maximumCharacterCount: 1_000, timeToLive: TimeSpan.FromMinutes(1)); + sut.Set("entry-1", "1"); + sut.Set("entry-2", "2"); + sut.Set("entry-3", "3"); + + // Act + sut.Set("entry-4", "4"); + + // Assert + // The oldest entries are trimmed to the lower water mark, while the most recently cached one always survives. + Assert.False(sut.TryGet("entry-1", out _)); + Assert.False(sut.TryGet("entry-2", out _)); + Assert.True(sut.TryGet("entry-3", out _)); + Assert.True(sut.TryGet("entry-4", out _)); + } + + [Fact] + public void Set_WhenTheEntryCountBudgetIsExceededByOne_ShouldEvictTheOldestEntryAndKeepTheNewOne() + { + // Arrange + MusicBrainzResponseCache sut = new(maximumEntryCount: 1, maximumCharacterCount: 1_000, timeToLive: TimeSpan.FromMinutes(1)); + sut.Set("entry-1", "1"); + + // Act + sut.Set("entry-2", "2"); + + // Assert + Assert.True(sut.TryGet("entry-2", out _)); + Assert.False(sut.TryGet("entry-1", out _)); + } + + [Fact] + public void TryGet_WhenTheCachedEntryExpired_ShouldReturnFalse() + { + // Arrange + MusicBrainzResponseCache sut = new(maximumEntryCount: 10, maximumCharacterCount: 1_000, timeToLive: TimeSpan.FromMilliseconds(-1)); + sut.Set("expired", "value"); + + // Act + bool result = sut.TryGet("expired", out string? json); + + // Assert + Assert.False(result); + Assert.Null(json); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Mapping/MusicBrainzMapperTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Mapping/MusicBrainzMapperTests.cs new file mode 100644 index 00000000..91d8eb01 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Mapping/MusicBrainzMapperTests.cs @@ -0,0 +1,1508 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaContributors; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.Common; +using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors; +using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; +using Lumina.Plugins.MusicBrainz.Core.Mapping; +using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core.Mapping; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzMapperTests +{ + private readonly MusicBrainzArtistResponseFixture _musicBrainzArtistResponseFixture = new(); + private readonly MusicBrainzAreaResponseFixture _musicBrainzAreaResponseFixture = new(); + private readonly MusicBrainzAliasResponseFixture _musicBrainzAliasResponseFixture = new(); + private readonly MusicBrainzRelationResponseFixture _musicBrainzRelationResponseFixture = new(); + private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new(); + private readonly MusicBrainzLifeSpanResponseFixture _musicBrainzLifeSpanResponseFixture = new(); + private readonly MusicBrainzRatingResponseFixture _musicBrainzRatingResponseFixture = new(); + private readonly MusicBrainzReleaseGroupResponseFixture _musicBrainzReleaseGroupResponseFixture = new(); + private readonly MusicBrainzReleaseResponseFixture _musicBrainzReleaseResponseFixture = new(); + private readonly MusicBrainzArtistCreditResponseFixture _musicBrainzArtistCreditResponseFixture = new(); + private readonly MusicBrainzLabelInfoResponseFixture _musicBrainzLabelInfoResponseFixture = new(); + private readonly MusicBrainzMediumResponseFixture _musicBrainzMediumResponseFixture = new(); + private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new(); + private readonly MusicBrainzWorkResponseFixture _musicBrainzWorkResponseFixture = new(); + private readonly MusicBrainzUrlResponseFixture _musicBrainzUrlResponseFixture = new(); + private readonly MusicBrainzTextRepresentationResponseFixture _musicBrainzTextRepresentationResponseFixture = new(); + private readonly MusicBrainzLabelResponseFixture _musicBrainzLabelResponseFixture = new(); + + [Fact] + public void MapArtist_WhenEveryFieldIsPresent_ShouldMapEveryField() + { + // Arrange + Guid artistId = Guid.NewGuid(); + Guid areaId = Guid.NewGuid(); + Guid beginAreaId = Guid.NewGuid(); + Guid endAreaId = Guid.NewGuid(); + MusicBrainzAreaResponse area = _musicBrainzAreaResponseFixture.Create(id: areaId.ToString(), name: "United States", sortName: "United States", disambiguation: "the country", type: "Country", iso3166Part1Codes: ["US"], iso3166Part2Codes: ["US-NY"]); + MusicBrainzAreaResponse beginArea = _musicBrainzAreaResponseFixture.Create(id: beginAreaId.ToString(), name: "New York", iso3166Part1Codes: ["US"], iso3166Part2Codes: []); + MusicBrainzAreaResponse endArea = _musicBrainzAreaResponseFixture.Create(id: endAreaId.ToString(), name: "Los Angeles", iso3166Part1Codes: ["US"], iso3166Part2Codes: []); + MusicBrainzAliasResponse alias = _musicBrainzAliasResponseFixture.Create(name: "The Alias", sortName: "Alias, The", type: "Artist name", locale: "en", isPrimary: true, begin: "1990-01-01", end: "2000-01-01", isEnded: false); + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + id: artistId.ToString(), + name: " The Artist ", + sortName: "Artist, The", + disambiguation: "UK band", + type: "Group", + gender: "Female", + country: "US", + area: area, + includeArea: true, + beginArea: beginArea, + includeBeginArea: true, + endArea: endArea, + includeEndArea: true, + lifeSpan: _musicBrainzLifeSpanResponseFixture.Create(begin: "1950-01-01", end: "2000-12-31", isEnded: true), + includeLifeSpan: true, + isnis: ["ISNI1", "", " "], + ipis: ["IPI1", "", " "], + aliases: [alias], + tags: [_musicBrainzTagResponseFixture.Create(name: "Rock"), _musicBrainzTagResponseFixture.Create(name: "rock"), _musicBrainzTagResponseFixture.Create(name: " ")], + genres: [_musicBrainzTagResponseFixture.Create(name: "Pop"), _musicBrainzTagResponseFixture.Create(name: "POP")], + relations: + [ + _musicBrainzRelationResponseFixture.Create(type: "official homepage", targetType: "url", includeUrl: true, url: _musicBrainzUrlResponseFixture.Create(resource: "https://artist.example")), + _musicBrainzRelationResponseFixture.Create(type: "official homepage", targetType: "url", includeUrl: true, url: _musicBrainzUrlResponseFixture.Create(resource: "https://second.example")), + _musicBrainzRelationResponseFixture.Create(type: "wikidata", targetType: "url", includeUrl: true, url: _musicBrainzUrlResponseFixture.Create(resource: "https://wikidata.example")), + _musicBrainzRelationResponseFixture.Create(type: "member of band", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "Member")), + _musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Producer")), + _musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Producer")), + _musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: " ")), + _musicBrainzRelationResponseFixture.Create(type: "composer", targetType: "work") + ], + rating: _musicBrainzRatingResponseFixture.Create(value: 4.5m, votesCount: 12), + includeRating: true); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal("The Artist", result.Name); + Assert.Equal("Artist, The", result.SortName); + Assert.Equal("UK band", result.Disambiguation); + Assert.Equal(MusicArtistType.Group, result.Type); + Assert.Equal(MusicArtistGender.Female, result.Gender); + Assert.Equal("US", result.Country); + Assert.NotNull(result.Area); + Assert.Equal(areaId, result.Area.MusicBrainzAreaId); + Assert.Equal("United States", result.Area.Name); + Assert.Equal("United States", result.Area.SortName); + Assert.Equal("the country", result.Area.Disambiguation); + Assert.Equal("Country", result.Area.Type); + Assert.Equal("US", result.Area.Iso3166Code); + Assert.NotNull(result.BeginArea); + Assert.Equal(beginAreaId, result.BeginArea.MusicBrainzAreaId); + Assert.NotNull(result.EndArea); + Assert.Equal(endAreaId, result.EndArea.MusicBrainzAreaId); + Assert.Equal(new DateOnly(1950, 1, 1), result.LifeSpanBegin); + Assert.Equal(new DateOnly(2000, 12, 31), result.LifeSpanEnd); + Assert.True(result.IsEnded); + Assert.Equal("https://artist.example", result.Website); + Assert.Equal(artistId, result.MusicBrainzArtistId); + Assert.Equal(["IPI1"], result.Ipis); + Assert.Equal(["ISNI1"], result.Isnis); + MusicArtistAliasDto mappedAlias = Assert.Single(result.Aliases!); + Assert.Equal("The Alias", mappedAlias.Name); + Assert.Equal("Alias, The", mappedAlias.SortName); + Assert.Equal("Artist name", mappedAlias.Type); + Assert.Equal("en", mappedAlias.Locale); + Assert.True(mappedAlias.IsPrimary); + Assert.Equal(new DateOnly(1990, 1, 1), mappedAlias.BeginDate); + Assert.Equal(new DateOnly(2000, 1, 1), mappedAlias.EndDate); + Assert.False(mappedAlias.IsEnded); + Assert.Equal(["Rock"], result.Tags!.Select(tag => tag.Name)); + Assert.Equal(["Pop"], result.Genres!.Select(genre => genre.Name)); + Assert.Single(result.Ratings!); + Assert.Equal(4.5m, result.Ratings![0].Value); + Assert.Equal(5m, result.Ratings[0].MaxValue); + Assert.Equal(AudioRatingSource.MusicBrainz, result.Ratings[0].Source); + Assert.Equal(12, result.Ratings[0].VoteCount); + Assert.Equal(2, result.Contributors!.Count); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "Member" && contributor.Role == MediaContributorRole.Performer); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Producer" && contributor.Role == MediaContributorRole.Producer); + } + + [Fact] + public void MapArtist_WhenOptionalFieldsAreMissing_ShouldReturnNullAndEmptyCollections() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + id: "not-a-guid", + name: " ", + includeSortName: false, + includeDisambiguation: false, + includeType: false, + includeGender: false, + includeCountry: false, + includeArea: false, + includeBeginArea: false, + includeEndArea: false, + includeLifeSpan: false, + isnis: [], + ipis: [], + aliases: [], + tags: [], + genres: [], + relations: [], + includeRating: false); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Null(result.Name); + Assert.Null(result.SortName); + Assert.Null(result.Disambiguation); + Assert.Null(result.Type); + Assert.Null(result.Gender); + Assert.Null(result.Country); + Assert.Null(result.Area); + Assert.Null(result.BeginArea); + Assert.Null(result.EndArea); + Assert.Null(result.LifeSpanBegin); + Assert.Null(result.LifeSpanEnd); + Assert.False(result.IsEnded); + Assert.Null(result.Website); + Assert.Null(result.MusicBrainzArtistId); + Assert.Empty(result.Ipis!); + Assert.Empty(result.Isnis!); + Assert.Empty(result.Aliases!); + Assert.Empty(result.Tags!); + Assert.Empty(result.Genres!); + Assert.Empty(result.Ratings!); + Assert.Empty(result.Contributors!); + } + + [Theory] + [InlineData("person", MusicArtistType.Person)] // an individual + [InlineData("group", MusicArtistType.Group)] // an ensemble + [InlineData("orchestra", MusicArtistType.Orchestra)] // an instrumental ensemble + [InlineData("choir", MusicArtistType.Choir)] // a vocal ensemble + [InlineData("character", MusicArtistType.Character)] // a fictional character + [InlineData("other", MusicArtistType.Other)] // a known but uncategorized type + [InlineData("PERSON", MusicArtistType.Person)] // the value is normalized + public void MapArtist_WhenTheTypeIsKnown_ShouldMapIt(string type, MusicArtistType expected) + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create(type: type, relations: [], aliases: [], tags: [], genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal(expected, result.Type); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("made-up")] + public void MapArtist_WhenTheTypeIsUnknown_ShouldReturnNullType(string? type) + { + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(_musicBrainzArtistResponseFixture.Create(type: type, includeType: type is not null, relations: [], aliases: [], tags: [], genres: [])); + + // Assert + Assert.Null(result.Type); + } + + [Theory] + [InlineData("male", MusicArtistGender.Male)] + [InlineData("female", MusicArtistGender.Female)] + [InlineData("other", MusicArtistGender.Other)] + [InlineData("not applicable", MusicArtistGender.NotApplicable)] + [InlineData("FEMALE", MusicArtistGender.Female)] // the value is normalized + public void MapArtist_WhenTheGenderIsKnown_ShouldMapIt(string gender, MusicArtistGender expected) + { + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(_musicBrainzArtistResponseFixture.Create(gender: gender, relations: [], aliases: [], tags: [], genres: [])); + + // Assert + Assert.Equal(expected, result.Gender); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("made-up")] + public void MapArtist_WhenTheGenderIsUnknown_ShouldReturnNullGender(string? gender) + { + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(_musicBrainzArtistResponseFixture.Create(gender: gender, includeGender: gender is not null, relations: [], aliases: [], tags: [], genres: [])); + + // Assert + Assert.Null(result.Gender); + } + + [Theory] + [InlineData("executive producer", MediaContributorRole.ExecutiveProducer)] // more specific than producer + [InlineData("producer", MediaContributorRole.Producer)] + [InlineData("remixer", MediaContributorRole.Remixer)] + [InlineData("mix", MediaContributorRole.Mixer)] + [InlineData("engineer", MediaContributorRole.Engineer)] + [InlineData("mastering", MediaContributorRole.Engineer)] + [InlineData("composer", MediaContributorRole.Composer)] + [InlineData("writer", MediaContributorRole.Author)] + [InlineData("lyricist", MediaContributorRole.Lyricist)] + [InlineData("librettist", MediaContributorRole.Lyricist)] + [InlineData("arranger", MediaContributorRole.Arranger)] + [InlineData("conductor", MediaContributorRole.Conductor)] + [InlineData("orchestrator", MediaContributorRole.Orchestrator)] + [InlineData("backing vocals", MediaContributorRole.BackingVocals)] + [InlineData("vocal", MediaContributorRole.Vocals)] + [InlineData("member of band", MediaContributorRole.Performer)] + [InlineData("performer", MediaContributorRole.Performer)] + [InlineData("orchestra", MediaContributorRole.Performer)] + [InlineData("choir", MediaContributorRole.Performer)] + [InlineData("made-up role", MediaContributorRole.Other)] + public void MapArtist_WhenAnArtistRelationHasAKnownType_ShouldMapTheRole(string relationType, MediaContributorRole expected) + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: relationType, targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Person"))], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal(expected, contributor.Role); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void MapArtist_WhenAnArtistRelationHasNoType_ShouldMapTheRoleAsOther(string? relationType) + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: relationType, includeType: relationType is not null, targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Person"))], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal(MediaContributorRole.Other, Assert.Single(result.Contributors!).Role); + } + + [Theory] + [InlineData("backing vocal", MediaContributorRole.BackingVocals)] + [InlineData("vocals", MediaContributorRole.Vocals)] + [InlineData("bass guitar", MediaContributorRole.BassGuitar)] + [InlineData("guitar", MediaContributorRole.Guitar)] + [InlineData("drums", MediaContributorRole.Drums)] + [InlineData("percussion", MediaContributorRole.Percussion)] + [InlineData("keyboard", MediaContributorRole.Keyboards)] + [InlineData("piano", MediaContributorRole.Piano)] + [InlineData("synthesizer", MediaContributorRole.Synthesizer)] + [InlineData("synth", MediaContributorRole.Synthesizer)] + [InlineData("strings", MediaContributorRole.Strings)] + [InlineData("violin", MediaContributorRole.Strings)] + [InlineData("cello", MediaContributorRole.Strings)] + [InlineData("viola", MediaContributorRole.Strings)] + [InlineData("brass", MediaContributorRole.Brass)] + [InlineData("trumpet", MediaContributorRole.Brass)] + [InlineData("trombone", MediaContributorRole.Brass)] + [InlineData("horn", MediaContributorRole.Brass)] + [InlineData("woodwind", MediaContributorRole.Woodwinds)] + [InlineData("flute", MediaContributorRole.Woodwinds)] + [InlineData("saxophone", MediaContributorRole.Woodwinds)] + [InlineData("clarinet", MediaContributorRole.Woodwinds)] + public void MapArtist_WhenAnArtistRelationHasAnInstrumentAttribute_ShouldPreferTheInstrument(string attribute, MediaContributorRole expected) + { + // Arrange + // The relation type would map to a different role, so the instrument attribute must take precedence. + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Person"), attributes: [attribute])], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal(expected, Assert.Single(result.Contributors!).Role); + } + + [Fact] + public void MapArtist_WhenAnArtistRelationHasAnUnknownInstrumentAttribute_ShouldFallBackToTheRelationType() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Person"), attributes: ["made-up instrument"])], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal(MediaContributorRole.Producer, Assert.Single(result.Contributors!).Role); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void MapArtist_WhenAnArtistRelationHasABlankInstrumentAttribute_ShouldFallBackToTheRelationType(string attribute) + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: "composer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Person"), attributes: [attribute])], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal(MediaContributorRole.Composer, Assert.Single(result.Contributors!).Role); + } + + [Fact] + public void MapArtist_WhenARelationTargetsAnotherType_ShouldIgnoreIt() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: + [ + _musicBrainzRelationResponseFixture.Create(type: "composer", targetType: "work"), + _musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Producer")) + ], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Producer", contributor.Name!.DisplayName); + } + + [Fact] + public void MapArtist_WhenAnArtistRelationHasNoName_ShouldSkipIt() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: " "))], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Empty(result.Contributors!); + } + + [Fact] + public void MapArtist_WhenAUrlRelationIsNotAnOfficialHomepage_ShouldNotSetTheWebsite() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: "wikidata", targetType: "url", includeUrl: true, url: _musicBrainzUrlResponseFixture.Create(resource: "https://wikidata.example"))], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Null(result.Website); + } + + [Fact] + public void MapArea_WhenTheAreaIsNull_ShouldReturnNull() + { + // Act + MusicAreaDto? result = MusicBrainzMapper.MapArea(null); + + // Assert + Assert.Null(result); + } + + [Fact] + public void MapArea_WhenThePrimaryIsoCodeIsMissing_ShouldUseTheSecondaryIsoCode() + { + // Arrange + MusicBrainzAreaResponse area = _musicBrainzAreaResponseFixture.Create(id: Guid.NewGuid().ToString(), name: "Some Area", iso3166Part1Codes: [], iso3166Part2Codes: ["GB-ENG"]); + + // Act + MusicAreaDto? result = MusicBrainzMapper.MapArea(area); + + // Assert + Assert.NotNull(result); + Assert.Equal("GB-ENG", result.Iso3166Code); + } + + [Fact] + public void MapArea_WhenEveryOptionalFieldIsBlank_ShouldReturnNullFields() + { + // Arrange + MusicBrainzAreaResponse area = _musicBrainzAreaResponseFixture.Create(id: "not-a-guid", name: " ", includeSortName: false, includeDisambiguation: false, includeType: false, iso3166Part1Codes: [], iso3166Part2Codes: []); + + // Act + MusicAreaDto? result = MusicBrainzMapper.MapArea(area); + + // Assert + Assert.NotNull(result); + Assert.Null(result.MusicBrainzAreaId); + Assert.Null(result.Name); + Assert.Null(result.SortName); + Assert.Null(result.Disambiguation); + Assert.Null(result.Type); + Assert.Null(result.Iso3166Code); + } + + [Fact] + public void MapAlbum_WhenEveryFieldIsPresent_ShouldMapEveryField() + { + // Arrange + Guid releaseGroupId = Guid.NewGuid(); + Guid releaseId = Guid.NewGuid(); + Guid releaseArtistId = Guid.NewGuid(); + MusicBrainzArtistCreditResponse credit = _musicBrainzArtistCreditResponseFixture.Create(name: "The Album Artist", artist: _musicBrainzArtistResponseFixture.Create(id: releaseArtistId.ToString(), name: "The Album Artist"), includeJoinPhrase: false); + MusicBrainzMediumResponse medium = _musicBrainzMediumResponseFixture.Create(position: 1, format: "CD", tracks: [], trackCount: 12); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + id: releaseId.ToString(), + title: "The Release", + disambiguation: "remastered", + status: "Official", + date: "1995-11-21", + country: "US", + barcode: "1234567890123", + packaging: "Jewel Case", + textRepresentation: _musicBrainzTextRepresentationResponseFixture.Create(language: "eng", script: "Latn"), + artistCredit: [credit], + includeReleaseGroup: false, + labelInfo: + [ + _musicBrainzLabelInfoResponseFixture.Create(catalogNumber: "CAT-1", label: _musicBrainzLabelResponseFixture.Create(name: "The Label")), + _musicBrainzLabelInfoResponseFixture.Create(catalogNumber: "CAT-2", label: _musicBrainzLabelResponseFixture.Create(name: "Other Label")), + _musicBrainzLabelInfoResponseFixture.Create(catalogNumber: "cat-1", label: _musicBrainzLabelResponseFixture.Create(name: "Other Label")), + _musicBrainzLabelInfoResponseFixture.Create(catalogNumber: " ", label: _musicBrainzLabelResponseFixture.Create(name: "Other Label")) + ], + media: [medium, _musicBrainzMediumResponseFixture.Create(position: 2, format: "Vinyl", tracks: [], trackCount: 3)], + asin: "B000000001", + tags: [_musicBrainzTagResponseFixture.Create(name: "Rock")], + genres: [_musicBrainzTagResponseFixture.Create(name: "Pop")], + relations: [_musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Release Producer"))]); + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create( + id: releaseGroupId.ToString(), + title: "The Album", + disambiguation: "the album", + primaryType: "Album", + secondaryTypes: ["Live"], + firstReleaseDate: "1975-06-01", + artistCredit: [credit], + tags: [_musicBrainzTagResponseFixture.Create(name: "Rock"), _musicBrainzTagResponseFixture.Create(name: "rock")], + genres: [_musicBrainzTagResponseFixture.Create(name: "Pop")], + rating: _musicBrainzRatingResponseFixture.Create(value: 4m, votesCount: 8), + includeRating: true); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal("The Album", result.Title); + Assert.Null(result.OriginalTitle); + Assert.Null(result.Description); + Assert.Equal("the album", result.Disambiguation); + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(new DateOnly(1975, 6, 1), result.ReleaseInfo.OriginalReleaseDate); + Assert.Equal(1975, result.ReleaseInfo.OriginalReleaseYear); + Assert.Equal(new DateOnly(1995, 11, 21), result.ReleaseInfo.ReReleaseDate); + Assert.Equal(1995, result.ReleaseInfo.ReReleaseYear); + Assert.Equal(ReleaseCountry.US, result.ReleaseInfo.ReleaseCountry); + Assert.Equal("remastered", result.ReleaseInfo.ReleaseVersion); + Assert.NotNull(result.Language); + Assert.Equal("en", result.Language.LanguageCode); + Assert.Null(result.OriginalLanguage); + Assert.Equal(["Rock"], result.Tags!.Select(tag => tag.Name)); + Assert.Equal(["Pop"], result.Genres!.Select(genre => genre.Name)); + Assert.Equal("Latn", result.Script); + Assert.Equal([MusicReleaseType.Album, MusicReleaseType.Live], result.ReleaseTypes); + Assert.Equal(MusicReleaseStatus.Official, result.ReleaseStatus); + Assert.Equal(MusicMediaFormat.CD, result.MediaFormat); + Assert.Equal(MusicReleasePackaging.JewelCase, result.Packaging); + Assert.Equal(2, result.TotalDiscs); + Assert.Equal(15, result.TotalTracks); + Assert.Equal("1234567890123", result.Barcode); + Assert.Equal(["CAT-1", "CAT-2"], result.CatalogNumbers); + Assert.Equal("The Label", result.Label); + Assert.Equal("B000000001", result.ASIN); + Assert.Equal(releaseId, result.MusicBrainzReleaseId); + Assert.Equal(releaseGroupId, result.MusicBrainzReleaseGroupId); + Assert.Equal(releaseArtistId, result.MusicBrainzReleaseArtistId); + Assert.Equal("The Release", result.ReleaseTitle); + Assert.Single(result.Ratings!); + Assert.Equal(4m, result.Ratings![0].Value); + Assert.Equal(2, result.Contributors!.Count); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Album Artist" && contributor.Role == MediaContributorRole.Performer); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Release Producer" && contributor.Role == MediaContributorRole.Producer); + } + + [Fact] + public void MapAlbum_WhenThereIsNoRelease_ShouldReturnNullReleaseLevelFields() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create( + id: Guid.NewGuid().ToString(), + title: "The Album", + includeDisambiguation: false, + includePrimaryType: false, + secondaryTypes: [], + includeFirstReleaseDate: false, + artistCredit: [], + tags: [], + genres: [], + includeRating: false); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, null); + + // Assert + Assert.Equal("The Album", result.Title); + Assert.Null(result.Disambiguation); + Assert.NotNull(result.ReleaseInfo); + Assert.Null(result.ReleaseInfo.OriginalReleaseDate); + Assert.Null(result.ReleaseInfo.OriginalReleaseYear); + Assert.Null(result.ReleaseInfo.ReReleaseDate); + Assert.Null(result.ReleaseInfo.ReReleaseYear); + Assert.Null(result.ReleaseInfo.ReleaseCountry); + Assert.Null(result.ReleaseInfo.ReleaseVersion); + Assert.Null(result.Language); + Assert.Empty(result.Tags!); + Assert.Empty(result.Genres!); + Assert.Null(result.Script); + Assert.Empty(result.ReleaseTypes!); + Assert.Null(result.ReleaseStatus); + Assert.Null(result.MediaFormat); + Assert.Null(result.Packaging); + Assert.Null(result.TotalDiscs); + Assert.Null(result.TotalTracks); + Assert.Null(result.Barcode); + Assert.Empty(result.CatalogNumbers!); + Assert.Null(result.Label); + Assert.Null(result.ASIN); + Assert.Null(result.MusicBrainzReleaseId); + Assert.Equal(releaseGroup.Id, result.MusicBrainzReleaseGroupId.ToString()); + Assert.Null(result.MusicBrainzReleaseArtistId); + Assert.Empty(result.Contributors!); + Assert.Empty(result.Ratings!); + Assert.Null(result.ReleaseTitle); + } + + [Fact] + public void MapAlbum_WhenTheReleaseGroupTitleIsBlank_ShouldFallBackToTheReleaseTitle() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(title: " ", artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(title: "The Release Title", includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal("The Release Title", result.Title); + Assert.Equal("The Release Title", result.ReleaseTitle); + } + + [Fact] + public void MapAlbum_WhenTheReleaseGroupCreditIsMissing_ShouldFallBackToTheReleaseCredit() + { + // Arrange + Guid releaseArtistId = Guid.NewGuid(); + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + includeReleaseGroup: false, + includeTextRepresentation: false, + media: [], + labelInfo: [], + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "Release Artist", artist: _musicBrainzArtistResponseFixture.Create(id: releaseArtistId.ToString(), name: "Release Artist"))], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal(releaseArtistId, result.MusicBrainzReleaseArtistId); + Assert.Equal("Release Artist", Assert.Single(result.Contributors!).Name!.DisplayName); + } + + [Fact] + public void MapAlbum_WhenTheReleaseGroupCreditHasNoArtistId_ShouldFallBackToTheReleaseCreditId() + { + // Arrange + Guid releaseArtistId = Guid.NewGuid(); + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create( + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "Group Artist", artist: _musicBrainzArtistResponseFixture.Create(id: null, includeId: false, name: "Group Artist"))], + tags: [], + genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + includeReleaseGroup: false, + includeTextRepresentation: false, + media: [], + labelInfo: [], + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "Release Artist", artist: _musicBrainzArtistResponseFixture.Create(id: releaseArtistId.ToString(), name: "Release Artist"))], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal(releaseArtistId, result.MusicBrainzReleaseArtistId); + } + + [Fact] + public void MapAlbum_WhenTheReReleaseIsInTheSameYear_ShouldCollapseTheReRelease() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(firstReleaseDate: "1975-06-01", artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(date: "1975-11-21", includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(new DateOnly(1975, 6, 1), result.ReleaseInfo.OriginalReleaseDate); + Assert.Null(result.ReleaseInfo.ReReleaseDate); + Assert.Null(result.ReleaseInfo.ReReleaseYear); + } + + [Theory] + [InlineData("1975-11-21", 1975, 11, 21, 1975)] // an exact date is parsed fully + [InlineData("1975", null, 0, 0, 1975)] // a bare year yields only the year + [InlineData("Spring 1975", null, 0, 0, 1975)] // an embedded year is extracted when the value is not a date + [InlineData("not a date", null, 0, 0, null)] // an unparsable value yields nothing + [InlineData("2200", null, 0, 0, null)] // a year outside the accepted window yields nothing + [InlineData("2100", null, 0, 0, 2100)] // the upper boundary is accepted + [InlineData(" 1975-11-21 ", 1975, 11, 21, 1975)] // surrounding white space is trimmed + public void MapAlbum_WhenTheFirstReleaseDateHasVariousShapes_ShouldParseIt(string firstReleaseDate, int? expectedYear, int expectedMonth, int expectedDay, int? expectedParsedYear) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(firstReleaseDate: firstReleaseDate, artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, null); + + // Assert + Assert.NotNull(result.ReleaseInfo); + if (expectedMonth == 0) + Assert.Null(result.ReleaseInfo.OriginalReleaseDate); + else + Assert.Equal(new DateOnly(expectedYear!.Value, expectedMonth, expectedDay), result.ReleaseInfo.OriginalReleaseDate); + Assert.Equal(expectedParsedYear, result.ReleaseInfo.OriginalReleaseYear); + } + + [Theory] + [InlineData("US", ReleaseCountry.US)] + [InlineData("us", ReleaseCountry.US)] // the code is matched case insensitively + [InlineData("XE", ReleaseCountry.XE)] // the Europe special code + [InlineData("XW", ReleaseCountry.XW)] // the Worldwide special code + [InlineData("AN", ReleaseCountry.AN)] // the Netherlands Antilles special code + public void MapAlbum_WhenTheReleaseCountryIsKnown_ShouldMapIt(string country, ReleaseCountry expected) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(country: country, includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal(expected, result.ReleaseInfo!.ReleaseCountry); + } + + [Theory] + [InlineData("ZZ")] // a valid shape but not a known code + [InlineData("")] // an empty value + [InlineData(" ")] // only white space + public void MapAlbum_WhenTheReleaseCountryIsUnknown_ShouldReturnNullCountry(string country) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(country: country, includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Null(result.ReleaseInfo!.ReleaseCountry); + } + + [Theory] + [InlineData("album", MusicReleaseType.Album)] + [InlineData("single", MusicReleaseType.Single)] + [InlineData("ep", MusicReleaseType.Ep)] + [InlineData("broadcast", MusicReleaseType.Broadcast)] + [InlineData("other", MusicReleaseType.Other)] + [InlineData("compilation", MusicReleaseType.Compilation)] + [InlineData("live", MusicReleaseType.Live)] + [InlineData("soundtrack", MusicReleaseType.Soundtrack)] + [InlineData("spokenword", MusicReleaseType.SpokenWord)] + [InlineData("audio drama", MusicReleaseType.AudioDrama)] + [InlineData("audiobook", MusicReleaseType.AudioBook)] + [InlineData("demo", MusicReleaseType.Demo)] + [InlineData("dj-mix", MusicReleaseType.DjMix)] + [InlineData("field recording", MusicReleaseType.FieldRecording)] + [InlineData("interview", MusicReleaseType.Interview)] + [InlineData("mixtape/street", MusicReleaseType.Mixtape)] + [InlineData("remix", MusicReleaseType.Remix)] + public void MapAlbum_WhenThePrimaryReleaseTypeIsKnown_ShouldMapIt(string primaryType, MusicReleaseType expected) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(primaryType: primaryType, secondaryTypes: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, null); + + // Assert + Assert.Equal([expected], result.ReleaseTypes); + } + + [Fact] + public void MapAlbum_WhenTheReleaseTypesContainDuplicatesAndUnknowns_ShouldKeepOnlyTheDistinctKnownOnes() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(primaryType: "Album", secondaryTypes: ["Live", "live", "made-up", "Album"], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, null); + + // Assert + Assert.Equal([MusicReleaseType.Album, MusicReleaseType.Live], result.ReleaseTypes); + } + + [Theory] + [InlineData("official", MusicReleaseStatus.Official)] + [InlineData("promotion", MusicReleaseStatus.Promotion)] + [InlineData("bootleg", MusicReleaseStatus.Bootleg)] + [InlineData("pseudo-release", MusicReleaseStatus.PseudoRelease)] + [InlineData("withdrawn", MusicReleaseStatus.Withdrawn)] + [InlineData("cancelled", MusicReleaseStatus.Cancelled)] + [InlineData("expunged", MusicReleaseStatus.Expunged)] + public void MapAlbum_WhenTheReleaseStatusIsKnown_ShouldMapIt(string status, MusicReleaseStatus expected) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(status: status, includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal(expected, result.ReleaseStatus); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + [InlineData("made-up")] + public void MapAlbum_WhenTheReleaseStatusIsUnknown_ShouldReturnNullStatus(string? status) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(status: status, includeStatus: status is not null, includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Null(result.ReleaseStatus); + } + + [Theory] + [InlineData("cd", MusicMediaFormat.CD)] + [InlineData("vinyl", MusicMediaFormat.Vinyl)] + [InlineData("12\" vinyl", MusicMediaFormat.Inch12Vinyl)] + [InlineData("10\" vinyl", MusicMediaFormat.Inch10Vinyl)] + [InlineData("7\" vinyl", MusicMediaFormat.Inch7Vinyl)] + [InlineData("digital media", MusicMediaFormat.DigitalMedia)] + [InlineData("cassette", MusicMediaFormat.Cassette)] + [InlineData("dvd", MusicMediaFormat.DVD)] + [InlineData("dvd-video", MusicMediaFormat.DVDVideo)] + [InlineData("dvd-audio", MusicMediaFormat.DVDAudio)] + [InlineData("sacd", MusicMediaFormat.SACD)] + [InlineData("hybrid sacd", MusicMediaFormat.HybridSACD)] + [InlineData("blu-ray", MusicMediaFormat.BluRay)] + [InlineData("minidisc", MusicMediaFormat.MiniDisc)] + [InlineData("8cm cd", MusicMediaFormat.Cm8CD)] + [InlineData("dat", MusicMediaFormat.DAT)] + [InlineData("other", MusicMediaFormat.Other)] + [InlineData("made-up", MusicMediaFormat.Other)] // an unknown format still maps to Other + public void MapAlbum_WhenTheMediaFormatIsKnownOrUnknownButPresent_ShouldMapIt(string format, MusicMediaFormat expected) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + media: [_musicBrainzMediumResponseFixture.Create(position: 1, format: format, tracks: [], trackCount: 0)], + includeReleaseGroup: false, + includeTextRepresentation: false, + labelInfo: [], + artistCredit: [], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal(expected, result.MediaFormat); + } + + [Theory] + [InlineData("book", MusicReleasePackaging.Book)] + [InlineData("box", MusicReleasePackaging.Box)] + [InlineData("cardboard/paper sleeve", MusicReleasePackaging.CardboardPaperSleeve)] + [InlineData("cassette case", MusicReleasePackaging.CassetteCase)] + [InlineData("clamshell case", MusicReleasePackaging.ClamshellCase)] + [InlineData("digibook", MusicReleasePackaging.Digibook)] + [InlineData("digifile", MusicReleasePackaging.Digifile)] + [InlineData("digipak", MusicReleasePackaging.Digipak)] + [InlineData("discbox slider", MusicReleasePackaging.DiscboxSlider)] + [InlineData("fatbox", MusicReleasePackaging.Fatbox)] + [InlineData("gatefold cover", MusicReleasePackaging.GatefoldCover)] + [InlineData("jewel case", MusicReleasePackaging.JewelCase)] + [InlineData("keep case", MusicReleasePackaging.KeepCase)] + [InlineData("longbox", MusicReleasePackaging.Longbox)] + [InlineData("metal tin", MusicReleasePackaging.MetalTin)] + [InlineData("plastic sleeve", MusicReleasePackaging.PlasticSleeve)] + [InlineData("slidepack", MusicReleasePackaging.Slidepack)] + [InlineData("slim jewel case", MusicReleasePackaging.SlimJewelCase)] + [InlineData("slipcase", MusicReleasePackaging.Slipcase)] + [InlineData("snap case", MusicReleasePackaging.SnapCase)] + [InlineData("snappack", MusicReleasePackaging.SnapPack)] + [InlineData("super jewel box", MusicReleasePackaging.SuperJewelBox)] + [InlineData("none", MusicReleasePackaging.None)] + [InlineData("other", MusicReleasePackaging.Other)] + [InlineData("made-up", MusicReleasePackaging.Other)] // an unknown packaging still maps to Other + public void MapAlbum_WhenThePackagingIsKnownOrUnknownButPresent_ShouldMapIt(string packaging, MusicReleasePackaging expected) + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(packaging: packaging, includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal(expected, result.Packaging); + } + + [Fact] + public void MapAlbum_WhenTheMediaAreMissing_ShouldReturnNullDiscAndTrackCounts() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(media: [], includeReleaseGroup: false, includeTextRepresentation: false, labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Null(result.TotalDiscs); + Assert.Null(result.TotalTracks); + } + + [Fact] + public void MapAlbum_WhenTheMediaFormatIsBlank_ShouldReturnNullMediaFormat() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + media: [_musicBrainzMediumResponseFixture.Create(position: 1, format: " ", tracks: [], trackCount: 0)], + includeReleaseGroup: false, + includeTextRepresentation: false, + labelInfo: [], + artistCredit: [], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Null(result.MediaFormat); + } + + [Fact] + public void MapAlbum_WhenThePackagingIsBlank_ShouldReturnNullPackaging() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(packaging: " ", includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Null(result.Packaging); + } + + [Fact] + public void MapTrack_WhenEveryFieldIsPresent_ShouldMapEveryField() + { + // Arrange + Guid recordingId = Guid.NewGuid(); + Guid workId = Guid.NewGuid(); + MusicBrainzWorkResponse work = _musicBrainzWorkResponseFixture.Create( + id: workId.ToString(), + title: "The Work", + type: "Song", + disambiguation: "the work", + languages: ["eng"], + iswcs: ["T-010.154.482-4"], + relations: [_musicBrainzRelationResponseFixture.Create(type: "composer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Work Composer"))], + tags: [], + genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + date: "1975-11-21", + textRepresentation: _musicBrainzTextRepresentationResponseFixture.Create(language: "eng", script: "Latn"), + includeReleaseGroup: false, + media: [], + labelInfo: [], + artistCredit: [], + tags: [], + genres: []); + MusicBrainzRecordingResponse recording = _musicBrainzRecordingResponseFixture.Create( + id: recordingId.ToString(), + title: " The Track ", + disambiguation: "the track", + length: 215_400, + isVideo: true, + firstReleaseDate: "1975-10-31", + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "The Track Artist", includeJoinPhrase: false)], + isrcs: ["US1A2B3C4D5E", "", " "], + releases: [], + tags: [_musicBrainzTagResponseFixture.Create(name: "Rock")], + genres: [_musicBrainzTagResponseFixture.Create(name: "Pop")], + relations: [_musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Producer"))], + rating: _musicBrainzRatingResponseFixture.Create(value: 3m, votesCount: 4), + includeRating: true); + + // Act + AudioMetadataDto result = MusicBrainzMapper.MapTrack(recording, work, release); + + // Assert + Assert.Equal("The Track", result.Title); + Assert.Null(result.OriginalTitle); + Assert.Null(result.Description); + Assert.Equal("the track", result.Disambiguation); + Assert.NotNull(result.ReleaseInfo); + Assert.Equal(new DateOnly(1975, 10, 31), result.ReleaseInfo.OriginalReleaseDate); + Assert.Equal(1975, result.ReleaseInfo.OriginalReleaseYear); + Assert.Null(result.ReleaseInfo.ReReleaseDate); + Assert.Null(result.ReleaseInfo.ReReleaseYear); + Assert.Null(result.ReleaseInfo.ReleaseCountry); + Assert.Null(result.ReleaseInfo.ReleaseVersion); + Assert.NotNull(result.Language); + Assert.Equal("en", result.Language.LanguageCode); + Assert.Null(result.OriginalLanguage); + Assert.Equal(["Rock"], result.Tags!.Select(tag => tag.Name)); + Assert.Equal(["Pop"], result.Genres!.Select(genre => genre.Name)); + Assert.Equal("Latn", result.Script); + Assert.Null(result.Key); + Assert.Null(result.Bpm); + Assert.True(result.IsVideo); + Assert.NotNull(result.Work); + Assert.Equal(workId, result.Work.MusicBrainzWorkId); + Assert.Equal("The Work", result.Work.Title); + Assert.Equal("Song", result.Work.Type); + Assert.Equal("en", Assert.Single(result.Work.Languages!).LanguageCode); + Assert.Equal("T-010.154.482-4", Assert.Single(result.Work.Iswcs!)); + Assert.Equal("US1A2B3C4D5E", Assert.Single(result.Isrcs!).Value); + Assert.Null(result.Moods); + Assert.Equal(215, result.DurationInSeconds); + Assert.Null(result.SampleRate); + Assert.Null(result.Channels); + Assert.Null(result.BitDepth); + Assert.Null(result.AudioCodec); + Assert.Null(result.Bitrate); + Assert.Equal(recordingId, result.MusicBrainzRecordingId); + Assert.Null(result.MusicBrainzTrackId); + Assert.Single(result.Ratings!); + Assert.Equal(3m, result.Ratings![0].Value); + Assert.Equal(4, result.Ratings[0].VoteCount); + Assert.Equal(3, result.Contributors!.Count); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Track Artist" && contributor.Role == MediaContributorRole.Performer); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Producer" && contributor.Role == MediaContributorRole.Producer); + Assert.Contains(result.Contributors, contributor => contributor.Name!.DisplayName == "The Work Composer" && contributor.Role == MediaContributorRole.Composer); + } + + [Fact] + public void MapTrack_WhenTheRecordingHasNoFirstReleaseDate_ShouldFallBackToTheReleaseDate() + { + // Arrange + MusicBrainzRecordingResponse recording = _musicBrainzRecordingResponseFixture.Create( + id: Guid.NewGuid().ToString(), + includeFirstReleaseDate: false, + artistCredit: [], + isrcs: [], + tags: [], + genres: [], + relations: [], + includeRating: false); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(date: "1975-10-31", includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AudioMetadataDto result = MusicBrainzMapper.MapTrack(recording, null, release); + + // Assert + Assert.Equal(new DateOnly(1975, 10, 31), result.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(1975, result.ReleaseInfo.OriginalReleaseYear); + } + + [Fact] + public void MapTrack_WhenTheRecordingHasAFirstReleaseDate_ShouldPreferItOverTheReleaseDate() + { + // Arrange + MusicBrainzRecordingResponse recording = _musicBrainzRecordingResponseFixture.Create( + id: Guid.NewGuid().ToString(), + firstReleaseDate: "1975-11-21", + artistCredit: [], + isrcs: [], + tags: [], + genres: [], + relations: [], + includeRating: false); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create(date: "2011-03-14", includeReleaseGroup: false, includeTextRepresentation: false, media: [], labelInfo: [], artistCredit: [], tags: [], genres: []); + + // Act + AudioMetadataDto result = MusicBrainzMapper.MapTrack(recording, null, release); + + // Assert + Assert.Equal(new DateOnly(1975, 11, 21), result.ReleaseInfo!.OriginalReleaseDate); + Assert.Equal(1975, result.ReleaseInfo.OriginalReleaseYear); + } + + [Theory] + [InlineData(null, null)] // no length at all + [InlineData(0L, null)] // a zero length is treated as unknown + [InlineData(-100L, null)] // a negative length is treated as unknown + [InlineData(1500L, 1)] // milliseconds are truncated to whole seconds + [InlineData(215_400L, 215)] + public void MapTrack_WhenTheRecordingHasALength_ShouldMapTheDurationInSeconds(long? length, int? expectedSeconds) + { + // Arrange + MusicBrainzRecordingResponse recording = _musicBrainzRecordingResponseFixture.Create( + id: Guid.NewGuid().ToString(), + length: length, + includeLength: length is not null, + artistCredit: [], + isrcs: [], + tags: [], + genres: [], + relations: [], + includeRating: false); + + // Act + AudioMetadataDto result = MusicBrainzMapper.MapTrack(recording, null, null); + + // Assert + Assert.Equal(expectedSeconds, result.DurationInSeconds); + } + + [Fact] + public void MapTrack_WhenTheVideoFlagIsMissing_ShouldReturnFalse() + { + // Arrange + MusicBrainzRecordingResponse recording = _musicBrainzRecordingResponseFixture.Create( + id: Guid.NewGuid().ToString(), + includeVideo: false, + artistCredit: [], + isrcs: [], + tags: [], + genres: [], + relations: [], + includeRating: false); + + // Act + AudioMetadataDto result = MusicBrainzMapper.MapTrack(recording, null, null); + + // Assert + Assert.False(result.IsVideo); + } + + [Fact] + public void MapTrack_WhenTheOptionalCollectionsAreEmpty_ShouldReturnNullWorkAndEmptyCollections() + { + // Arrange + MusicBrainzRecordingResponse recording = _musicBrainzRecordingResponseFixture.Create( + id: "not-a-guid", + title: " ", + includeDisambiguation: false, + includeLength: false, + includeVideo: false, + includeFirstReleaseDate: false, + artistCredit: [], + isrcs: [], + releases: [], + tags: [], + genres: [], + relations: [], + includeRating: false); + + // Act + AudioMetadataDto result = MusicBrainzMapper.MapTrack(recording, null, null); + + // Assert + Assert.Null(result.Title); + Assert.Null(result.Disambiguation); + Assert.NotNull(result.ReleaseInfo); + Assert.Null(result.ReleaseInfo.OriginalReleaseDate); + Assert.Null(result.ReleaseInfo.OriginalReleaseYear); + Assert.Null(result.Language); + Assert.Empty(result.Tags!); + Assert.Empty(result.Genres!); + Assert.Null(result.Script); + Assert.Null(result.Work); + Assert.Empty(result.Isrcs!); + Assert.Null(result.DurationInSeconds); + Assert.Null(result.MusicBrainzRecordingId); + Assert.Empty(result.Contributors!); + Assert.Empty(result.Ratings!); + } + + [Theory] + [InlineData(1.0)] // a value only + [InlineData(2.5)] + public void MapArtist_WhenOnlyTheRatingValueIsPresent_ShouldMapItWithANullVoteCount(decimal value) + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [], + aliases: [], + tags: [], + genres: [], + rating: _musicBrainzRatingResponseFixture.Create(value: value, includeVotesCount: false), + includeRating: true); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + AudioRatingDto rating = Assert.Single(result.Ratings!); + Assert.Equal(value, rating.Value); + Assert.Null(rating.VoteCount); + } + + [Fact] + public void MapArtist_WhenOnlyTheRatingVoteCountIsPresent_ShouldMapItWithANullValue() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [], + aliases: [], + tags: [], + genres: [], + rating: _musicBrainzRatingResponseFixture.Create(includeValue: false, votesCount: 7), + includeRating: true); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + AudioRatingDto rating = Assert.Single(result.Ratings!); + Assert.Null(rating.Value); + Assert.Equal(7, rating.VoteCount); + } + + [Fact] + public void MapArtist_WhenTheRatingHasNoValueNorVotes_ShouldReturnAnEmptyRatingList() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [], + aliases: [], + tags: [], + genres: [], + rating: _musicBrainzRatingResponseFixture.Create(includeValue: false, includeVotesCount: false), + includeRating: true); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Empty(result.Ratings!); + } + + [Theory] + [InlineData("eng", "en", "English")] // a three letter code maps to the neutral culture + [InlineData("deu", "de", "German")] + [InlineData("en", "en", "English")] // a two letter code maps too + [InlineData("zxx", "zxx", "No linguistic content")] // a special MusicBrainz code + [InlineData("mul", "mul", "Multiple languages")] + [InlineData("und", "und", "Undetermined")] + [InlineData("eng/ara", "en", "English")] // only the first code of a multi language value is used + [InlineData("/", "/", "/")] // a value with no usable part falls back to the raw code + [InlineData(" eng ", "en", "English")] // surrounding white space is trimmed + [InlineData("qqq", "qqq", "qqq")] // an unknown code falls back to the raw code + public void MapTrack_WhenTheLanguageCodeIsPresent_ShouldMapIt(string language, string expectedCode, string expectedName) + { + // Arrange + MusicBrainzRecordingResponse recording = _musicBrainzRecordingResponseFixture.Create( + id: Guid.NewGuid().ToString(), + artistCredit: [], + isrcs: [], + tags: [], + genres: [], + relations: [], + includeRating: false); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + textRepresentation: _musicBrainzTextRepresentationResponseFixture.Create(language: language, includeScript: false), + includeReleaseGroup: false, + media: [], + labelInfo: [], + artistCredit: [], + tags: [], + genres: []); + + // Act + AudioMetadataDto result = MusicBrainzMapper.MapTrack(recording, null, release); + + // Assert + Assert.NotNull(result.Language); + Assert.Equal(expectedCode, result.Language.LanguageCode); + Assert.Equal(expectedName, result.Language.LanguageName); + } + + [Fact] + public void MapWork_WhenEveryFieldIsPresent_ShouldMapEveryField() + { + // Arrange + Guid workId = Guid.NewGuid(); + MusicBrainzWorkResponse work = _musicBrainzWorkResponseFixture.Create( + id: workId.ToString(), + title: " The Work ", + type: "Song", + languages: ["eng", "zxx", ""], + iswcs: ["T-1", " ", "T-2"]); + + // Act + MusicWorkDto result = MusicBrainzMapper.MapWork(work); + + // Assert + Assert.Equal(workId, result.MusicBrainzWorkId); + Assert.Equal("The Work", result.Title); + Assert.Equal("Song", result.Type); + Assert.Equal(2, result.Languages!.Count); + Assert.Equal("en", result.Languages[0].LanguageCode); + Assert.Equal("zxx", result.Languages[1].LanguageCode); + Assert.Equal(["T-1", "T-2"], result.Iswcs); + } + + [Fact] + public void MapWork_WhenTheIdentifierIsNotAGuid_ShouldReturnNullIdentifier() + { + // Arrange + MusicBrainzWorkResponse work = _musicBrainzWorkResponseFixture.Create(id: "not-a-guid", includeTitle: false, includeType: false, languages: [], iswcs: []); + + // Act + MusicWorkDto result = MusicBrainzMapper.MapWork(work); + + // Assert + Assert.Null(result.MusicBrainzWorkId); + Assert.Null(result.Title); + Assert.Null(result.Type); + Assert.Empty(result.Languages!); + Assert.Empty(result.Iswcs!); + } + + [Fact] + public void MapAlbum_WhenTheReleaseGroupCreditsHaveNoUsableName_ShouldFallBackToTheReleaseCredits() + { + // Arrange + Guid releaseArtistId = Guid.NewGuid(); + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create( + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: null, includeName: false, includeArtist: false)], + tags: [], + genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + includeReleaseGroup: false, + includeTextRepresentation: false, + media: [], + labelInfo: [], + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "Release Artist", artist: _musicBrainzArtistResponseFixture.Create(id: releaseArtistId.ToString(), name: "Release Artist"))], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Equal(releaseArtistId, result.MusicBrainzReleaseArtistId); + Assert.Equal("Release Artist", Assert.Single(result.Contributors!).Name!.DisplayName); + } + + [Fact] + public void MapAlbum_WhenTheReleaseGroupCreditHasNoNameButItsArtistDoes_ShouldFallBackToTheArtistName() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create( + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: null, includeName: false, artist: _musicBrainzArtistResponseFixture.Create(name: "The Artist"))], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, null); + + // Assert + Assert.Equal("The Artist", Assert.Single(result.Contributors!).Name!.DisplayName); + } + + [Fact] + public void MapAlbum_WhenAReleaseRelationTargetsAnArtistWithoutAName_ShouldSkipIt() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create(artistCredit: [], tags: [], genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + includeReleaseGroup: false, + includeTextRepresentation: false, + media: [], + labelInfo: [], + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "The Artist", includeJoinPhrase: false)], + tags: [], + genres: [], + relations: [_musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: false)]); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + MediaContributorDto contributor = Assert.Single(result.Contributors!); + Assert.Equal("The Artist", contributor.Name!.DisplayName); + } + + [Fact] + public void MapArtist_WhenAUrlRelationPrecedesAnOfficialHomepage_ShouldPreferTheOfficialHomepage() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: + [ + _musicBrainzRelationResponseFixture.Create(type: "wikidata", targetType: "url", includeUrl: true, url: _musicBrainzUrlResponseFixture.Create(resource: "https://wikidata.example")), + _musicBrainzRelationResponseFixture.Create(type: "official homepage", targetType: "url", includeUrl: true, url: _musicBrainzUrlResponseFixture.Create(resource: "https://artist.example")) + ], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal("https://artist.example", result.Website); + } + + [Fact] + public void MapArtist_WhenAnArtistRelationHasNoArtist_ShouldSkipIt() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: [_musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: false)], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Empty(result.Contributors!); + } + + [Fact] + public void MapArtist_WhenTheSameNameIsCreditedWithTwoRoles_ShouldKeepBothContributors() + { + // Arrange + MusicBrainzArtistResponse artist = _musicBrainzArtistResponseFixture.Create( + relations: + [ + _musicBrainzRelationResponseFixture.Create(type: "producer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Person")), + _musicBrainzRelationResponseFixture.Create(type: "composer", targetType: "artist", includeArtist: true, artist: _musicBrainzArtistResponseFixture.Create(name: "The Person")) + ], + aliases: [], + tags: [], + genres: []); + + // Act + ArtistMetadataDto result = MusicBrainzMapper.MapArtist(artist); + + // Assert + Assert.Equal(2, result.Contributors!.Count); + } + + [Fact] + public void MapAlbum_WhenNeitherCreditHasAnArtistIdentifier_ShouldReturnNullReleaseArtistId() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create( + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "Group Artist", includeArtist: false)], + tags: [], + genres: []); + MusicBrainzReleaseResponse release = _musicBrainzReleaseResponseFixture.Create( + includeReleaseGroup: false, + includeTextRepresentation: false, + media: [], + labelInfo: [], + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "Release Artist", includeArtist: false)], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, release); + + // Assert + Assert.Null(result.MusicBrainzReleaseArtistId); + } + + [Fact] + public void MapAlbum_WhenTheReleaseIsNullAndTheCreditHasNoArtistIdentifier_ShouldReturnNullReleaseArtistId() + { + // Arrange + MusicBrainzReleaseGroupResponse releaseGroup = _musicBrainzReleaseGroupResponseFixture.Create( + artistCredit: [_musicBrainzArtistCreditResponseFixture.Create(name: "Group Artist", includeArtist: false)], + tags: [], + genres: []); + + // Act + AlbumMetadataDto result = MusicBrainzMapper.MapAlbum(releaseGroup, null); + + // Assert + Assert.Null(result.MusicBrainzReleaseArtistId); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzAlbumMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzAlbumMetadataProviderTests.cs new file mode 100644 index 00000000..817b050a --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzAlbumMetadataProviderTests.cs @@ -0,0 +1,592 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.MusicBrainz.Core; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzAlbumMetadataProviderTests +{ + private static readonly Guid s_releaseId = Guid.Parse("11111111-1111-1111-1111-111111111111"); + private static readonly Guid s_releaseGroupId = Guid.Parse("22222222-2222-2222-2222-222222222222"); + + private readonly AlbumMetadataLookupDtoFixture _albumMetadataLookupDtoFixture = new(); + private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new(); + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Arrange + (MusicBrainzAlbumMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + string result = sut.Name; + + // Assert + Assert.Equal("MusicBrainz", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Arrange + (MusicBrainzAlbumMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + IReadOnlyList result = sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnTrue() + { + // Arrange + (MusicBrainzAlbumMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + bool result = sut.RequiresWebAccess; + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task GetSearchResultsAsync_WhenTheTitleIsMissing_ShouldReturnAnEmptyCollectionWithoutAnyRequest(string? title) + { + // Arrange + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}")); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: title); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + Assert.Equal(0, handler.CallCount); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheSearchReturnsReleaseGroups_ShouldMapEveryTitledOneAndSkipTheUntitledOnes() + { + // Arrange + const string SEARCH_JSON = """ + { + "count": 3, + "release-groups": [ + { "id": "22222222-2222-2222-2222-222222222222", "title": "The Album", "primary-type": "Album" }, + { "id": "33333333-3333-3333-3333-333333333333", "title": "Other Album" }, + { "id": "44444444-4444-4444-4444-444444444444", "title": null } + ] + } + """; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: " The \"Album\" ", artistName: " The Artist "); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal("The Album", result[0].Title); + Assert.Equal("Other Album", result[1].Title); + Assert.Equal(1, handler.CallCount); + Assert.Contains("limit=10", handler.Requests[0].RequestUri!.Query); + // the quotes are removed from the built query, and the artist constraint is appended + string query = Uri.UnescapeDataString(handler.Requests[0].RequestUri!.Query); + Assert.Contains("releasegroup:\"The Album\"", query); + Assert.Contains("AND artist:\"The Artist\"", query); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseAndTheArtistArePresent_ShouldMapBothTheReleaseGroupAndTheRelease() + { + // Arrange + string releaseJson = ReleaseJson(s_releaseId, "The Release", s_releaseGroupId, "The Album", "1975-06-01", "Official", "1975-11-21", "US"); + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : releaseJson)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Album", result.Title); + Assert.Equal(s_releaseId, result.MusicBrainzReleaseId); + Assert.Equal(s_releaseGroupId, result.MusicBrainzReleaseGroupId); + Assert.Equal("The Release", result.ReleaseTitle); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseIdentifierIsPresentButTheReleaseIsNotFound_ShouldReturnNull() + { + // Arrange + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseCarriesAnUnparsableReleaseGroupIdentifier_ShouldMapOnlyTheRelease() + { + // Arrange + const string RELEASE_JSON = """ + { + "id": "11111111-1111-1111-1111-111111111111", + "title": "The Release", + "release-group": { "id": "not-a-guid", "title": "The Album" } + } + """; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(RELEASE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Release", result.Title); + Assert.Null(result.MusicBrainzReleaseGroupId); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseDoesNotReferenceAReleaseGroup_ShouldMapOnlyTheRelease() + { + // Arrange + const string RELEASE_JSON = """{"id":"11111111-1111-1111-1111-111111111111","title":"The Release"}"""; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(RELEASE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Release", result.Title); + Assert.Null(result.MusicBrainzReleaseGroupId); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenThereIsNeitherAnIdentifierNorATitle_ShouldReturnNullWithoutAnyRequest() + { + // Arrange + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}")); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: " "); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(0, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenOnlyTheTitleIsPresent_ShouldSearchAndResolveTheFirstReleaseGroup() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"release-groups":[{"id":"22222222-2222-2222-2222-222222222222","title":"The Album"}]}"""; + const string BROWSE_JSON = """{"release-count":0,"releases":[]}"""; + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(Route(request, SEARCH_JSON, releaseGroupJson, BROWSE_JSON))); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: "The Album"); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Album", result.Title); + Assert.Equal(s_releaseGroupId, result.MusicBrainzReleaseGroupId); + // the search, the detail lookup and the release browse are all used + Assert.Equal(3, handler.CallCount); + Assert.Contains("limit=1", handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTitleSearchReturnsNothing_ShouldReturnNull() + { + // Arrange + const string SEARCH_JSON = """{"count":0,"release-groups":[]}"""; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: "The Album"); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheSearchResultIdentifierIsNotAGuid_ShouldReturnNull() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"release-groups":[{"id":"not-a-guid","title":"The Album"}]}"""; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", title: "The Album"); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseGroupIdentifierIsPresent_ShouldFetchItDirectly() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseGroupJson)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_releaseGroupId, result.MusicBrainzReleaseGroupId); + Assert.Contains($"/release-group/{s_releaseGroupId:D}", handler.Requests[0].RequestUri!.AbsolutePath); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseGroupIsUnknownButATitleIsPresent_ShouldFallBackToTheTitleSearch() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"release-groups":[{"id":"22222222-2222-2222-2222-222222222222","title":"The Album"}]}"""; + const string BROWSE_JSON = """{"release-count":0,"releases":[]}"""; + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => + request.RequestUri!.Query.Contains("query=") + ? Json(SEARCH_JSON) + : request.RequestUri.AbsolutePath.Contains("/release-group/") + ? callIndex == 1 + ? new HttpResponseMessage(HttpStatusCode.NotFound) + : Json(releaseGroupJson) + : Json(BROWSE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, title: "The Album"); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Album", result.Title); + Assert.Equal(s_releaseGroupId, result.MusicBrainzReleaseGroupId); + Assert.Equal(4, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseGroupIdentifierIsPresentButTheDetailIsMissing_ShouldReturnNull() + { + // Arrange + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheLocalTrackCountIsUnknown_ShouldNotSelectAnyRelease() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseGroupJson)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: null); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(result.MusicBrainzReleaseId); + } + + [Fact] + public async Task GetMetadataAsync_WhenNoReleaseMatchesTheLocalTrackCount_ShouldNotSelectAnyRelease() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + const string BROWSE_JSON = """{"release-count":1,"releases":[{"id":"11111111-1111-1111-1111-111111111111","title":"The Release","media":[{"position":1,"track-count":9}]}]}"""; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 12); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(result.MusicBrainzReleaseId); + } + + [Fact] + public async Task GetMetadataAsync_WhenSeveralReleasesMatch_ShouldSelectTheBestScoredOne() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + const string BROWSE_JSON = """ + { + "release-count": 3, + "releases": [ + { "id": "11111111-1111-1111-1111-111111111111", "title": "Bootleg Edition", "status": "Bootleg", "date": "1975", "media": [ { "position": 1, "track-count": 2 } ] }, + { "id": "22222222-2222-2222-2222-222222222222", "title": "Official Edition", "status": "Official", "date": "1975-11-21", "barcode": "123", "label-info": [ { "catalog-number": "CAT" } ], "media": [ { "position": 1, "track-count": 2 } ] }, + { "id": "33333333-3333-3333-3333-333333333333", "title": "Promotion Edition", "status": "Promotion", "date": "1980-01-01", "media": [ { "position": 1, "track-count": 2 } ] } + ] + } + """; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 2, releaseYear: 1975); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(Guid.Parse("22222222-2222-2222-2222-222222222222"), result.MusicBrainzReleaseId); + Assert.Equal("Official Edition", result.ReleaseTitle); + } + + [Fact] + public async Task GetMetadataAsync_WhenSeveralReleasesScoreTheSame_ShouldSelectTheFirstOne() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + const string BROWSE_JSON = """ + { + "release-count": 2, + "releases": [ + { "id": "11111111-1111-1111-1111-111111111111", "title": "First Edition", "status": "Official", "date": "1975-11-21", "media": [ { "position": 1, "track-count": 2 } ] }, + { "id": "22222222-2222-2222-2222-222222222222", "title": "Second Edition", "status": "Official", "date": "1975-11-21", "media": [ { "position": 1, "track-count": 2 } ] } + ] + } + """; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 2, releaseYear: 1975); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(Guid.Parse("11111111-1111-1111-1111-111111111111"), result.MusicBrainzReleaseId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseDateIsUnparsable_ShouldStillSelectTheMatchingRelease() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + const string BROWSE_JSON = """ + { + "release-count": 2, + "releases": [ + { "id": "11111111-1111-1111-1111-111111111111", "title": "Unparsable Edition", "status": "Official", "date": "not a date", "media": [ { "position": 1, "track-count": 2 } ] }, + { "id": "22222222-2222-2222-2222-222222222222", "title": "Matching Edition", "status": "Official", "date": "1975-06-01", "media": [ { "position": 1, "track-count": 2 } ] } + ] + } + """; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 2, releaseYear: 1975); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(Guid.Parse("22222222-2222-2222-2222-222222222222"), result.MusicBrainzReleaseId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseCarriesSeveralCatalogNumbers_ShouldMapAllOfThem() + { + // Arrange + const string RELEASE_JSON = """ + { + "id": "11111111-1111-1111-1111-111111111111", + "title": "A Night at the Opera", + "release-group": { "id": "22222222-2222-2222-2222-222222222222", "title": "A Night at the Opera", "primary-type": "Album" }, + "label-info": [ + { "catalog-number": "EMC 4008", "label": { "name": "EMI" } }, + { "catalog-number": "0C 066-98 485", "label": { "name": "EMI" } }, + { "catalog-number": "EMC 4008", "label": { "name": "EMI" } } + ] + } + """; + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "A Night at the Opera", "Album", "1975-11-21"); + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : RELEASE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.NotNull(result.CatalogNumbers); + // every distinct catalog number is kept, while the duplicates are removed. + Assert.Equal(["EMC 4008", "0C 066-98 485"], result.CatalogNumbers); + Assert.Equal("EMI", result.Label); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheMatchingReleaseHasNoMedia_ShouldStillSelectIt() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + const string BROWSE_JSON = """{"release-count":1,"releases":[{"id":"11111111-1111-1111-1111-111111111111","title":"Empty Edition","status":"Official","media":[]}]}"""; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 0); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(Guid.Parse("11111111-1111-1111-1111-111111111111"), result.MusicBrainzReleaseId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseDatesAreMissingOrTooShort_ShouldStillSelectAMatchingRelease() + { + // Arrange + string releaseGroupJson = ReleaseGroupJson(s_releaseGroupId, "The Album", "Album", "1975-06-01"); + const string BROWSE_JSON = """ + { + "release-count": 2, + "releases": [ + { "id": "11111111-1111-1111-1111-111111111111", "status": "Official", "media": [ { "position": 1, "track-count": 2 } ] }, + { "id": "22222222-2222-2222-2222-222222222222", "status": "Official", "date": "75", "media": [ { "position": 1, "track-count": 2 } ] } + ] + } + """; + (MusicBrainzAlbumMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(request.RequestUri!.AbsolutePath.Contains("/release-group/") ? releaseGroupJson : BROWSE_JSON)); + AlbumMetadataLookupDto lookup = _albumMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseGroupId: s_releaseGroupId, trackCount: 2, releaseYear: 1975); + + // Act + AlbumMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(Guid.Parse("11111111-1111-1111-1111-111111111111"), result.MusicBrainzReleaseId); + } + + /// + /// Creates a whose requests are answered by the provided stub handler. + /// + /// The factory that produces the response of a request. + /// The created provider and its stub handler. + private (MusicBrainzAlbumMetadataProvider Provider, StubHttpMessageHandler Handler) CreateProvider(Func responseFactory) + { + StubHttpMessageHandler handler = new(responseFactory); + MusicBrainzSettingsProvider settingsProvider = new(null, MusicBrainzPlugin.s_pluginId, _musicBrainzSettingsDtoFixture.Create( + baseUrl: "http://localhost/", + searchResultLimit: 10, + releaseLookupLimit: 25, + minimumRequestInterval: TimeSpan.Zero)); + MusicBrainzHttpClient httpClient = new(new HttpClient(handler), settingsProvider, new MusicBrainzRequestThrottle(), new MusicBrainzResponseCache()); + return (new MusicBrainzAlbumMetadataProvider(httpClient, settingsProvider), handler); + } + + /// + /// Routes a request to the search, release group or release browse JSON, based on the request URI. + /// + /// The request to route. + /// The JSON returned for a search request. + /// The JSON returned for a release group detail request. + /// The JSON returned for a release browse request. + /// The JSON that answers the request. + private static string Route(HttpRequestMessage request, string searchString, string releaseGroupJson, string browseJson) + { + if (request.RequestUri!.Query.Contains("query=", StringComparison.Ordinal)) + return searchString; + return request.RequestUri.AbsolutePath.Contains("/release-group/", StringComparison.Ordinal) ? releaseGroupJson : browseJson; + } + + /// + /// Creates the JSON of a release group response. + /// + /// The MusicBrainz identifier of the release group. + /// The title of the release group. + /// The primary type of the release group. + /// The first release date of the release group. + /// The JSON of the release group response. + private static string ReleaseGroupJson(Guid id, string title, string primaryType, string firstReleaseDate) + { + return $$"""{"id":"{{id:D}}","title":"{{title}}","primary-type":"{{primaryType}}","first-release-date":"{{firstReleaseDate}}"}"""; + } + + /// + /// Creates the JSON of a release response. + /// + /// The MusicBrainz identifier of the release. + /// The title of the release. + /// The MusicBrainz identifier of the release group. + /// The title of the release group. + /// The first release date of the release group. + /// The date the release was issued. + /// The status of the release. + /// The date of the release. + /// The country the release was issued in. + /// The JSON of the release response. + private static string ReleaseJson(Guid id, string title, Guid releaseGroupId, string releaseGroupTitle, string releaseGroupFirstReleaseDate, string status, string releaseDate, string country) + { + return $$""" + { + "id": "{{id:D}}", + "title": "{{title}}", + "status": "{{status}}", + "date": "{{releaseDate}}", + "country": "{{country}}", + "release-group": { "id": "{{releaseGroupId:D}}", "title": "{{releaseGroupTitle}}", "primary-type": "Album", "first-release-date": "{{releaseGroupFirstReleaseDate}}" } + } + """; + } + + /// + /// Creates an OK response with the provided JSON body. + /// + /// The JSON body of the response. + /// The created response. + private static HttpResponseMessage Json(string json) + { + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzArtistMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzArtistMetadataProviderTests.cs new file mode 100644 index 00000000..514babe0 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzArtistMetadataProviderTests.cs @@ -0,0 +1,308 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.MusicBrainz.Core; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzArtistMetadataProviderTests +{ + private static readonly Guid s_artistId = Guid.Parse("11111111-1111-1111-1111-111111111111"); + + private readonly ArtistMetadataLookupDtoFixture _artistMetadataLookupDtoFixture = new(); + private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new(); + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Arrange + (MusicBrainzArtistMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + string result = sut.Name; + + // Assert + Assert.Equal("MusicBrainz", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Arrange + (MusicBrainzArtistMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + IReadOnlyList result = sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnTrue() + { + // Arrange + (MusicBrainzArtistMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + bool result = sut.RequiresWebAccess; + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task GetSearchResultsAsync_WhenTheNameIsMissing_ShouldReturnAnEmptyCollectionWithoutAnyRequest(string? name) + { + // Arrange + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}")); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", name: name); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + Assert.Equal(0, handler.CallCount); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheSearchReturnsArtists_ShouldMapEveryNamedArtistAndSkipTheUnnamedOnes() + { + // Arrange + const string SEARCH_JSON = """ + { + "count": 3, + "artists": [ + { "id": "11111111-1111-1111-1111-111111111111", "name": "The Artist" }, + { "id": "22222222-2222-2222-2222-222222222222", "name": "Other Artist" }, + { "id": "33333333-3333-3333-3333-333333333333", "name": null } + ] + } + """; + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", name: " The Artist "); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal("The Artist", result[0].Name); + Assert.Equal("Other Artist", result[1].Name); + Assert.Equal(1, handler.CallCount); + // the name is trimmed and the configured search result limit is used + Assert.Contains("limit=10", handler.Requests[0].RequestUri!.Query); + Assert.Contains("query=The%20Artist", handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheSearchResponseIsEmpty_ShouldReturnAnEmptyCollection() + { + // Arrange + const string SEARCH_JSON = """{"count":0,"artists":[]}"""; + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheMusicBrainzIdentifierIsPresent_ShouldLookUpTheArtistByIdentifier() + { + // Arrange + string artistJson = CreateArtistJson("The Artist", "Group", "11111111-1111-1111-1111-111111111111"); + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(artistJson)); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", musicBrainzArtistId: s_artistId); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Artist", result.Name); + Assert.Equal(MusicArtistType.Group, result.Type); + Assert.Equal(s_artistId, result.MusicBrainzArtistId); + Assert.Equal(1, handler.CallCount); + Assert.Contains($"/artist/{s_artistId:D}", handler.Requests[0].RequestUri!.AbsolutePath); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheIdentifierLookupReturnsNothing_ShouldReturnNull() + { + // Arrange + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => new HttpResponseMessage(HttpStatusCode.NotFound)); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", musicBrainzArtistId: s_artistId); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenThereIsNeitherAnIdentifierNorAName_ShouldReturnNullWithoutAnyRequest() + { + // Arrange + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}")); + ArtistMetadataLookupDto lookup = _artistMetadataLookupDtoFixture.Create(path: "path", name: " "); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(0, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheNameSearchReturnsNothing_ShouldReturnNull() + { + // Arrange + const string SEARCH_JSON = """{"count":0,"artists":[]}"""; + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(_artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"), CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheSearchResultHasNoIdentifier_ShouldReturnNull() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"artists":[{"id":null,"name":"The Artist"}]}"""; + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(_artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"), CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheSearchResultIdentifierIsNotAGuid_ShouldMapTheSearchResult() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"artists":[{"id":"not-a-guid","name":"The Artist","type":"Group"}]}"""; + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(_artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Artist", result.Name); + Assert.Equal(MusicArtistType.Group, result.Type); + Assert.Null(result.MusicBrainzArtistId); + // the search is used, and the per identifier lookup must not be requested + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheSearchResultIdentifierIsAGuid_ShouldResolveTheDetailedArtist() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"artists":[{"id":"11111111-1111-1111-1111-111111111111","name":"The Artist"}]}"""; + string detailJson = CreateArtistJson("The Detailed Artist", "Person", "11111111-1111-1111-1111-111111111111"); + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => request.RequestUri!.AbsolutePath.Contains("/artist/") ? Json(detailJson) : Json(SEARCH_JSON)); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(_artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Detailed Artist", result.Name); + Assert.Equal(MusicArtistType.Person, result.Type); + Assert.Equal(2, handler.CallCount); + Assert.Contains("limit=1", handler.Requests[0].RequestUri!.Query); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheDetailedArtistLookupReturnsNothing_ShouldMapTheSearchResult() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"artists":[{"id":"11111111-1111-1111-1111-111111111111","name":"The Artist","type":"Group"}]}"""; + (MusicBrainzArtistMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => request.RequestUri!.AbsolutePath.Contains("/artist/") ? new HttpResponseMessage(HttpStatusCode.NotFound) : Json(SEARCH_JSON)); + + // Act + ArtistMetadataDto? result = await sut.GetMetadataAsync(_artistMetadataLookupDtoFixture.Create(path: "path", name: "The Artist"), CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("The Artist", result.Name); + Assert.Equal(MusicArtistType.Group, result.Type); + Assert.Equal(2, handler.CallCount); + } + + /// + /// Creates a whose requests are answered by the provided stub handler. + /// + /// The factory that produces the response of a request. + /// The created provider and its stub handler. + private (MusicBrainzArtistMetadataProvider Provider, StubHttpMessageHandler Handler) CreateProvider(Func responseFactory) + { + StubHttpMessageHandler handler = new(responseFactory); + MusicBrainzSettingsProvider settingsProvider = new(null, MusicBrainzPlugin.s_pluginId, _musicBrainzSettingsDtoFixture.Create( + baseUrl: "http://localhost/", + searchResultLimit: 10, + releaseLookupLimit: 25, + minimumRequestInterval: TimeSpan.Zero)); + MusicBrainzHttpClient httpClient = new(new HttpClient(handler), settingsProvider, new MusicBrainzRequestThrottle(), new MusicBrainzResponseCache()); + return (new MusicBrainzArtistMetadataProvider(httpClient, settingsProvider), handler); + } + + /// + /// Creates the JSON of an artist response. + /// + /// The name of the artist. + /// The MusicBrainz type of the artist. + /// The MusicBrainz identifier of the artist. + /// The JSON of the artist response. + private static string CreateArtistJson(string name, string type, string id) + { + return $$"""{"id":"{{id}}","name":"{{name}}","type":"{{type}}"}"""; + } + + /// + /// Creates an OK response with the provided JSON body. + /// + /// The JSON body of the response. + /// The created response. + private static HttpResponseMessage Json(string json) + { + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzPluginTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzPluginTests.cs new file mode 100644 index 00000000..df7b9157 --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzPluginTests.cs @@ -0,0 +1,129 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Plugins; +using Lumina.Plugins.Contracts.Common.Models.DTO.Settings; +using Lumina.Plugins.Contracts.Core.Metadata; +using Lumina.Plugins.MusicBrainz.Core; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Microsoft.Extensions.DependencyInjection; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzPluginTests +{ + private readonly MusicBrainzPlugin _sut = new(); + + [Fact] + public void Id_WhenCalled_ShouldReturnStablePluginIdentifier() + { + // Act + Guid result = _sut.Id; + + // Assert + Assert.Equal(MusicBrainzPlugin.s_pluginId, result); + Assert.Equal(new Guid("f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3"), result); + } + + [Fact] + public void Name_WhenCalled_ShouldReturnPluginDisplayName() + { + // Act + string result = _sut.Name; + + // Assert + Assert.Equal("MusicBrainz Metadata", result); + } + + [Fact] + public void Author_WhenCalled_ShouldReturnPluginAuthor() + { + // Act + string result = _sut.Author; + + // Assert + Assert.Equal("Lumina", result); + } + + [Fact] + public void Version_WhenCalled_ShouldReturnPluginVersion() + { + // Act + Version result = _sut.Version; + + // Assert + Assert.Equal(new Version(1, 0, 0), result); + } + + [Fact] + public void Description_WhenCalled_ShouldReturnPluginDescription() + { + // Act + string result = _sut.Description; + + // Assert + Assert.Equal("Retrieves artist, album and track metadata from MusicBrainz.", result); + } + + [Fact] + public void GetSettingsSchema_WhenCalled_ShouldReturnTheSixSettingDescriptors() + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + Assert.Equal(6, result.Count); + Assert.Equal( + [ + MusicBrainzSettingsKeys.BASE_URL, + MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL, + MusicBrainzSettingsKeys.CONTACT_EMAIL, + MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT, + MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT, + MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS + ], + result.Select(descriptor => descriptor.Key)); + } + + [Theory] + [InlineData(MusicBrainzSettingsKeys.BASE_URL, "Base URL", PluginSettingType.Text, "https://musicbrainz.org/ws/2/")] + [InlineData(MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL, "Allow LAN/Private Base URL", PluginSettingType.Boolean, "false")] + [InlineData(MusicBrainzSettingsKeys.CONTACT_EMAIL, "Contact Email", PluginSettingType.Text, null)] + [InlineData(MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT, "Search Result Limit", PluginSettingType.Number, "10")] + [InlineData(MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT, "Release Lookup Limit", PluginSettingType.Number, "25")] + [InlineData(MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, "Minimum Request Interval (seconds)", PluginSettingType.Number, "1.0")] + public void GetSettingsSchema_WhenCalled_ShouldDescribeEachSettingCorrectly(string key, string label, PluginSettingType type, string? defaultValue) + { + // Act + IReadOnlyList result = _sut.GetSettingsSchema(); + + // Assert + PluginSettingDescriptorDto descriptor = Assert.Single(result, candidate => candidate.Key == key); + Assert.Equal(label, descriptor.Label); + Assert.Equal(type, descriptor.Type); + Assert.Equal(defaultValue, descriptor.DefaultValue); + Assert.Null(descriptor.AllowedValues); + } + + [Fact] + public void RegisterServices_WhenCalled_ShouldRegisterTheThreeKeyedMetadataProviders() + { + // Arrange + ServiceCollection services = new(); + + // Act + _sut.RegisterServices(services); + ServiceProvider serviceProvider = services.BuildServiceProvider(); + + // Assert + Assert.Equal(3, serviceProvider.GetKeyedServices(MusicBrainzPlugin.s_pluginId).Count()); + Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid())); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzTrackMetadataProviderTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzTrackMetadataProviderTests.cs new file mode 100644 index 00000000..e3001edc --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/MusicBrainzTrackMetadataProviderTests.cs @@ -0,0 +1,730 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Contracts.DTO.Common; +using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Contracts.Fixtures.Core.DTO.MediaLibrary.AudioLibrary.MusicLibrary; +using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary; +using Lumina.Plugins.MusicBrainz.Core; +using Lumina.Plugins.MusicBrainz.Core.Api; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.UnitTests.Common.TestHelpers; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzTrackMetadataProviderTests +{ + private static readonly Guid s_releaseId = Guid.Parse("11111111-1111-1111-1111-111111111111"); + private static readonly Guid s_recordingId = Guid.Parse("22222222-2222-2222-2222-222222222222"); + private static readonly Guid s_secondRecordingId = Guid.Parse("33333333-3333-3333-3333-333333333333"); + private static readonly Guid s_workId = Guid.Parse("44444444-4444-4444-4444-444444444444"); + + private readonly TrackMetadataLookupDtoFixture _trackMetadataLookupDtoFixture = new(); + private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new(); + + [Fact] + public void Name_WhenCalled_ShouldReturnTheProviderDisplayName() + { + // Arrange + (MusicBrainzTrackMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + string result = sut.Name; + + // Assert + Assert.Equal("MusicBrainz", result); + } + + [Fact] + public void SupportedLibraryTypes_WhenCalled_ShouldReturnMusic() + { + // Arrange + (MusicBrainzTrackMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + IReadOnlyList result = sut.SupportedLibraryTypes; + + // Assert + Assert.Equal([LibraryType.Music], result); + } + + [Fact] + public void RequiresWebAccess_WhenCalled_ShouldReturnTrue() + { + // Arrange + (MusicBrainzTrackMetadataProvider sut, _) = CreateProvider((request, callIndex) => Json("{}")); + + // Act + bool result = sut.RequiresWebAccess; + + // Assert + Assert.True(result); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task GetSearchResultsAsync_WhenTheTitleIsMissing_ShouldReturnAnEmptyCollectionWithoutAnyRequest(string? title) + { + // Arrange + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}")); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", title: title); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Empty(result); + Assert.Equal(0, handler.CallCount); + } + + [Fact] + public async Task GetSearchResultsAsync_WhenTheSearchReturnsRecordings_ShouldMapEveryTitledOneAndSkipTheUntitledOnes() + { + // Arrange + const string SEARCH_JSON = """ + { + "count": 3, + "recordings": [ + { "id": "22222222-2222-2222-2222-222222222222", "title": "The Track" }, + { "id": "33333333-3333-3333-3333-333333333333", "title": "Other Track" }, + { "id": "44444444-4444-4444-4444-444444444444", "title": null } + ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", title: " The \"Track\" ", artistName: "The Artist", releaseName: "The Album"); + + // Act + IReadOnlyList result = await sut.GetSearchResultsAsync(lookup, CancellationToken.None); + + // Assert + Assert.Equal(2, result.Count); + Assert.Equal("The Track", result[0].Title); + Assert.Equal("Other Track", result[1].Title); + Assert.Equal(1, handler.CallCount); + Assert.Contains("limit=10", handler.Requests[0].RequestUri!.Query); + string query = Uri.UnescapeDataString(handler.Requests[0].RequestUri!.Query); + Assert.Contains("recording:\"The Track\"", query); + Assert.Contains("artist:\"The Artist\"", query); + Assert.Contains("release:\"The Album\"", query); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseTracklistMatchesTheRecordingIdentifier_ShouldResolveTheTrackFromTheRelease() + { + // Arrange + string releaseJson = TwoTrackReleaseJson(); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: s_secondRecordingId, trackNumber: 9, discNumber: 1); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_secondRecordingId, result.MusicBrainzRecordingId); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseTracklistDoesNotMatch_ShouldFallBackToTheRecordingIdentifier() + { + // Arrange + Guid fallbackRecordingId = Guid.NewGuid(); + string releaseJson = TwoTrackReleaseJson(); + string recordingJson = RecordingJson(fallbackRecordingId, "Searched Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json( + request.RequestUri!.AbsolutePath.Contains("/release/") ? releaseJson : recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: fallbackRecordingId, trackNumber: 99); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + // The release has no matching track, so it falls through to the recording lookup. + Assert.NotNull(result); + Assert.Equal(fallbackRecordingId, result.MusicBrainzRecordingId); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseIsNotFound_ShouldFallBackToTheRecordingIdentifier() + { + // Arrange + string recordingJson = RecordingJson(s_recordingId, "Searched Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => + request.RequestUri!.AbsolutePath.Contains("/release/") ? new HttpResponseMessage(HttpStatusCode.NotFound) : Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_recordingId, result.MusicBrainzRecordingId); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheMatchedTrackHasNoRecording_ShouldFallThroughToTheSearch() + { + // Arrange + const string RELEASE_JSON = """ + { + "id": "11111111-1111-1111-1111-111111111111", + "title": "The Release", + "media": [ { "position": 1, "track-count": 1, "tracks": [ { "position": 1, "title": "Track Without Recording" } ] } ] + } + """; + const string SEARCH_JSON = """{"count":1,"recordings":[{"id":"22222222-2222-2222-2222-222222222222","title":"Searched Track"}]}"""; + string recordingJson = RecordingJson(s_recordingId, "Searched Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => + request.RequestUri!.Query.Contains("query=") + ? Json(SEARCH_JSON) + : request.RequestUri.AbsolutePath.Contains("/recording/") + ? Json(recordingJson) + : Json(RELEASE_JSON)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, title: "Searched Track", trackNumber: 1, discNumber: 1); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Searched Track", result.Title); + Assert.Equal(s_recordingId, result.MusicBrainzRecordingId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseTrackCarriesAnInlineWork_ShouldUseItWithoutAFurtherLookup() + { + // Arrange + string releaseJson = $$""" + { + "id": "{{s_releaseId:D}}", + "title": "The Release", + "media": [ { "position": 1, "track-count": 1, "tracks": [ { "position": 1, "title": "The Track", "recording": { "id": "{{s_recordingId:D}}", "title": "The Track", "relations": [ { "target-type": "work", "work": { "id": "{{s_workId:D}}", "title": "Inline Work", "type": "Song" } } ] } } ] } ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.NotNull(result.Work); + Assert.Equal(s_workId, result.Work.MusicBrainzWorkId); + Assert.Equal("Inline Work", result.Work.Title); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheInlineWorkRelationHasNoWorkPayload_ShouldFallBackToTheWorkIdentifierOfTheTags() + { + // Arrange + string releaseJson = $$""" + { + "id": "{{s_releaseId:D}}", + "title": "The Release", + "media": [ { "position": 1, "track-count": 1, "tracks": [ { "position": 1, "title": "The Track", "recording": { "id": "{{s_recordingId:D}}", "title": "The Track", "relations": [ { "target-type": "work" } ] } } ] } ] + } + """; + string workJson = $$"""{"id":"{{s_workId:D}}","title":"Tagged Work"}"""; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json( + request.RequestUri!.AbsolutePath.Contains("/release/") ? releaseJson : workJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: s_recordingId, musicBrainzWorkId: s_workId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.NotNull(result.Work); + Assert.Equal(s_workId, result.Work.MusicBrainzWorkId); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseTrackCarriesAWorkWithoutAWorkTitleInTheTags_ShouldNotQueryTheWorkAgain() + { + // Arrange + string releaseJson = $$""" + { + "id": "{{s_releaseId:D}}", + "title": "The Release", + "media": [ { "position": 1, "track-count": 1, "tracks": [ { "position": 1, "title": "The Track", "recording": { "id": "{{s_recordingId:D}}", "title": "The Track", "relations": [ { "target-type": "work", "work": { "id": "{{s_workId:D}}", "title": "Inline Work" } } ] } } ] } ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: s_recordingId, musicBrainzWorkId: Guid.NewGuid()); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Inline Work", result.Work!.Title); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenOnlyTheRecordingIdentifierIsPresent_ShouldResolveTheRecordingItsWorkAndItsRelease() + { + // Arrange + string recordingJson = $$""" + { + "id": "{{s_recordingId:D}}", + "title": "The Track", + "relations": [ { "target-type": "work", "work": { "id": "{{s_workId:D}}", "title": "The Work" } } ], + "releases": [ { "id": "{{s_releaseId:D}}", "title": "The Release", "text-representation": { "language": "eng", "script": "Latn" } } ] + } + """; + string workJson = $$"""{"id":"{{s_workId:D}}","title":"The Work","type":"Song"}"""; + string releaseJson = $$"""{"id":"{{s_releaseId:D}}","title":"The Release","text-representation":{"language":"eng","script":"Latn"} }"""; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => + request.RequestUri!.AbsolutePath.Contains("/work/") ? Json(workJson) + : request.RequestUri.AbsolutePath.Contains("/release/") ? Json(releaseJson) + : Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_recordingId, result.MusicBrainzRecordingId); + Assert.Equal(s_workId, result.Work!.MusicBrainzWorkId); + Assert.Equal("The Work", result.Work.Title); + Assert.NotNull(result.Language); + Assert.Equal("en", result.Language.LanguageCode); + Assert.Equal(3, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheRecordingRelationsCarryAnUnparsableWorkIdentifier_ShouldUseTheEmbeddedWork() + { + // Arrange + string recordingJson = $$""" + { + "id": "{{s_recordingId:D}}", + "title": "The Track", + "relations": [ { "target-type": "work", "work": { "id": "not-a-guid", "title": "Embedded Work" } } ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Embedded Work", result.Work!.Title); + Assert.Null(result.Work.MusicBrainzWorkId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheRecordingHasNoWorkRelation_ShouldReturnATrackWithoutWork() + { + // Arrange + string recordingJson = RecordingJson(s_recordingId, "The Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(result.Work); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheRecordingReferencesAnUnparsableRelease_ShouldReturnATrackWithoutRelease() + { + // Arrange + string recordingJson = $$""" + { + "id": "{{s_recordingId:D}}", + "title": "The Track", + "releases": [ { "id": "not-a-guid", "title": "The Release" } ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(result.Language); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheRecordingHasNoReleases_ShouldReturnATrackWithoutRelease() + { + // Arrange + string recordingJson = RecordingJson(s_recordingId, "The Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(result.Script); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheIsrcMatchesARecordingWithAParsableIdentifier_ShouldResolveItInFull() + { + // Arrange + const string ISRC_JSON = """{"recordings":[{"id":"22222222-2222-2222-2222-222222222222","title":"Isrc Track"}]}"""; + string recordingJson = RecordingJson(s_recordingId, "Resolved Isrc Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => + request.RequestUri!.AbsolutePath.Contains("/isrc/") ? Json(ISRC_JSON) : Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", isrc: "US1A2B3C4D5E"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Resolved Isrc Track", result.Title); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheIsrcMatchesARecordingWithAnUnparsableIdentifier_ShouldReturnItAsIs() + { + // Arrange + const string ISRC_JSON = """{"recordings":[{"id":"not-a-guid","title":"Raw Isrc Track"}]}"""; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(ISRC_JSON)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", isrc: "US1A2B3C4D5E"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Raw Isrc Track", result.Title); + Assert.Null(result.MusicBrainzRecordingId); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheIsrcMatchesNothing_ShouldReturnNullWithoutATitle() + { + // Arrange + const string ISRC_JSON = """{"recordings":[]}"""; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(ISRC_JSON)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", isrc: "US1A2B3C4D5E"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenOnlyTheTitleIsPresent_ShouldSearchAndResolveTheRecordingInFull() + { + // Arrange + const string SEARCH_JSON = """{"count":1,"recordings":[{"id":"22222222-2222-2222-2222-222222222222","title":"Searched Track"}]}"""; + string recordingJson = RecordingJson(s_recordingId, "Resolved Searched Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => + request.RequestUri!.Query.Contains("query=") ? Json(SEARCH_JSON) : Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", title: "Searched Track"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal("Resolved Searched Track", result.Title); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheSearchReturnsNothing_ShouldReturnNull() + { + // Arrange + const string SEARCH_JSON = """{"count":0,"recordings":[]}"""; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(SEARCH_JSON)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", title: "Searched Track"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenNoLookupInformationIsPresent_ShouldReturnNullWithoutAnyRequest() + { + // Arrange + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json("{}")); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Equal(0, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheLocalDiscNumberDoesNotMatchAnyMedium_ShouldReturnNull() + { + // Arrange + string releaseJson = TwoTrackReleaseJson(); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, discNumber: 9); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.Null(result); + } + + [Fact] + public async Task GetMetadataAsync_WhenOnlyTheTrackNumberIsPresent_ShouldSelectTheTrackOnAnyDisc() + { + // Arrange + string releaseJson = TwoTrackReleaseJson(); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, trackNumber: 2); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_secondRecordingId, result.MusicBrainzRecordingId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTitleSinglesOutATrack_ShouldSelectIt() + { + // Arrange + string releaseJson = TwoTrackReleaseJson(); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(releaseJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, title: "Second Track"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_secondRecordingId, result.MusicBrainzRecordingId); + } + + [Fact] + public async Task GetMetadataAsync_WhenSeveralTracksShareTheTitle_ShouldUseTheDurationAsATieBreaker() + { + // Arrange + const string RELEASE_JSON = """ + { + "id": "11111111-1111-1111-1111-111111111111", + "title": "The Release", + "media": [ { "position": 1, "track-count": 2, "tracks": [ + { "position": 1, "title": "Same Title", "length": 100000, "recording": { "id": "22222222-2222-2222-2222-222222222222", "title": "Same Title" } }, + { "position": 2, "title": "Same Title", "length": 200000, "recording": { "id": "33333333-3333-3333-3333-333333333333", "title": "Same Title" } } + ] } ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(RELEASE_JSON)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, title: "Same Title", durationInSeconds: 190); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_secondRecordingId, result.MusicBrainzRecordingId); + } + + [Fact] + public async Task GetMetadataAsync_WhenSeveralTracksShareTheTitleAndNoDurationIsKnown_ShouldSelectTheFirstOne() + { + // Arrange + const string RELEASE_JSON = """ + { + "id": "11111111-1111-1111-1111-111111111111", + "title": "The Release", + "media": [ { "position": 1, "track-count": 2, "tracks": [ + { "position": 1, "title": "Same Title", "length": 100000, "recording": { "id": "22222222-2222-2222-2222-222222222222", "title": "Same Title" } }, + { "position": 2, "title": "Same Title", "length": 200000, "recording": { "id": "33333333-3333-3333-3333-333333333333", "title": "Same Title" } } + ] } ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(RELEASE_JSON)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, title: "Different Title"); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(s_recordingId, result.MusicBrainzRecordingId); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheTagsCarryAWorkIdButMusicBrainzAlreadyLinkedAWork_ShouldResolveTheMusicBrainzWorkInFull() + { + // Arrange + string recordingJson = $$""" + { + "id": "{{s_recordingId:D}}", + "title": "The Track", + "relations": [ { "target-type": "work", "work": { "id": "{{s_workId:D}}", "title": "MusicBrainz Work" } } ] + } + """; + string workJson = $$"""{"id":"{{s_workId:D}}","title":"Tagged Work"}"""; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json( + request.RequestUri!.AbsolutePath.Contains("/work/") ? workJson : recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId, musicBrainzWorkId: Guid.NewGuid()); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + // The work identifier linked by MusicBrainz is resolved in full, taking precedence over the work identifier of the tags. + Assert.Equal(s_workId, result.Work!.MusicBrainzWorkId); + Assert.Equal("Tagged Work", result.Work.Title); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenTheReleaseTracksHaveMissingOrUnparsableRecordingIdentifiers_ShouldFallBackToTheRecordingLookup() + { + // Arrange + Guid fallbackRecordingId = Guid.NewGuid(); + const string RELEASE_JSON = """ + { + "id": "11111111-1111-1111-1111-111111111111", + "title": "The Release", + "media": [ { "position": 1, "track-count": 2, "tracks": [ + { "position": 1, "title": "Track Without Recording" }, + { "position": 2, "title": "Track With Bad Recording", "recording": { "id": "not-a-guid", "title": "Track With Bad Recording" } } + ] } ] + } + """; + string recordingJson = RecordingJson(fallbackRecordingId, "Fallback Track"); + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json( + request.RequestUri!.AbsolutePath.Contains("/release/") ? RELEASE_JSON : recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzReleaseId: s_releaseId, musicBrainzRecordingId: fallbackRecordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Equal(fallbackRecordingId, result.MusicBrainzRecordingId); + Assert.Equal(2, handler.CallCount); + } + + [Fact] + public async Task GetMetadataAsync_WhenAWorkRelationHasNoWork_ShouldReturnATrackWithoutWork() + { + // Arrange + string recordingJson = $$""" + { + "id": "{{s_recordingId:D}}", + "title": "The Track", + "relations": [ { "target-type": "work" } ] + } + """; + (MusicBrainzTrackMetadataProvider sut, StubHttpMessageHandler handler) = CreateProvider((request, callIndex) => Json(recordingJson)); + TrackMetadataLookupDto lookup = _trackMetadataLookupDtoFixture.Create(path: "path", musicBrainzRecordingId: s_recordingId); + + // Act + AudioMetadataDto? result = await sut.GetMetadataAsync(lookup, CancellationToken.None); + + // Assert + Assert.NotNull(result); + Assert.Null(result.Work); + } + + /// + /// Creates a whose requests are answered by the provided stub handler. + /// + /// The factory that produces the response of a request. + /// The created provider and its stub handler. + private (MusicBrainzTrackMetadataProvider Provider, StubHttpMessageHandler Handler) CreateProvider(Func responseFactory) + { + StubHttpMessageHandler handler = new(responseFactory); + MusicBrainzSettingsProvider settingsProvider = new(null, MusicBrainzPlugin.s_pluginId, _musicBrainzSettingsDtoFixture.Create( + baseUrl: "http://localhost/", + searchResultLimit: 10, + releaseLookupLimit: 25, + minimumRequestInterval: TimeSpan.Zero)); + MusicBrainzHttpClient httpClient = new(new HttpClient(handler), settingsProvider, new MusicBrainzRequestThrottle(), new MusicBrainzResponseCache()); + return (new MusicBrainzTrackMetadataProvider(httpClient, settingsProvider), handler); + } + + /// + /// Creates the JSON of a release with two tracks, each with its own recording. + /// + /// The JSON of the release. + private static string TwoTrackReleaseJson() + { + return $$""" + { + "id": "{{s_releaseId:D}}", + "title": "The Release", + "media": [ { "position": 1, "track-count": 2, "tracks": [ + { "position": 1, "title": "First Track", "recording": { "id": "{{s_recordingId:D}}", "title": "First Track" } }, + { "position": 2, "title": "Second Track", "recording": { "id": "{{s_secondRecordingId:D}}", "title": "Second Track" } } + ] } ] + } + """; + } + + /// + /// Creates the JSON of a recording response. + /// + /// The MusicBrainz identifier of the recording. + /// The title of the recording. + /// The JSON of the recording response. + private static string RecordingJson(Guid id, string title) + { + return $$"""{"id":"{{id:D}}","title":"{{title}}"}"""; + } + + /// + /// Creates an OK response with the provided JSON body. + /// + /// The JSON body of the response. + /// The created response. + private static HttpResponseMessage Json(string json) + { + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; + } +} \ No newline at end of file diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Settings/MusicBrainzSettingsProviderTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Settings/MusicBrainzSettingsProviderTests.cs new file mode 100644 index 00000000..00c0643e --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Settings/MusicBrainzSettingsProviderTests.cs @@ -0,0 +1,359 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Core.Plugins; +using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; +using Lumina.Plugins.MusicBrainz.Core.Settings; +using Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings; +using NSubstitute; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Plugins.MusicBrainz.UnitTests.Core.Settings; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class MusicBrainzSettingsProviderTests +{ + private readonly MusicBrainzSettingsDtoFixture _musicBrainzSettingsDtoFixture = new(); + + [Fact] + public async Task GetAsync_WhenNoStoreIsAvailable_ShouldReturnTheDefaults() + { + // Arrange + MusicBrainzSettingsDto defaults = CreateDefaults(); + MusicBrainzSettingsProvider sut = new(null, Guid.NewGuid(), defaults); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.NotSame(defaults, result); + Assert.Equal("https://musicbrainz.org/ws/2/", result.BaseUrl); + Assert.False(result.DoesAllowPrivateBaseUrl); + Assert.Equal("Lumina-MusicBrainz/1.0", result.UserAgent); + Assert.Equal("default@example.com", result.ContactEmail); + Assert.Equal(10, result.SearchResultLimit); + Assert.Equal(25, result.ReleaseLookupLimit); + Assert.Equal(TimeSpan.FromSeconds(1), result.MinimumRequestInterval); + } + + [Fact] + public async Task GetAsync_WhenTheStoreReturnsNoSettings_ShouldReturnTheDefaults() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns((IReadOnlyDictionary?)null); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("https://musicbrainz.org/ws/2/", result.BaseUrl); + Assert.Equal(10, result.SearchResultLimit); + } + + [Fact] + public async Task GetAsync_WhenEverySettingIsPersisted_ShouldOverlayThemOverTheDefaults() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary + { + [MusicBrainzSettingsKeys.BASE_URL] = "https://mirror.example/ws/2/", + [MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL] = "true", + [MusicBrainzSettingsKeys.CONTACT_EMAIL] = " contact@example.com ", + [MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT] = "42", + [MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT] = "30", + [MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = "2.5" + }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("https://mirror.example/ws/2/", result.BaseUrl); + Assert.True(result.DoesAllowPrivateBaseUrl); + Assert.Equal("contact@example.com", result.ContactEmail); + Assert.Equal(42, result.SearchResultLimit); + Assert.Equal(30, result.ReleaseLookupLimit); + Assert.Equal(TimeSpan.FromSeconds(2.5), result.MinimumRequestInterval); + } + + [Theory] + [InlineData("not-a-url")] // a value that is not an URI at all + [InlineData("ftp://mirror.example/")] // an absolute URI with an unsupported scheme + [InlineData("relative/path")] // a relative URI + [InlineData(" ")] // only white space + public async Task GetAsync_WhenThePersistedBaseUrlIsInvalid_ShouldKeepTheDefaultBaseUrl(string baseUrl) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.BASE_URL] = baseUrl }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("https://musicbrainz.org/ws/2/", result.BaseUrl); + } + + [Theory] + [InlineData("http://127.0.0.1/ws/2/")] // IPv4 loopback + [InlineData("http://localhost/ws/2/")] // loopback host name + [InlineData("http://[::1]/ws/2/")] // IPv6 loopback + [InlineData("http://169.254.169.254/latest/meta-data/")] // link local cloud metadata endpoint + [InlineData("http://10.0.0.5/ws/2/")] // private class A range + [InlineData("http://172.16.0.1/ws/2/")] // private class B range + [InlineData("http://192.168.1.10/ws/2/")] // private class C range + [InlineData("http://0.0.0.0/ws/2/")] // unspecified address + [InlineData("http://[fc00::1]/ws/2/")] // IPv6 unique local range + public async Task GetAsync_WhenThePersistedBaseUrlPointsAtALocalOrPrivateHost_ShouldKeepTheDefaultBaseUrl(string baseUrl) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.BASE_URL] = baseUrl }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("https://musicbrainz.org/ws/2/", result.BaseUrl); + } + + [Theory] + [InlineData("http://192.168.1.10/ws/2/")] // private class C range, a typical self hosted mirror + [InlineData("http://localhost/ws/2/")] // loopback host name + [InlineData("http://[fc00::1]/ws/2/")] // IPv6 unique local range + public async Task GetAsync_WhenPrivateBaseUrlsAreExplicitlyAllowed_ShouldApplyThem(string baseUrl) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary + { + [MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL] = "true", + [MusicBrainzSettingsKeys.BASE_URL] = baseUrl + }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal(baseUrl, result.BaseUrl); + } + + [Theory] + [InlineData("user\r\n@example.com")] // carriage return and line feed injection + [InlineData("user@example.com\r\nX-Injected: value")] // header injection attempt + [InlineData("user(comment)@example.com")] // parentheses break the user agent comment + [InlineData("user\"quoted\"@example.com")] // quotes break the header value + [InlineData("user example@example.com")] // an inner space is not a valid token character + public async Task GetAsync_WhenThePersistedContactEmailContainsUnsafeCharacters_ShouldDropIt(string storedEmail) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.CONTACT_EMAIL] = storedEmail }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Null(result.ContactEmail); + } + + [Fact] + public async Task GetAsync_WhenThePersistedBaseUrlIsAnAbsoluteHttpUrl_ShouldApplyIt() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.BASE_URL] = "http://mirror.example/ws/2/" }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("http://mirror.example/ws/2/", result.BaseUrl); + } + + [Fact] + public async Task GetAsync_WhenThePersistedBaseUrlIsNull_ShouldKeepTheDefaultBaseUrl() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.BASE_URL] = null! }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal("https://musicbrainz.org/ws/2/", result.BaseUrl); + } + + [Theory] + [InlineData("", null)] // an empty value clears the email + [InlineData(" ", null)] // a white space value clears the email + [InlineData(" user@example.com ", "user@example.com")] // a value with surrounding white space is trimmed + public async Task GetAsync_WhenThePersistedContactEmailIsPresent_ShouldSetOrClearIt(string storedEmail, string? expectedEmail) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.CONTACT_EMAIL] = storedEmail }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal(expectedEmail, result.ContactEmail); + } + + [Theory] + [InlineData("42", 42)] + [InlineData("0", 1)] // a limit of zero is clamped to one + [InlineData("-5", 1)] // a negative limit is clamped to one + [InlineData("not-a-number", 10)] // an unparsable value keeps the default + public async Task GetAsync_WhenThePersistedSearchResultLimitIsPresent_ShouldParseAndClampIt(string storedLimit, int expectedLimit) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT] = storedLimit }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal(expectedLimit, result.SearchResultLimit); + } + + [Theory] + [InlineData("30", 30)] + [InlineData("0", 1)] // a limit of zero is clamped to one + [InlineData("-5", 1)] // a negative limit is clamped to one + [InlineData("not-a-number", 25)] // an unparsable value keeps the default + public async Task GetAsync_WhenThePersistedReleaseLookupLimitIsPresent_ShouldParseAndClampIt(string storedLimit, int expectedLimit) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT] = storedLimit }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal(expectedLimit, result.ReleaseLookupLimit); + } + + [Theory] + [InlineData("2.5", 2.5)] + [InlineData("0", 0)] // an interval of zero is allowed + [InlineData("-3", 0)] // a negative interval is clamped to zero + [InlineData("not-a-number", 1)] // an unparsable value keeps the default + public async Task GetAsync_WhenThePersistedMinimumRequestIntervalIsPresent_ShouldParseAndClampIt(string storedInterval, double expectedSeconds) + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS] = storedInterval }); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Equal(TimeSpan.FromSeconds(expectedSeconds), result.MinimumRequestInterval); + } + + [Fact] + public async Task GetAsync_WhenCalledTwice_ShouldReadTheStoreOnlyOnce() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(new Dictionary()); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto first = await sut.GetAsync(CancellationToken.None); + MusicBrainzSettingsDto second = await sut.GetAsync(CancellationToken.None); + + // Assert + Assert.Same(first, second); + await mockStore.Received(1).GetSettingsAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetAsync_WhenCalledConcurrently_ShouldReadTheStoreOnlyOnce() + { + // Arrange + IPluginSettingsStore mockStore = Substitute.For(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns(new Dictionary()); + MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults()); + + // Act + MusicBrainzSettingsDto[] results = await Task.WhenAll(Enumerable.Range(0, 10).Select(_ => sut.GetAsync(CancellationToken.None))); + + // Assert + Assert.All(results, result => Assert.Same(results[0], result)); + await mockStore.Received(1).GetSettingsAsync(Arg.Any(), Arg.Any()); + } + + [Fact] + public async Task GetAsync_WhenTheCancellationTokenIsAlreadyCancelled_ShouldThrowOperationCanceledException() + { + // Arrange + using (CancellationTokenSource cancellationTokenSource = new()) + { + cancellationTokenSource.Cancel(); + MusicBrainzSettingsProvider sut = new(null, Guid.NewGuid(), CreateDefaults()); + + // Act + Task Act() + { + return sut.GetAsync(cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + } + + /// + /// Creates the default settings used by the tests of the provider. + /// + /// The default settings. + private MusicBrainzSettingsDto CreateDefaults() + { + return _musicBrainzSettingsDtoFixture.Create( + baseUrl: "https://musicbrainz.org/ws/2/", + doesAllowPrivateBaseUrl: false, + userAgent: "Lumina-MusicBrainz/1.0", + contactEmail: "default@example.com", + searchResultLimit: 10, + releaseLookupLimit: 25, + minimumRequestInterval: TimeSpan.FromSeconds(1)); + } +} diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Lumina.Plugins.MusicBrainz.UnitTests.csproj b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Lumina.Plugins.MusicBrainz.UnitTests.csproj new file mode 100644 index 00000000..ff528e9a --- /dev/null +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Lumina.Plugins.MusicBrainz.UnitTests.csproj @@ -0,0 +1,48 @@ + + + + net10.0 + disable + enable + + false + true + + + + + <_Parameter1>DisableTestParallelization = true + <_Parameter1_IsLiteral>true + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + +