Adds the MusicBrainz music metadata plugin, its fixtures, and its unit test suite

This commit is contained in:
BinaryAlley committed 2026-10-01 12:00:00 +03:00
1 parent 1ffa14cec4
commit 0abda472c6
101 files changed
+11461

No files matched your search

@@ -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;
/// <summary>
/// Utility class for registering the services of the MusicBrainz metadata provider into the Dependency Injection container.
/// </summary>
internal static class MusicBrainzServices
{
/// <summary>
/// Registers the services of the MusicBrainz metadata providers into the Dependency Injection container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <param name="pluginId">The unique identifier of the plugin that provides the metadata.</param>
/// <param name="settingsCallback">Action used to configure the <see cref="MusicBrainzSettingsDto"/>.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
internal static IServiceCollection AddMusicBrainzMetadataProviders(this IServiceCollection services, Guid pluginId, Action<MusicBrainzSettingsDto>? 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<IPluginSettingsStore>();
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<MusicBrainzRequestThrottle>();
// 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<MusicBrainzResponseCache>();
// 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<MusicBrainzHttpClient>()
.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<IMetadataProvider, MusicBrainzArtistMetadataProvider>(pluginId);
services.AddKeyedTransient<IMetadataProvider, MusicBrainzAlbumMetadataProvider>(pluginId);
services.AddKeyedTransient<IMetadataProvider, MusicBrainzTrackMetadataProvider>(pluginId);
return services;
}
}
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for an alias of a MusicBrainz entity.
/// </summary>
internal sealed record MusicBrainzAliasResponse
{
/// <summary>
/// Gets the name of the alias.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the sort name of the alias.
/// </summary>
[JsonPropertyName("sort-name")]
public string? SortName { get; init; }
/// <summary>
/// Gets the type of the alias.
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; init; }
/// <summary>
/// Gets the locale the alias is used in.
/// </summary>
[JsonPropertyName("locale")]
public string? Locale { get; init; }
/// <summary>
/// Gets a value indicating whether this is the primary alias.
/// </summary>
[JsonPropertyName("primary")]
public bool? IsPrimary { get; init; }
/// <summary>
/// Gets the begin date of the alias.
/// </summary>
[JsonPropertyName("begin")]
public string? Begin { get; init; }
/// <summary>
/// Gets the end date of the alias.
/// </summary>
[JsonPropertyName("end")]
public string? End { get; init; }
/// <summary>
/// Gets a value indicating whether the alias has ended.
/// </summary>
[JsonPropertyName("ended")]
public bool? IsEnded { get; init; }
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for an area from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzAreaResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the area.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the name of the area.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the sort name of the area.
/// </summary>
[JsonPropertyName("sort-name")]
public string? SortName { get; init; }
/// <summary>
/// Gets the disambiguation comment of the area.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the MusicBrainz type of the area.
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; init; }
/// <summary>
/// Gets the ISO 3166-1 codes of the area.
/// </summary>
[JsonPropertyName("iso-3166-1-codes")]
public List<string> Iso3166Part1Codes { get; init; } = [];
/// <summary>
/// Gets the ISO 3166-2 codes of the area.
/// </summary>
[JsonPropertyName("iso-3166-2-codes")]
public List<string> Iso3166Part2Codes { get; init; } = [];
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a single credit in the artist credit of a MusicBrainz entity.
/// </summary>
internal sealed record MusicBrainzArtistCreditResponse
{
/// <summary>
/// Gets the credited name of the artist.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the join phrase that follows the credit.
/// </summary>
[JsonPropertyName("joinphrase")]
public string? JoinPhrase { get; init; }
/// <summary>
/// Gets the artist the credit refers to.
/// </summary>
[JsonPropertyName("artist")]
public MusicBrainzArtistResponse? Artist { get; init; }
}
@@ -0,0 +1,120 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for an artist from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzArtistResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the artist.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the name of the artist.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the sort name of the artist.
/// </summary>
[JsonPropertyName("sort-name")]
public string? SortName { get; init; }
/// <summary>
/// Gets the disambiguation comment of the artist.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the MusicBrainz type of the artist.
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; init; }
/// <summary>
/// Gets the gender of the artist.
/// </summary>
[JsonPropertyName("gender")]
public string? Gender { get; init; }
/// <summary>
/// Gets the ISO 3166-1 alpha-2 code of the country of the artist.
/// </summary>
[JsonPropertyName("country")]
public string? Country { get; init; }
/// <summary>
/// Gets the area the artist is primarily identified with.
/// </summary>
[JsonPropertyName("area")]
public MusicBrainzAreaResponse? Area { get; init; }
/// <summary>
/// Gets the area the artist began in.
/// </summary>
[JsonPropertyName("begin-area")]
public MusicBrainzAreaResponse? BeginArea { get; init; }
/// <summary>
/// Gets the area the artist ended in.
/// </summary>
[JsonPropertyName("end-area")]
public MusicBrainzAreaResponse? EndArea { get; init; }
/// <summary>
/// Gets the life span of the artist.
/// </summary>
[JsonPropertyName("life-span")]
public MusicBrainzLifeSpanResponse? LifeSpan { get; init; }
/// <summary>
/// Gets the ISNI codes of the artist.
/// </summary>
[JsonPropertyName("isnis")]
public List<string> Isnis { get; init; } = [];
/// <summary>
/// Gets the IPI codes of the artist.
/// </summary>
[JsonPropertyName("ipis")]
public List<string> Ipis { get; init; } = [];
/// <summary>
/// Gets the alternative names of the artist.
/// </summary>
[JsonPropertyName("aliases")]
public List<MusicBrainzAliasResponse> Aliases { get; init; } = [];
/// <summary>
/// Gets the tags of the artist.
/// </summary>
[JsonPropertyName("tags")]
public List<MusicBrainzTagResponse> Tags { get; init; } = [];
/// <summary>
/// Gets the genres of the artist.
/// </summary>
[JsonPropertyName("genres")]
public List<MusicBrainzTagResponse> Genres { get; init; } = [];
/// <summary>
/// Gets the relationships of the artist to other entities.
/// </summary>
[JsonPropertyName("relations")]
public List<MusicBrainzRelationResponse> Relations { get; init; } = [];
/// <summary>
/// Gets the aggregated rating of the artist.
/// </summary>
[JsonPropertyName("rating")]
public MusicBrainzRatingResponse? Rating { get; init; }
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for an artist search from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzArtistSearchResponse
{
/// <summary>
/// Gets the total number of matching artists.
/// </summary>
[JsonPropertyName("count")]
public int Count { get; init; }
/// <summary>
/// Gets the offset of the returned artists.
/// </summary>
[JsonPropertyName("offset")]
public int Offset { get; init; }
/// <summary>
/// Gets the matching artists.
/// </summary>
[JsonPropertyName("artists")]
public List<MusicBrainzArtistResponse> Artists { get; init; } = [];
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the label information of a MusicBrainz release.
/// </summary>
internal sealed record MusicBrainzLabelInfoResponse
{
/// <summary>
/// Gets the catalog number assigned by the label.
/// </summary>
[JsonPropertyName("catalog-number")]
public string? CatalogNumber { get; init; }
/// <summary>
/// Gets the label that issued the release.
/// </summary>
[JsonPropertyName("label")]
public MusicBrainzLabelResponse? Label { get; init; }
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a label from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzLabelResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the label.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the name of the label.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the disambiguation comment of the label.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the label code of the label.
/// </summary>
[JsonPropertyName("label-code")]
public int? LabelCode { get; init; }
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the life span of a MusicBrainz artist, label, or area.
/// </summary>
internal sealed record MusicBrainzLifeSpanResponse
{
/// <summary>
/// Gets the begin date of the life span.
/// </summary>
[JsonPropertyName("begin")]
public string? Begin { get; init; }
/// <summary>
/// Gets the end date of the life span.
/// </summary>
[JsonPropertyName("end")]
public string? End { get; init; }
/// <summary>
/// Gets a value indicating whether the life span has ended.
/// </summary>
[JsonPropertyName("ended")]
public bool? IsEnded { get; init; }
}
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a medium of a MusicBrainz release.
/// </summary>
internal sealed record MusicBrainzMediumResponse
{
/// <summary>
/// Gets the position of the medium within its release.
/// </summary>
[JsonPropertyName("position")]
public int Position { get; init; }
/// <summary>
/// Gets the title of the medium.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the format of the medium (e.g., CD, Vinyl, Digital Media).
/// </summary>
[JsonPropertyName("format")]
public string? Format { get; init; }
/// <summary>
/// Gets the number of tracks of the medium.
/// </summary>
[JsonPropertyName("track-count")]
public int TrackCount { get; init; }
/// <summary>
/// Gets the tracks of the medium. The tracks are only returned when the recordings are included in the request.
/// </summary>
[JsonPropertyName("tracks")]
public List<MusicBrainzTrackResponse> Tracks { get; init; } = [];
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the aggregated rating of a MusicBrainz entity.
/// </summary>
internal sealed record MusicBrainzRatingResponse
{
/// <summary>
/// Gets the average rating value.
/// </summary>
[JsonPropertyName("value")]
public decimal? Value { get; init; }
/// <summary>
/// Gets the number of votes that contributed to the rating.
/// </summary>
[JsonPropertyName("votes-count")]
public int? VotesCount { get; init; }
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the recordings returned by an ISRC lookup from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzRecordingListResponse
{
/// <summary>
/// Gets the recordings that carry the looked up ISRC.
/// </summary>
[JsonPropertyName("recordings")]
public List<MusicBrainzRecordingResponse> Recordings { get; init; } = [];
}
@@ -0,0 +1,90 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a recording from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzRecordingResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the recording.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the title of the recording.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the disambiguation comment of the recording.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the length of the recording in milliseconds.
/// </summary>
[JsonPropertyName("length")]
public long? Length { get; init; }
/// <summary>
/// Gets a value indicating whether the recording is a video recording.
/// </summary>
[JsonPropertyName("video")]
public bool? IsVideo { get; init; }
/// <summary>
/// Gets the date the recording was first released.
/// </summary>
[JsonPropertyName("first-release-date")]
public string? FirstReleaseDate { get; init; }
/// <summary>
/// Gets the artist credit of the recording.
/// </summary>
[JsonPropertyName("artist-credit")]
public List<MusicBrainzArtistCreditResponse> ArtistCredit { get; init; } = [];
/// <summary>
/// Gets the ISRC (International Standard Recording Code) of the recording.
/// </summary>
[JsonPropertyName("isrcs")]
public List<string> Isrcs { get; init; } = [];
/// <summary>
/// Gets the releases the recording appears on.
/// </summary>
[JsonPropertyName("releases")]
public List<MusicBrainzReleaseResponse> Releases { get; init; } = [];
/// <summary>
/// Gets the tags of the recording.
/// </summary>
[JsonPropertyName("tags")]
public List<MusicBrainzTagResponse> Tags { get; init; } = [];
/// <summary>
/// Gets the genres of the recording.
/// </summary>
[JsonPropertyName("genres")]
public List<MusicBrainzTagResponse> Genres { get; init; } = [];
/// <summary>
/// Gets the relationships of the recording to other entities (e.g., its work, and its performers).
/// </summary>
[JsonPropertyName("relations")]
public List<MusicBrainzRelationResponse> Relations { get; init; } = [];
/// <summary>
/// Gets the aggregated rating of the recording.
/// </summary>
[JsonPropertyName("rating")]
public MusicBrainzRatingResponse? Rating { get; init; }
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a recording search from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzRecordingSearchResponse
{
/// <summary>
/// Gets the total number of matching recordings.
/// </summary>
[JsonPropertyName("count")]
public int Count { get; init; }
/// <summary>
/// Gets the offset of the returned recordings.
/// </summary>
[JsonPropertyName("offset")]
public int Offset { get; init; }
/// <summary>
/// Gets the matching recordings.
/// </summary>
[JsonPropertyName("recordings")]
public List<MusicBrainzRecordingResponse> Recordings { get; init; } = [];
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a relationship between a MusicBrainz entity and another entity.
/// </summary>
internal sealed record MusicBrainzRelationResponse
{
/// <summary>
/// Gets the type of the relationship (e.g., producer, composer, member of band).
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; init; }
/// <summary>
/// Gets the MusicBrainz identifier of the type of the relationship.
/// </summary>
[JsonPropertyName("type-id")]
public string? TypeId { get; init; }
/// <summary>
/// Gets the direction of the relationship.
/// </summary>
[JsonPropertyName("direction")]
public string? Direction { get; init; }
/// <summary>
/// Gets the type of the entity the relationship targets.
/// </summary>
[JsonPropertyName("target-type")]
public string? TargetType { get; init; }
/// <summary>
/// Gets the artist the relationship targets, when the target is an artist.
/// </summary>
[JsonPropertyName("artist")]
public MusicBrainzArtistResponse? Artist { get; init; }
/// <summary>
/// Gets the work the relationship targets, when the target is a work.
/// </summary>
[JsonPropertyName("work")]
public MusicBrainzWorkResponse? Work { get; init; }
/// <summary>
/// Gets the URL the relationship targets, when the target is a URL.
/// </summary>
[JsonPropertyName("url")]
public MusicBrainzUrlResponse? Url { get; init; }
/// <summary>
/// Gets the attributes of the relationship (e.g., the instrument that was performed).
/// </summary>
[JsonPropertyName("attributes")]
public List<string> Attributes { get; init; } = [];
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the result of browsing the releases linked to another MusicBrainz entity.
/// </summary>
internal sealed record MusicBrainzReleaseBrowseResponse
{
/// <summary>
/// Gets the releases returned by the browse request.
/// </summary>
[JsonPropertyName("releases")]
public List<MusicBrainzReleaseResponse> Releases { get; init; } = [];
/// <summary>
/// Gets the total number of releases linked to the browsed entity.
/// </summary>
[JsonPropertyName("release-count")]
public int ReleaseCount { get; init; }
/// <summary>
/// Gets the offset of the returned releases.
/// </summary>
[JsonPropertyName("release-offset")]
public int ReleaseOffset { get; init; }
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a release event of a MusicBrainz release.
/// </summary>
internal sealed record MusicBrainzReleaseEventResponse
{
/// <summary>
/// Gets the date of the release event.
/// </summary>
[JsonPropertyName("date")]
public string? Date { get; init; }
/// <summary>
/// Gets the area of the release event.
/// </summary>
[JsonPropertyName("area")]
public MusicBrainzAreaResponse? Area { get; init; }
}
@@ -0,0 +1,78 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a release group from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzReleaseGroupResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the release group.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the title of the release group.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the disambiguation comment of the release group.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the primary type of the release group.
/// </summary>
[JsonPropertyName("primary-type")]
public string? PrimaryType { get; init; }
/// <summary>
/// Gets the secondary types of the release group.
/// </summary>
[JsonPropertyName("secondary-types")]
public List<string> SecondaryTypes { get; init; } = [];
/// <summary>
/// Gets the date the release group was first released.
/// </summary>
[JsonPropertyName("first-release-date")]
public string? FirstReleaseDate { get; init; }
/// <summary>
/// Gets the artist credit of the release group.
/// </summary>
[JsonPropertyName("artist-credit")]
public List<MusicBrainzArtistCreditResponse> ArtistCredit { get; init; } = [];
/// <summary>
/// Gets the releases of the release group.
/// </summary>
[JsonPropertyName("releases")]
public List<MusicBrainzReleaseResponse> Releases { get; init; } = [];
/// <summary>
/// Gets the tags of the release group.
/// </summary>
[JsonPropertyName("tags")]
public List<MusicBrainzTagResponse> Tags { get; init; } = [];
/// <summary>
/// Gets the genres of the release group.
/// </summary>
[JsonPropertyName("genres")]
public List<MusicBrainzTagResponse> Genres { get; init; } = [];
/// <summary>
/// Gets the aggregated rating of the release group.
/// </summary>
[JsonPropertyName("rating")]
public MusicBrainzRatingResponse? Rating { get; init; }
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a release group search from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzReleaseGroupSearchResponse
{
/// <summary>
/// Gets the total number of matching release groups.
/// </summary>
[JsonPropertyName("count")]
public int Count { get; init; }
/// <summary>
/// Gets the offset of the returned release groups.
/// </summary>
[JsonPropertyName("offset")]
public int Offset { get; init; }
/// <summary>
/// Gets the matching release groups.
/// </summary>
[JsonPropertyName("release-groups")]
public List<MusicBrainzReleaseGroupResponse> ReleaseGroups { get; init; } = [];
}
@@ -0,0 +1,120 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a release from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzReleaseResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the release.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the title of the release.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the disambiguation comment of the release.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the status of the release (e.g., Official, Bootleg).
/// </summary>
[JsonPropertyName("status")]
public string? Status { get; init; }
/// <summary>
/// Gets the date the release was issued.
/// </summary>
[JsonPropertyName("date")]
public string? Date { get; init; }
/// <summary>
/// Gets the ISO 3166-1 alpha-2 code of the country the release was issued in.
/// </summary>
[JsonPropertyName("country")]
public string? Country { get; init; }
/// <summary>
/// Gets the release events of the release.
/// </summary>
[JsonPropertyName("release-events")]
public List<MusicBrainzReleaseEventResponse> ReleaseEvents { get; init; } = [];
/// <summary>
/// Gets the barcode of the release.
/// </summary>
[JsonPropertyName("barcode")]
public string? Barcode { get; init; }
/// <summary>
/// Gets the outermost packaging of the release.
/// </summary>
[JsonPropertyName("packaging")]
public string? Packaging { get; init; }
/// <summary>
/// Gets the language and script of the titles of the release.
/// </summary>
[JsonPropertyName("text-representation")]
public MusicBrainzTextRepresentationResponse? TextRepresentation { get; init; }
/// <summary>
/// Gets the artist credit of the release.
/// </summary>
[JsonPropertyName("artist-credit")]
public List<MusicBrainzArtistCreditResponse> ArtistCredit { get; init; } = [];
/// <summary>
/// Gets the release group the release belongs to.
/// </summary>
[JsonPropertyName("release-group")]
public MusicBrainzReleaseGroupResponse? ReleaseGroup { get; init; }
/// <summary>
/// Gets the label information of the release.
/// </summary>
[JsonPropertyName("label-info")]
public List<MusicBrainzLabelInfoResponse> LabelInfo { get; init; } = [];
/// <summary>
/// Gets the media of the release.
/// </summary>
[JsonPropertyName("media")]
public List<MusicBrainzMediumResponse> Media { get; init; } = [];
/// <summary>
/// Gets the ASIN (Amazon Standard Identification Number) of the release.
/// </summary>
[JsonPropertyName("asin")]
public string? Asin { get; init; }
/// <summary>
/// Gets the tags of the release.
/// </summary>
[JsonPropertyName("tags")]
public List<MusicBrainzTagResponse> Tags { get; init; } = [];
/// <summary>
/// Gets the genres of the release.
/// </summary>
[JsonPropertyName("genres")]
public List<MusicBrainzTagResponse> Genres { get; init; } = [];
/// <summary>
/// Gets the relationships of the release to other entities (e.g., its producers and engineers).
/// </summary>
[JsonPropertyName("relations")]
public List<MusicBrainzRelationResponse> Relations { get; init; } = [];
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a tag or a genre of a MusicBrainz entity.
/// </summary>
internal sealed record MusicBrainzTagResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the genre, when the tag is a genre.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the name of the tag.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the disambiguation comment of the genre, when the tag is a genre.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the number of votes the tag received.
/// </summary>
[JsonPropertyName("count")]
public int Count { get; init; }
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the language and script of the titles of a MusicBrainz release.
/// </summary>
internal sealed record MusicBrainzTextRepresentationResponse
{
/// <summary>
/// Gets the ISO 639-3 language code of the release.
/// </summary>
[JsonPropertyName("language")]
public string? Language { get; init; }
/// <summary>
/// Gets the ISO 15924 script code of the release.
/// </summary>
[JsonPropertyName("script")]
public string? Script { get; init; }
}
@@ -0,0 +1,47 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a track of a medium of a MusicBrainz release, including the recording it is a performance of.
/// </summary>
internal sealed record MusicBrainzTrackResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the track.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the track number, as displayed on the medium (for example, "1" or "A1").
/// </summary>
[JsonPropertyName("number")]
public string? Number { get; init; }
/// <summary>
/// Gets the position of the track within its medium.
/// </summary>
[JsonPropertyName("position")]
public int Position { get; init; }
/// <summary>
/// Gets the title of the track.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the length of the track in milliseconds.
/// </summary>
[JsonPropertyName("length")]
public long? Length { get; init; }
/// <summary>
/// Gets the recording the track is a performance of.
/// </summary>
[JsonPropertyName("recording")]
public MusicBrainzRecordingResponse? Recording { get; init; }
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a URL from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzUrlResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the URL.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the resource the URL points to.
/// </summary>
[JsonPropertyName("resource")]
public string? Resource { get; init; }
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a work from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzWorkResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the work.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the title of the work.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the MusicBrainz type of the work.
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; init; }
/// <summary>
/// Gets the disambiguation comment of the work.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the languages of the work.
/// </summary>
[JsonPropertyName("languages")]
public List<string> Languages { get; init; } = [];
/// <summary>
/// Gets the ISWC (International Standard Musical Work Code) of the work.
/// </summary>
[JsonPropertyName("iswcs")]
public List<string> Iswcs { get; init; } = [];
/// <summary>
/// Gets the relationships of the work to other entities (e.g., its composers and lyricists).
/// </summary>
[JsonPropertyName("relations")]
public List<MusicBrainzRelationResponse> Relations { get; init; } = [];
/// <summary>
/// Gets the tags of the work.
/// </summary>
[JsonPropertyName("tags")]
public List<MusicBrainzTagResponse> Tags { get; init; } = [];
/// <summary>
/// Gets the genres of the work.
/// </summary>
[JsonPropertyName("genres")]
public List<MusicBrainzTagResponse> Genres { get; init; } = [];
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
/// <summary>
/// Data transfer object for the settings that configure the MusicBrainz metadata plugin.
/// </summary>
internal sealed class MusicBrainzSettingsDto
{
/// <summary>
/// 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.
/// </summary>
public string BaseUrl { get; set; } = "https://musicbrainz.org/ws/2/";
/// <summary>
/// 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 <see langword="false"/>, so that a misconfigured base URL cannot silently reach a local service.
/// </summary>
public bool DoesAllowPrivateBaseUrl { get; set; }
/// <summary>
/// Gets or sets the user agent sent with every request to the MusicBrainz API.
/// </summary>
public string UserAgent { get; set; } = "Lumina-MusicBrainz/1.0";
/// <summary>
/// Gets or sets the contact email sent with every request to the MusicBrainz API.
/// </summary>
public string? ContactEmail { get; set; }
/// <summary>
/// Gets or sets the maximum number of results returned by a single search.
/// </summary>
public int SearchResultLimit { get; set; } = 10;
/// <summary>
/// Gets or sets the maximum number of releases fetched for a single release group.
/// </summary>
public int ReleaseLookupLimit { get; set; } = 25;
/// <summary>
/// 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.
/// </summary>
public TimeSpan MinimumRequestInterval { get; set; } = TimeSpan.FromSeconds(1.0);
}
@@ -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;
/// <summary>
/// HTTP client that calls the MusicBrainz web service and deserializes its JSON responses into typed response models.
/// </summary>
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;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzHttpClient"/> class.
/// </summary>
/// <param name="httpClient">The <see cref="HttpClient"/> used to send requests to the MusicBrainz web service.</param>
/// <param name="settingsProvider">The provider of the settings that configure the MusicBrainz web service requests.</param>
/// <param name="requestThrottle">The process-wide throttle that spaces out the requests sent to the MusicBrainz web service.</param>
/// <param name="responseCache">The process-wide cache that avoids fetching the same entity more than once during a run.</param>
public MusicBrainzHttpClient(HttpClient httpClient, MusicBrainzSettingsProvider settingsProvider, MusicBrainzRequestThrottle requestThrottle, MusicBrainzResponseCache responseCache)
{
_httpClient = httpClient;
_settingsProvider = settingsProvider;
_requestThrottle = requestThrottle;
_responseCache = responseCache;
}
/// <summary>
/// Looks up the artist identified by <paramref name="musicBrainzArtistId"/>.
/// </summary>
/// <param name="musicBrainzArtistId">The MusicBrainz identifier of the artist.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The artist, or <see langword="null"/> when no artist was found.</returns>
public Task<MusicBrainzArtistResponse?> GetArtistAsync(Guid musicBrainzArtistId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzArtistResponse>(
$"artist/{musicBrainzArtistId:D}?inc=aliases+tags+genres+url-rels+artist-rels+ratings&fmt=json", cancellationToken);
}
/// <summary>
/// Searches MusicBrainz for artists matching the provided query.
/// </summary>
/// <param name="query">The search query.</param>
/// <param name="limit">The maximum number of results to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of matching artists.</returns>
public async Task<IReadOnlyList<MusicBrainzArtistResponse>> SearchArtistsAsync(string query, int limit, CancellationToken cancellationToken)
{
MusicBrainzArtistSearchResponse? response = await GetJsonOrNullAsync<MusicBrainzArtistSearchResponse>(
$"artist?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
cancellationToken).ConfigureAwait(false);
return response?.Artists ?? [];
}
/// <summary>
/// Looks up the release group identified by <paramref name="musicBrainzReleaseGroupId"/>.
/// </summary>
/// <param name="musicBrainzReleaseGroupId">The MusicBrainz identifier of the release group.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The release group, or <see langword="null"/> when no release group was found.</returns>
public Task<MusicBrainzReleaseGroupResponse?> GetReleaseGroupAsync(Guid musicBrainzReleaseGroupId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzReleaseGroupResponse>(
$"release-group/{musicBrainzReleaseGroupId:D}?inc=artist-credits+tags+genres+ratings&fmt=json", cancellationToken);
}
/// <summary>
/// Searches MusicBrainz for release groups matching the provided query.
/// </summary>
/// <param name="query">The search query.</param>
/// <param name="limit">The maximum number of results to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of matching release groups.</returns>
public async Task<IReadOnlyList<MusicBrainzReleaseGroupResponse>> SearchReleaseGroupsAsync(string query, int limit, CancellationToken cancellationToken)
{
MusicBrainzReleaseGroupSearchResponse? response = await GetJsonOrNullAsync<MusicBrainzReleaseGroupSearchResponse>(
$"release-group?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
cancellationToken).ConfigureAwait(false);
return response?.ReleaseGroups ?? [];
}
/// <summary>
/// Looks up the release identified by <paramref name="musicBrainzReleaseId"/>.
/// </summary>
/// <param name="musicBrainzReleaseId">The MusicBrainz identifier of the release.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The release, or <see langword="null"/> when no release was found.</returns>
public Task<MusicBrainzReleaseResponse?> GetReleaseAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzReleaseResponse>(
$"release/{musicBrainzReleaseId:D}?inc=artist-credits+labels+release-groups+media+tags+genres+artist-rels&fmt=json", cancellationToken);
}
/// <summary>
/// Browses the releases that belong to the release group identified by <paramref name="musicBrainzReleaseGroupId"/>.
/// </summary>
/// <param name="musicBrainzReleaseGroupId">The MusicBrainz identifier of the release group.</param>
/// <param name="limit">The maximum number of releases to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of releases of the release group.</returns>
public async Task<IReadOnlyList<MusicBrainzReleaseResponse>> BrowseReleasesByReleaseGroupAsync(Guid musicBrainzReleaseGroupId, int limit, CancellationToken cancellationToken)
{
MusicBrainzReleaseBrowseResponse? response = await GetJsonOrNullAsync<MusicBrainzReleaseBrowseResponse>(
$"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 ?? [];
}
/// <summary>
/// Looks up the recording identified by <paramref name="musicBrainzRecordingId"/>.
/// </summary>
/// <param name="musicBrainzRecordingId">The MusicBrainz identifier of the recording.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The recording, or <see langword="null"/> when no recording was found.</returns>
public Task<MusicBrainzRecordingResponse?> GetRecordingAsync(Guid musicBrainzRecordingId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzRecordingResponse>(
$"recording/{musicBrainzRecordingId:D}?inc=artist-credits+isrcs+releases+tags+genres+work-rels+artist-rels+ratings&fmt=json", cancellationToken);
}
/// <summary>
/// Searches MusicBrainz for recordings matching the provided query.
/// </summary>
/// <param name="query">The search query.</param>
/// <param name="limit">The maximum number of results to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of matching recordings.</returns>
public async Task<IReadOnlyList<MusicBrainzRecordingResponse>> SearchRecordingsAsync(string query, int limit, CancellationToken cancellationToken)
{
MusicBrainzRecordingSearchResponse? response = await GetJsonOrNullAsync<MusicBrainzRecordingSearchResponse>(
$"recording?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
cancellationToken).ConfigureAwait(false);
return response?.Recordings ?? [];
}
/// <summary>
/// Looks up the recordings that carry the provided ISRC.
/// </summary>
/// <param name="isrc">The ISRC to look up.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of recordings that carry the ISRC.</returns>
public async Task<IReadOnlyList<MusicBrainzRecordingResponse>> GetRecordingsByIsrcAsync(string isrc, CancellationToken cancellationToken)
{
MusicBrainzRecordingListResponse? response = await GetJsonOrNullAsync<MusicBrainzRecordingListResponse>(
$"isrc/{Uri.EscapeDataString(isrc)}?inc=artist-credits+isrcs+work-rels+artist-rels&fmt=json", cancellationToken).ConfigureAwait(false);
return response?.Recordings ?? [];
}
/// <summary>
/// Looks up the work identified by <paramref name="musicBrainzWorkId"/>, together with its credited contributors.
/// </summary>
/// <param name="musicBrainzWorkId">The MusicBrainz identifier of the work.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The work, or <see langword="null"/> when no work was found.</returns>
public Task<MusicBrainzWorkResponse?> GetWorkAsync(Guid musicBrainzWorkId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzWorkResponse>(
$"work/{musicBrainzWorkId:D}?inc=artist-rels+tags+genres&fmt=json", cancellationToken);
}
/// <summary>
/// Looks up the release identified by <paramref name="musicBrainzReleaseId"/>, 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.
/// </summary>
/// <param name="musicBrainzReleaseId">The MusicBrainz identifier of the release.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The release, with its media, tracks and recordings, or <see langword="null"/> when no release was found.</returns>
public Task<MusicBrainzReleaseResponse?> GetReleaseWithRecordingsAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzReleaseResponse>(
$"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);
}
/// <summary>
/// Gets the JSON resource at the given relative URL and deserializes it into <typeparamref name="TModel"/>.
/// </summary>
/// <typeparam name="TModel">The type to deserialize the JSON response into.</typeparam>
/// <param name="relativeUrl">The URL of the resource, relative to the base address.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized resource, or <see langword="null"/> when the resource was not found.</returns>
/// <remarks>Transient failures and rate limiting are handled by retrying the request up to three times.</remarks>
private async Task<TModel?> GetJsonOrNullAsync<TModel>(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<TModel>(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<TModel>(json, s_serializerOptions);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="settings">The settings that configure the MusicBrainz web service requests.</param>
/// <param name="relativeUrl">The URL of the resource, relative to the base address.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The HTTP response message for the request.</returns>
private async Task<HttpResponseMessage> 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;
}
}
/// <summary>
/// Gets the delay to wait before the next attempt, preferring the delay requested by the MusicBrainz web service when it is provided.
/// </summary>
/// <param name="attempt">The one based number of the attempt that just failed.</param>
/// <param name="response">The response of the failed attempt, when the failure was a response rather than a transport exception.</param>
/// <returns>The delay to wait before the next attempt.</returns>
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));
}
/// <summary>
/// Determines whether the provided base URL points to the real MusicBrainz web service, which is the only one whose rate limit is observed.
/// </summary>
/// <param name="baseUrl">The base URL of the MusicBrainz web service the requests are sent to.</param>
/// <returns><see langword="true"/> when the base URL points to the real MusicBrainz web service, otherwise <see langword="false"/>.</returns>
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);
}
/// <summary>
/// Applies the request headers configured in the <paramref name="settings"/> onto the underlying HTTP client, unless they are already set.
/// </summary>
/// <param name="settings">The settings that configure the MusicBrainz web service requests.</param>
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);
}
}
/// <summary>
/// Combines the configured base URL with the given relative URL into the absolute URI of a request.
/// </summary>
/// <param name="baseUrl">The base URL of the MusicBrainz web service the requests are sent to.</param>
/// <param name="relativeUrl">The URL of the resource, relative to the base URL.</param>
/// <returns>The absolute URI of the request.</returns>
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);
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core.Api;
/// <summary>
/// Spaces out the requests sent to the MusicBrainz web service, so the configured minimum request interval is respected across every caller in the process.
/// </summary>
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;
/// <summary>
/// Waits until the minimum interval elapsed since the previous reserved request, then reserves the next request slot.
/// </summary>
/// <param name="minimumRequestInterval">The minimum amount of time that must elapse between two consecutive requests.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task that completes once the caller may send its request.</returns>
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();
}
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
internal sealed class MusicBrainzResponseCache
{
/// <summary>
/// The maximum number of responses the cache keeps.
/// </summary>
internal const int MAXIMUM_ENTRY_COUNT = 20_000;
/// <summary>
/// The maximum total number of characters of the cached response bodies.
/// </summary>
internal const long MAXIMUM_CHARACTER_COUNT = 100_000_000;
/// <summary>
/// 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.
/// </summary>
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<string, CacheEntry> _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;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzResponseCache"/> class with the default budgets and time to live.
/// </summary>
public MusicBrainzResponseCache()
{
_maximumEntryCount = MAXIMUM_ENTRY_COUNT;
_maximumCharacterCount = MAXIMUM_CHARACTER_COUNT;
_timeToLive = s_timeToLive;
}
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzResponseCache"/> class with the provided budgets and time to live.
/// </summary>
/// <param name="maximumEntryCount">The maximum number of responses the cache keeps.</param>
/// <param name="maximumCharacterCount">The maximum total number of characters of the cached response bodies.</param>
/// <param name="timeToLive">The amount of time a cached response stays valid.</param>
internal MusicBrainzResponseCache(int maximumEntryCount, long maximumCharacterCount, TimeSpan timeToLive)
{
_maximumEntryCount = maximumEntryCount;
_maximumCharacterCount = maximumCharacterCount;
_timeToLive = timeToLive;
}
/// <summary>
/// Tries to get the cached response body for <paramref name="key"/>.
/// </summary>
/// <param name="key">The key of the cached response.</param>
/// <param name="json">The cached response body, when found.</param>
/// <returns><see langword="true"/> when an unexpired response was found, otherwise <see langword="false"/>.</returns>
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;
}
/// <summary>
/// Adds or replaces the cached response body for <paramref name="key"/>, then trims the cache back to its budgets.
/// </summary>
/// <param name="key">The key of the cached response.</param>
/// <param name="json">The response body to cache.</param>
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();
}
}
/// <summary>
/// Removes the expired entries, and then the oldest unexpired entries, until the cache is back within its entry count and character budgets.
/// </summary>
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<string, CacheEntry> 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);
}
@@ -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;
/// <summary>
/// Maps MusicBrainz web service responses into the application's media metadata DTOs.
/// </summary>
internal static partial class MusicBrainzMapper
{
/// <summary>
/// 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.
/// </summary>
private static readonly IReadOnlyDictionary<string, CultureInfo> s_neutralCulturesByCode = BuildNeutralCultureLookup();
/// <summary>
/// Matches a four digit year.
/// </summary>
[GeneratedRegex(@"\b(?:1[0-9]{3}|20[0-9]{2}|2100)\b")]
private static partial Regex YearPattern();
/// <summary>
/// Maps a MusicBrainz artist response into artist metadata.
/// </summary>
/// <param name="artist">The artist response to map.</param>
/// <returns>The mapped artist metadata.</returns>
public static ArtistMetadataDto MapArtist(MusicBrainzArtistResponse artist)
{
(List<MediaContributorDto> 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);
}
/// <summary>
/// Maps a MusicBrainz release group, and optionally one of its releases, into album metadata.
/// </summary>
/// <param name="releaseGroup">The release group response to map.</param>
/// <param name="release">The selected release of the release group, or <see langword="null"/> when no release was selected.</param>
/// <returns>The mapped album metadata.</returns>
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<MediaContributorDto> 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<MusicBrainzMediumResponse> 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<string> 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));
}
/// <summary>
/// Maps a MusicBrainz recording, and optionally its work and release, into track metadata.
/// </summary>
/// <param name="recording">The recording response to map.</param>
/// <param name="work">The work the recording is an instance of, or <see langword="null"/> when the recording has no work.</param>
/// <param name="release">The release the recording appears on, or <see langword="null"/> when it is not known.</param>
/// <returns>The mapped track metadata.</returns>
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<MediaContributorDto> 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));
}
/// <summary>
/// Maps a MusicBrainz work into a work DTO.
/// </summary>
/// <param name="work">The work response to map.</param>
/// <returns>The mapped work.</returns>
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))]);
}
/// <summary>
/// Maps a MusicBrainz area into an area DTO.
/// </summary>
/// <param name="area">The area response to map.</param>
/// <returns>The mapped area, or <see langword="null"/> when no area is provided.</returns>
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));
}
/// <summary>
/// Maps a MusicBrainz alias into an alias DTO.
/// </summary>
/// <param name="alias">The alias response to map.</param>
/// <returns>The mapped alias.</returns>
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);
}
/// <summary>
/// Maps the genres of a MusicBrainz entity into genre DTOs.
/// </summary>
/// <param name="genres">The genre responses to map.</param>
/// <returns>The mapped genre DTOs.</returns>
private static List<GenreDto> MapGenres(IReadOnlyCollection<MusicBrainzTagResponse> genres)
{
return [.. genres
.Where(genre => !string.IsNullOrWhiteSpace(genre.Name))
.Select(genre => new GenreDto(genre.Name))
.DistinctBy(genre => genre.Name, StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// Maps the tags of a MusicBrainz entity into tag DTOs.
/// </summary>
/// <param name="tags">The tag responses to map.</param>
/// <returns>The mapped tag DTOs.</returns>
private static List<TagDto> MapTags(IReadOnlyCollection<MusicBrainzTagResponse> tags)
{
return [.. tags
.Where(tag => !string.IsNullOrWhiteSpace(tag.Name))
.Select(tag => new TagDto(tag.Name))
.DistinctBy(tag => tag.Name, StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// Maps the rating of a MusicBrainz entity into a rating DTO.
/// </summary>
/// <param name="rating">The rating response to map.</param>
/// <returns>The mapped rating DTO, or an empty list when no rating is provided.</returns>
private static List<AudioRatingDto> 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)];
}
/// <summary>
/// Maps an ISO 639-3 language code into a language DTO.
/// </summary>
/// <param name="rawCode">The code to map.</param>
/// <returns>The mapped language, or <see langword="null"/> when the code is empty.</returns>
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);
}
/// <summary>
/// Builds the lookup of the process' neutral cultures, indexed by both their two letter and three letter ISO 639 codes.
/// </summary>
/// <returns>The neutral cultures, indexed by their ISO 639 codes.</returns>
private static IReadOnlyDictionary<string, CultureInfo> BuildNeutralCultureLookup()
{
Dictionary<string, CultureInfo> 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;
}
/// <summary>
/// Maps the artist credit of a MusicBrainz entity into attributed performing contributors.
/// </summary>
/// <param name="artistCredit">The artist credit to map.</param>
/// <returns>The mapped contributors.</returns>
private static List<MediaContributorDto> MapArtistCredit(IReadOnlyCollection<MusicBrainzArtistCreditResponse> artistCredit)
{
List<MediaContributorDto> 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;
}
/// <summary>
/// Maps the artist relations of a MusicBrainz entity into contributors, excluding the URL relations.
/// </summary>
/// <param name="relations">The relations to map.</param>
/// <returns>The mapped contributors.</returns>
private static List<MediaContributorDto> MapContributorsFromRelations(IReadOnlyCollection<MusicBrainzRelationResponse> relations)
{
List<MediaContributorDto> 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;
}
/// <summary>
/// Maps the relations of an artist into its contributing members, and its official homepage.
/// </summary>
/// <param name="relations">The relations of the artist.</param>
/// <returns>The mapped contributors, and the official homepage of the artist.</returns>
private static (List<MediaContributorDto> Contributors, string? Website) MapArtistRelations(IReadOnlyCollection<MusicBrainzRelationResponse> relations)
{
List<MediaContributorDto> 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);
}
/// <summary>
/// Adds a contributor to the provided list, unless an identical name and role pair is already present.
/// </summary>
/// <param name="contributors">The contributors collected so far.</param>
/// <param name="displayName">The display name of the contributor.</param>
/// <param name="role">The role the contributor played.</param>
private static void AddContributor(List<MediaContributorDto> 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));
}
/// <summary>
/// Adds the <paramref name="incoming"/> contributors to <paramref name="contributors"/>, skipping the duplicate name and role pairs.
/// </summary>
/// <param name="contributors">The contributors collected so far.</param>
/// <param name="incoming">The contributors to add.</param>
private static void AddContributors(List<MediaContributorDto> contributors, IReadOnlyCollection<MediaContributorDto> incoming)
{
foreach (MediaContributorDto contributor in incoming)
{
if (contributor.Name?.DisplayName is not string displayName)
continue;
AddContributor(contributors, displayName, contributor.Role ?? MediaContributorRole.Other);
}
}
/// <summary>
/// Maps a MusicBrainz relationship type, and its attributes, into a canonical media contributor role.
/// </summary>
/// <param name="relationType">The relationship type to map.</param>
/// <param name="attributes">The attributes of the relationship.</param>
/// <returns>The mapped contributor role.</returns>
private static MediaContributorRole MapRole(string? relationType, IReadOnlyCollection<string> 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;
}
/// <summary>
/// Maps a MusicBrainz instrument attribute into a canonical media contributor role.
/// </summary>
/// <param name="attribute">The instrument attribute to map.</param>
/// <returns>The mapped contributor role, or <see langword="null"/> when the attribute is not an instrument.</returns>
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;
}
/// <summary>
/// Maps a MusicBrainz artist type into the application enum.
/// </summary>
/// <param name="type">The artist type to map.</param>
/// <returns>The mapped artist type, or <see langword="null"/> when the type is unknown.</returns>
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
};
}
/// <summary>
/// Maps a MusicBrainz gender into the application enum.
/// </summary>
/// <param name="gender">The gender to map.</param>
/// <returns>The mapped gender, or <see langword="null"/> when the gender is unknown.</returns>
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
};
}
/// <summary>
/// Maps the primary and secondary types of a release group into the application enum.
/// </summary>
/// <param name="primaryType">The primary type of the release group.</param>
/// <param name="secondaryTypes">The secondary types of the release group.</param>
/// <returns>The mapped release types.</returns>
private static List<MusicReleaseType> MapReleaseTypes(string? primaryType, IReadOnlyCollection<string> secondaryTypes)
{
List<MusicReleaseType> 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;
}
/// <summary>
/// Maps a single MusicBrainz release type into the application enum.
/// </summary>
/// <param name="type">The release type to map.</param>
/// <returns>The mapped release type, or <see langword="null"/> when the type is unknown.</returns>
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
};
}
/// <summary>
/// Maps a MusicBrainz release status into the application enum.
/// </summary>
/// <param name="status">The release status to map.</param>
/// <returns>The mapped release status, or <see langword="null"/> when the status is unknown.</returns>
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
};
}
/// <summary>
/// Maps a MusicBrainz medium format into the application enum.
/// </summary>
/// <param name="format">The format to map.</param>
/// <returns>The mapped media format, or <see langword="null"/> when the format is unknown.</returns>
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
};
}
/// <summary>
/// Maps a MusicBrainz release packaging into the application enum.
/// </summary>
/// <param name="packaging">The packaging to map.</param>
/// <returns>The mapped packaging, or <see langword="null"/> when the packaging is unknown.</returns>
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
};
}
/// <summary>
/// Maps an ISO 3166-1 alpha-2 country code into the application enum.
/// </summary>
/// <param name="country">The country code to map.</param>
/// <returns>The mapped release country, or <see langword="null"/> when the code is unknown.</returns>
private static ReleaseCountry? MapReleaseCountry(string? country)
{
if (string.IsNullOrWhiteSpace(country))
return null;
return Enum.TryParse(country.Trim(), ignoreCase: true, out ReleaseCountry releaseCountry) ? releaseCountry : null;
}
/// <summary>
/// Parses a MusicBrainz identifier into a <see cref="Guid"/>.
/// </summary>
/// <param name="value">The MusicBrainz identifier to parse.</param>
/// <returns>The parsed identifier, or <see langword="null"/> when the value is not a valid identifier.</returns>
private static Guid? ParseGuid(string? value)
{
return Guid.TryParse(value, out Guid parsed) ? parsed : null;
}
/// <summary>
/// Parses a MusicBrainz date string into a date and a year.
/// </summary>
/// <param name="value">The date string to parse.</param>
/// <returns>The parsed date and year, or <see langword="null"/> values when the string could not be parsed.</returns>
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);
}
/// <summary>
/// Returns the trimmed value, or <see langword="null"/> when the value is empty or white space.
/// </summary>
/// <param name="value">The value to process.</param>
/// <returns>The trimmed value, or <see langword="null"/>.</returns>
private static string? NullIfWhiteSpace(string? value)
{
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
}
@@ -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;
/// <summary>
/// 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.
/// </summary>
internal sealed class MusicBrainzAlbumMetadataProvider : IMetadataProvider<AlbumMetadataLookupDto, AlbumMetadataDto>
{
private readonly MusicBrainzHttpClient _musicBrainzHttpClient;
private readonly MusicBrainzSettingsProvider _settingsProvider;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "MusicBrainz";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => true;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzAlbumMetadataProvider"/> class.
/// </summary>
/// <param name="musicBrainzHttpClient">The HTTP client used to call the MusicBrainz web service.</param>
/// <param name="settingsProvider">The provider of the settings that configure the MusicBrainz web service requests.</param>
public MusicBrainzAlbumMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider)
{
_musicBrainzHttpClient = musicBrainzHttpClient;
_settingsProvider = settingsProvider;
}
/// <summary>
/// Searches for the metadata of the album described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the album to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of album metadata candidates found.</returns>
public async Task<IReadOnlyList<AlbumMetadataDto>> GetSearchResultsAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(lookup.Title))
return [];
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
IReadOnlyList<MusicBrainzReleaseGroupResponse> releaseGroups = await _musicBrainzHttpClient
.SearchReleaseGroupsAsync(BuildReleaseGroupQuery(lookup.Title, lookup.ArtistName), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
List<AlbumMetadataDto> candidates = [];
foreach (MusicBrainzReleaseGroupResponse releaseGroup in releaseGroups)
if (!string.IsNullOrWhiteSpace(releaseGroup.Title))
candidates.Add(MusicBrainzMapper.MapAlbum(releaseGroup, null));
return candidates;
}
/// <summary>
/// Gets the metadata of the album described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the album to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the album, or <see langword="null"/> when no album was found.</returns>
public async Task<AlbumMetadataDto?> 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<MusicBrainzReleaseGroupResponse> 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<MusicBrainzReleaseResponse> releases = await _musicBrainzHttpClient
.BrowseReleasesByReleaseGroupAsync(releaseGroupGuid, settings.ReleaseLookupLimit, cancellationToken).ConfigureAwait(false);
release = SelectRelease(releases, lookup);
}
return MusicBrainzMapper.MapAlbum(releaseGroup, release);
}
/// <summary>
/// Selects the release of a release group that best matches the lookup, favoring official releases and those released in the lookup year.
/// </summary>
/// <param name="releases">The releases to select from.</param>
/// <param name="lookup">The lookup the selected release must match.</param>
/// <returns>The best matching release, or <see langword="null"/> when no release was provided.</returns>
private static MusicBrainzReleaseResponse? SelectRelease(IReadOnlyList<MusicBrainzReleaseResponse> 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<MusicBrainzReleaseResponse> 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();
}
/// <summary>
/// Scores a release against the lookup to rank how well it matches.
/// </summary>
/// <param name="release">The release to score.</param>
/// <param name="lookup">The lookup the release must match.</param>
/// <returns>The match score of the release, where a higher score is a better match.</returns>
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;
}
/// <summary>
/// Gets the year of a MusicBrainz date string.
/// </summary>
/// <param name="date">The date string to read.</param>
/// <returns>The year of the date, or <see langword="null"/> when it could not be read.</returns>
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;
}
/// <summary>
/// Builds the MusicBrainz release group search query for the provided title and artist.
/// </summary>
/// <param name="title">The title of the release group.</param>
/// <param name="artistName">The name of the artist, if applicable.</param>
/// <returns>The built search query.</returns>
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;
}
}
@@ -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;
/// <summary>
/// Provides music artist metadata from MusicBrainz by resolving lookups into artist metadata DTOs.
/// </summary>
internal sealed class MusicBrainzArtistMetadataProvider : IMetadataProvider<ArtistMetadataLookupDto, ArtistMetadataDto>
{
private readonly MusicBrainzHttpClient _musicBrainzHttpClient;
private readonly MusicBrainzSettingsProvider _settingsProvider;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "MusicBrainz";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => true;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzArtistMetadataProvider"/> class.
/// </summary>
/// <param name="musicBrainzHttpClient">The HTTP client used to call the MusicBrainz web service.</param>
/// <param name="settingsProvider">The provider of the settings that configure the MusicBrainz web service requests.</param>
public MusicBrainzArtistMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider)
{
_musicBrainzHttpClient = musicBrainzHttpClient;
_settingsProvider = settingsProvider;
}
/// <summary>
/// Searches for the metadata of the artist described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the artist to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of artist metadata candidates found.</returns>
public async Task<IReadOnlyList<ArtistMetadataDto>> GetSearchResultsAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(lookup.Name))
return [];
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
IReadOnlyList<MusicBrainzArtistResponse> artists = await _musicBrainzHttpClient
.SearchArtistsAsync(lookup.Name.Trim(), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
List<ArtistMetadataDto> candidates = [];
foreach (MusicBrainzArtistResponse artist in artists)
if (!string.IsNullOrWhiteSpace(artist.Name))
candidates.Add(MusicBrainzMapper.MapArtist(artist));
return candidates;
}
/// <summary>
/// Gets the metadata of the artist described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the artist to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the artist, or <see langword="null"/> when no artist was found.</returns>
public async Task<ArtistMetadataDto?> 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<MusicBrainzArtistResponse> 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);
}
}
@@ -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;
/// <summary>
/// Plugin that provides music metadata retrieval from MusicBrainz.
/// </summary>
public sealed class MusicBrainzPlugin : IPlugin, IPluginServiceRegistrator
{
/// <summary>
/// The unique identifier of the plugin.
/// </summary>
public static readonly Guid s_pluginId = new("f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3");
/// <summary>
/// Gets the unique identifier of the plugin.
/// </summary>
public Guid Id => s_pluginId;
/// <summary>
/// Gets the display name of the plugin.
/// </summary>
public string Name => "MusicBrainz Metadata";
/// <summary>
/// Gets the author of the plugin.
/// </summary>
public string Author => "Lumina";
/// <summary>
/// Gets the version of the plugin.
/// </summary>
public Version Version => new(1, 0, 0);
/// <summary>
/// Gets the description of the plugin.
/// </summary>
public string Description => "Retrieves artist, album and track metadata from MusicBrainz.";
/// <summary>
/// Gets the settings schema of the plugin.
/// </summary>
/// <returns>The settings descriptors of the plugin.</returns>
public IReadOnlyList<PluginSettingDescriptorDto> 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")
];
}
/// <summary>
/// Registers the services required by the plugin.
/// </summary>
/// <param name="services">The service collection to register the services into.</param>
public void RegisterServices(IServiceCollection services)
{
services.AddMusicBrainzMetadataProviders(pluginId: Id);
}
}
@@ -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;
/// <summary>
/// Provides track metadata from MusicBrainz by resolving lookups into audio metadata DTOs.
/// </summary>
internal sealed class MusicBrainzTrackMetadataProvider : IMetadataProvider<TrackMetadataLookupDto, AudioMetadataDto>
{
private readonly MusicBrainzHttpClient _musicBrainzHttpClient;
private readonly MusicBrainzSettingsProvider _settingsProvider;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "MusicBrainz";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => true;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzTrackMetadataProvider"/> class.
/// </summary>
/// <param name="musicBrainzHttpClient">The HTTP client used to call the MusicBrainz web service.</param>
/// <param name="settingsProvider">The provider of the settings that configure the MusicBrainz web service requests.</param>
public MusicBrainzTrackMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider)
{
_musicBrainzHttpClient = musicBrainzHttpClient;
_settingsProvider = settingsProvider;
}
/// <summary>
/// Searches for the metadata of the track described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the track to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of track metadata candidates found.</returns>
public async Task<IReadOnlyList<AudioMetadataDto>> GetSearchResultsAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(lookup.Title))
return [];
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
IReadOnlyList<MusicBrainzRecordingResponse> recordings = await _musicBrainzHttpClient
.SearchRecordingsAsync(BuildRecordingQuery(lookup), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
List<AudioMetadataDto> candidates = [];
foreach (MusicBrainzRecordingResponse recording in recordings)
if (!string.IsNullOrWhiteSpace(recording.Title))
candidates.Add(MusicBrainzMapper.MapTrack(recording, null, null));
return candidates;
}
/// <summary>
/// Gets the metadata of the track described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the track to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the track, or <see langword="null"/> when no track was found.</returns>
public async Task<AudioMetadataDto?> 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<MusicBrainzRecordingResponse> 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<MusicBrainzRecordingResponse> 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);
}
/// <summary>
/// Falls back to the work identifier of the tags when MusicBrainz did not link the recording to a work.
/// </summary>
/// <param name="work">The work resolved from MusicBrainz, if any.</param>
/// <param name="lookup">The lookup describing the local track.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The provided work, the work resolved from the work identifier of the tags, or <see langword="null"/> when neither is available.</returns>
private async Task<MusicBrainzWorkResponse?> 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);
}
/// <summary>
/// Finds the track of <paramref name="release"/> that matches the provided <paramref name="lookup"/>, matching the recording identifier first,
/// then the disc and track numbers, then the title, and finally the duration.
/// </summary>
/// <param name="release">The release whose tracklist is searched.</param>
/// <param name="lookup">The lookup describing the local track.</param>
/// <returns>The matching track, or <see langword="null"/> when no track matched.</returns>
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<MusicBrainzTrackResponse> 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<MusicBrainzTrackResponse> 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];
}
/// <summary>
/// Gets the work the provided <paramref name="recording"/> is a performance of, from the relations already embedded in the response.
/// </summary>
/// <param name="recording">The recording whose work is resolved.</param>
/// <returns>The embedded work, or <see langword="null"/> when the recording has no work.</returns>
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);
}
/// <summary>
/// Resolves the full recording of the provided search or ISRC lookup result.
/// </summary>
/// <param name="recording">The partial recording to resolve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The full recording, or <see langword="null"/> when the recording could not be resolved.</returns>
private async Task<MusicBrainzRecordingResponse?> 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);
}
/// <summary>
/// Resolves the work the provided recording is an instance of, together with its credited contributors.
/// </summary>
/// <param name="recording">The recording whose work is resolved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The work of the recording, or <see langword="null"/> when the recording has no work.</returns>
private async Task<MusicBrainzWorkResponse?> 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);
}
/// <summary>
/// Resolves the release the provided recording appears on, for the release level language and script.
/// </summary>
/// <param name="recording">The recording whose release is resolved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The release of the recording, or <see langword="null"/> when the recording does not reference a release.</returns>
private async Task<MusicBrainzReleaseResponse?> 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);
}
/// <summary>
/// Builds the MusicBrainz recording search query for the provided lookup.
/// </summary>
/// <param name="lookup">The lookup describing the track.</param>
/// <returns>The built search query.</returns>
private static string BuildRecordingQuery(TrackMetadataLookupDto lookup)
{
List<string> 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);
}
}
@@ -0,0 +1,37 @@
namespace Lumina.Plugins.MusicBrainz.Core.Settings;
/// <summary>
/// Keys of the settings of the MusicBrainz metadata plugin, shared by the settings schema and the settings loader.
/// </summary>
internal static class MusicBrainzSettingsKeys
{
/// <summary>
/// The key of the setting defining the base URL of the MusicBrainz web service.
/// </summary>
internal const string BASE_URL = "BaseUrl";
/// <summary>
/// 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.
/// </summary>
internal const string DOES_ALLOW_PRIVATE_BASE_URL = "DoesAllowPrivateBaseUrl";
/// <summary>
/// The key of the setting defining the contact email sent to the MusicBrainz API.
/// </summary>
internal const string CONTACT_EMAIL = "ContactEmail";
/// <summary>
/// The key of the setting defining the maximum number of results returned by a single search.
/// </summary>
internal const string SEARCH_RESULT_LIMIT = "SearchResultLimit";
/// <summary>
/// The key of the setting defining the maximum number of releases fetched for a single release group.
/// </summary>
internal const string RELEASE_LOOKUP_LIMIT = "ReleaseLookupLimit";
/// <summary>
/// The key of the setting defining the minimum interval between consecutive requests to the MusicBrainz API, in seconds.
/// </summary>
internal const string MINIMUM_REQUEST_INTERVAL_SECONDS = "MinimumRequestIntervalSeconds";
}
@@ -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;
/// <summary>
/// Provides the runtime settings of the MusicBrainz metadata plugin, overlaying the settings persisted by the host over the configured defaults.
/// </summary>
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;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzSettingsProvider"/> class.
/// </summary>
/// <param name="settingsStore">The store of the settings persisted by the host, or <see langword="null"/> when no store is available.</param>
/// <param name="pluginId">The unique identifier of the plugin whose settings are read.</param>
/// <param name="defaults">The runtime settings with the default values and the optional configuration callback already applied.</param>
public MusicBrainzSettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, MusicBrainzSettingsDto defaults)
{
_settingsStore = settingsStore;
_pluginId = pluginId;
_defaults = defaults;
}
/// <summary>
/// Gets the runtime settings of the plugin, reading and applying the settings persisted by the host on the first call.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The runtime settings of the plugin.</returns>
public async Task<MusicBrainzSettingsDto> 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<string, string>? 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();
}
}
/// <summary>
/// Overlays the persisted settings onto the provided runtime settings, keeping the default values of the settings that were not persisted.
/// </summary>
/// <param name="settings">The runtime settings onto which the persisted settings are applied.</param>
/// <param name="storedSettings">The settings persisted by the host, keyed by setting key.</param>
private static void Apply(MusicBrainzSettingsDto settings, IReadOnlyDictionary<string, string> 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));
}
/// <summary>
/// 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.
/// </summary>
/// <param name="host">The host of the persisted base URL.</param>
/// <returns><see langword="true"/> when the host is public, otherwise <see langword="false"/>.</returns>
/// <remarks>
/// 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 <see cref="MusicBrainzSettingsDto.DoesAllowPrivateBaseUrl"/> is enabled, which supports self hosted
/// mirrors on a local network.
/// </remarks>
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;
}
/// <summary>
/// Determines whether the persisted contact email only contains characters that are safe inside the request user agent header.
/// </summary>
/// <param name="contactEmail">The persisted contact email.</param>
/// <returns><see langword="true"/> when the email is safe, otherwise <see langword="false"/>.</returns>
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;
}
/// <summary>
/// Creates a copy of the given runtime settings.
/// </summary>
/// <param name="source">The runtime settings to copy.</param>
/// <returns>A copy of the given runtime settings.</returns>
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
};
}
}
@@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\plugins\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
</ItemGroup>
<Target Name="CopyToPluginsFolder" AfterTargets="Build">
<MakeDir Directories="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="@(ReferenceCopyLocalPaths)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
</Target>
<ItemGroup>
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
<ExcludeAssets>runtime</ExcludeAssets>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
</Project>
@@ -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")]
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzAliasResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzAliasResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzAliasResponse"/> instance with randomized test data.
/// </summary>
/// <param name="name">Optional. The name of the alias.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="sortName">Optional. The sort name of the alias.</param>
/// <param name="includeSortName">Whether the sort name should be included, or forced to <see langword="null"/>.</param>
/// <param name="type">Optional. The type of the alias.</param>
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
/// <param name="locale">Optional. The locale the alias is used in.</param>
/// <param name="includeLocale">Whether the locale should be included, or forced to <see langword="null"/>.</param>
/// <param name="isPrimary">Optional. Whether this is the primary alias.</param>
/// <param name="includePrimary">Whether the primary flag should be included, or forced to <see langword="null"/>.</param>
/// <param name="begin">Optional. The begin date of the alias.</param>
/// <param name="includeBegin">Whether the begin date should be included, or forced to <see langword="null"/>.</param>
/// <param name="end">Optional. The end date of the alias.</param>
/// <param name="includeEnd">Whether the end date should be included, or forced to <see langword="null"/>.</param>
/// <param name="isEnded">Optional. Whether the alias has ended.</param>
/// <param name="includeEnded">Whether the ended flag should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="MusicBrainzAliasResponse"/> instance.</returns>
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
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzAliasResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzAliasResponse"/> instances.</returns>
public List<MusicBrainzAliasResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzAreaResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzAreaResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzAreaResponse"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional. The MusicBrainz identifier of the area.</param>
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="name">Optional. The name of the area.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="sortName">Optional. The sort name of the area.</param>
/// <param name="includeSortName">Whether the sort name should be included, or forced to <see langword="null"/>.</param>
/// <param name="disambiguation">Optional. The disambiguation comment of the area.</param>
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
/// <param name="type">Optional. The MusicBrainz type of the area.</param>
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
/// <param name="iso3166Part1Codes">Optional. The ISO 3166-1 codes of the area.</param>
/// <param name="iso3166Part2Codes">Optional. The ISO 3166-2 codes of the area.</param>
/// <returns>A configured <see cref="MusicBrainzAreaResponse"/> instance.</returns>
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<string>? iso3166Part1Codes = null,
List<string>? 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")]
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzAreaResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzAreaResponse"/> instances.</returns>
public List<MusicBrainzAreaResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzArtistCreditResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzArtistCreditResponseFixture
{
private readonly Faker _faker = new();
private readonly MusicBrainzArtistResponseFixture _musicBrainzArtistResponseFixture = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzArtistCreditResponse"/> instance with randomized test data.
/// </summary>
/// <param name="name">Optional. The credited name of the artist.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="joinPhrase">Optional. The join phrase that follows the credit.</param>
/// <param name="includeJoinPhrase">Whether the join phrase should be included, or forced to <see langword="null"/>.</param>
/// <param name="artist">Optional. The artist the credit refers to.</param>
/// <param name="includeArtist">Whether the artist should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="MusicBrainzArtistCreditResponse"/> instance.</returns>
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
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzArtistCreditResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzArtistCreditResponse"/> instances.</returns>
public List<MusicBrainzArtistCreditResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzArtistResponse"/> record.
/// </summary>
[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();
/// <summary>
/// Creates a new <see cref="MusicBrainzArtistResponse"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional. The MusicBrainz identifier of the artist.</param>
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="name">Optional. The name of the artist.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="sortName">Optional. The sort name of the artist.</param>
/// <param name="includeSortName">Whether the sort name should be included, or forced to <see langword="null"/>.</param>
/// <param name="disambiguation">Optional. The disambiguation comment of the artist.</param>
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
/// <param name="type">Optional. The MusicBrainz type of the artist.</param>
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
/// <param name="gender">Optional. The gender of the artist.</param>
/// <param name="includeGender">Whether the gender should be included, or forced to <see langword="null"/>.</param>
/// <param name="country">Optional. The ISO 3166-1 alpha-2 code of the country of the artist.</param>
/// <param name="includeCountry">Whether the country should be included, or forced to <see langword="null"/>.</param>
/// <param name="area">Optional. The area the artist is primarily identified with.</param>
/// <param name="includeArea">Whether the area should be included, or forced to <see langword="null"/>.</param>
/// <param name="beginArea">Optional. The area the artist began in.</param>
/// <param name="includeBeginArea">Whether the begin area should be included, or forced to <see langword="null"/>.</param>
/// <param name="endArea">Optional. The area the artist ended in.</param>
/// <param name="includeEndArea">Whether the end area should be included, or forced to <see langword="null"/>.</param>
/// <param name="lifeSpan">Optional. The life span of the artist.</param>
/// <param name="includeLifeSpan">Whether the life span should be included, or forced to <see langword="null"/>.</param>
/// <param name="isnis">Optional. The ISNI codes of the artist.</param>
/// <param name="ipis">Optional. The IPI codes of the artist.</param>
/// <param name="aliases">Optional. The alternative names of the artist.</param>
/// <param name="tags">Optional. The tags of the artist.</param>
/// <param name="genres">Optional. The genres of the artist.</param>
/// <param name="relations">Optional. The relationships of the artist to other entities.</param>
/// <param name="rating">Optional. The aggregated rating of the artist.</param>
/// <param name="includeRating">Whether the rating should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="MusicBrainzArtistResponse"/> instance.</returns>
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<string>? isnis = null,
List<string>? ipis = null,
List<MusicBrainzAliasResponse>? aliases = null,
List<MusicBrainzTagResponse>? tags = null,
List<MusicBrainzTagResponse>? genres = null,
List<MusicBrainzRelationResponse>? 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
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzArtistResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzArtistResponse"/> instances.</returns>
public List<MusicBrainzArtistResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzArtistSearchResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzArtistSearchResponseFixture
{
private readonly Faker _faker = new();
private readonly MusicBrainzArtistResponseFixture _musicBrainzArtistResponseFixture = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzArtistSearchResponse"/> instance with randomized test data.
/// </summary>
/// <param name="count">Optional. The total number of matching artists.</param>
/// <param name="offset">Optional. The offset of the returned artists.</param>
/// <param name="artists">Optional. The matching artists.</param>
/// <returns>A configured <see cref="MusicBrainzArtistSearchResponse"/> instance.</returns>
public MusicBrainzArtistSearchResponse Create(
int? count = null,
int? offset = null,
List<MusicBrainzArtistResponse>? artists = null)
{
List<MusicBrainzArtistResponse> resolvedArtists = artists ?? [.. _musicBrainzArtistResponseFixture.CreateMany(2)];
return new MusicBrainzArtistSearchResponse
{
Count = count ?? resolvedArtists.Count,
Offset = offset ?? _faker.Random.Int(0, 100),
Artists = resolvedArtists
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzArtistSearchResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzArtistSearchResponse"/> instances.</returns>
public List<MusicBrainzArtistSearchResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzLabelInfoResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzLabelInfoResponseFixture
{
private readonly Faker _faker = new();
private readonly MusicBrainzLabelResponseFixture _musicBrainzLabelResponseFixture = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzLabelInfoResponse"/> instance with randomized test data.
/// </summary>
/// <param name="catalogNumber">Optional. The catalog number assigned by the label.</param>
/// <param name="includeCatalogNumber">Whether the catalog number should be included, or forced to <see langword="null"/>.</param>
/// <param name="label">Optional. The label that issued the release.</param>
/// <param name="includeLabel">Whether the label should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="MusicBrainzLabelInfoResponse"/> instance.</returns>
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
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzLabelInfoResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzLabelInfoResponse"/> instances.</returns>
public List<MusicBrainzLabelInfoResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzLabelResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzLabelResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzLabelResponse"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional. The MusicBrainz identifier of the label.</param>
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="name">Optional. The name of the label.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="disambiguation">Optional. The disambiguation comment of the label.</param>
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
/// <param name="labelCode">Optional. The label code of the label.</param>
/// <param name="includeLabelCode">Whether the label code should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="MusicBrainzLabelResponse"/> instance.</returns>
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
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzLabelResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzLabelResponse"/> instances.</returns>
public List<MusicBrainzLabelResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzLifeSpanResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzLifeSpanResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzLifeSpanResponse"/> instance with randomized test data.
/// </summary>
/// <param name="begin">Optional. The begin date of the life span.</param>
/// <param name="includeBegin">Whether the begin date should be included, or forced to <see langword="null"/>.</param>
/// <param name="end">Optional. The end date of the life span.</param>
/// <param name="includeEnd">Whether the end date should be included, or forced to <see langword="null"/>.</param>
/// <param name="isEnded">Optional. Whether the life span has ended.</param>
/// <param name="includeEnded">Whether the ended flag should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="MusicBrainzLifeSpanResponse"/> instance.</returns>
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
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzLifeSpanResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzLifeSpanResponse"/> instances.</returns>
public List<MusicBrainzLifeSpanResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzMediumResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzMediumResponseFixture
{
private readonly Faker _faker = new();
private readonly MusicBrainzTrackResponseFixture _musicBrainzTrackResponseFixture = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzMediumResponse"/> instance with randomized test data.
/// </summary>
/// <param name="position">Optional. The position of the medium within its release.</param>
/// <param name="title">Optional. The title of the medium.</param>
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
/// <param name="format">Optional. The format of the medium.</param>
/// <param name="includeFormat">Whether the format should be included, or forced to <see langword="null"/>.</param>
/// <param name="trackCount">Optional. The number of tracks of the medium.</param>
/// <param name="tracks">Optional. The tracks of the medium.</param>
/// <returns>A configured <see cref="MusicBrainzMediumResponse"/> instance.</returns>
public MusicBrainzMediumResponse Create(
int? position = null,
string? title = null,
bool includeTitle = true,
string? format = null,
bool includeFormat = true,
int? trackCount = null,
List<MusicBrainzTrackResponse>? tracks = null)
{
List<MusicBrainzTrackResponse> 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
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzMediumResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzMediumResponse"/> instances.</returns>
public List<MusicBrainzMediumResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(index => Create(position: index + 1))];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzRatingResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzRatingResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzRatingResponse"/> instance with randomized test data.
/// </summary>
/// <param name="value">Optional. The average rating value.</param>
/// <param name="includeValue">Whether the value should be included, or forced to <see langword="null"/>.</param>
/// <param name="votesCount">Optional. The number of votes that contributed to the rating.</param>
/// <param name="includeVotesCount">Whether the votes count should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="MusicBrainzRatingResponse"/> instance.</returns>
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
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzRatingResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzRatingResponse"/> instances.</returns>
public List<MusicBrainzRatingResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzRecordingListResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzRecordingListResponseFixture
{
private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzRecordingListResponse"/> instance with randomized test data.
/// </summary>
/// <param name="recordings">Optional. The recordings that carry the looked up ISRC.</param>
/// <returns>A configured <see cref="MusicBrainzRecordingListResponse"/> instance.</returns>
public MusicBrainzRecordingListResponse Create(List<MusicBrainzRecordingResponse>? recordings = null)
{
return new MusicBrainzRecordingListResponse
{
Recordings = recordings ?? [.. _musicBrainzRecordingResponseFixture.CreateMany(2)]
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzRecordingListResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzRecordingListResponse"/> instances.</returns>
public List<MusicBrainzRecordingListResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzRecordingResponse"/> record.
/// The releases of the recording default to an empty list, because a recording embedded in a release does not carry them.
/// </summary>
[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();
/// <summary>
/// Creates a new <see cref="MusicBrainzRecordingResponse"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional. The MusicBrainz identifier of the recording.</param>
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="title">Optional. The title of the recording.</param>
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
/// <param name="disambiguation">Optional. The disambiguation comment of the recording.</param>
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
/// <param name="length">Optional. The length of the recording in milliseconds.</param>
/// <param name="includeLength">Whether the length should be included, or forced to <see langword="null"/>.</param>
/// <param name="isVideo">Optional. Whether the recording is a video recording.</param>
/// <param name="includeVideo">Whether the video flag should be included, or forced to <see langword="null"/>.</param>
/// <param name="firstReleaseDate">Optional. The date the recording was first released.</param>
/// <param name="includeFirstReleaseDate">Whether the first release date should be included, or forced to <see langword="null"/>.</param>
/// <param name="artistCredit">Optional. The artist credit of the recording.</param>
/// <param name="isrcs">Optional. The ISRCs of the recording.</param>
/// <param name="releases">Optional. The releases the recording appears on.</param>
/// <param name="tags">Optional. The tags of the recording.</param>
/// <param name="genres">Optional. The genres of the recording.</param>
/// <param name="relations">Optional. The relationships of the recording to other entities.</param>
/// <param name="rating">Optional. The aggregated rating of the recording.</param>
/// <param name="includeRating">Whether the rating should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="MusicBrainzRecordingResponse"/> instance.</returns>
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<MusicBrainzArtistCreditResponse>? artistCredit = null,
List<string>? isrcs = null,
List<MusicBrainzReleaseResponse>? releases = null,
List<MusicBrainzTagResponse>? tags = null,
List<MusicBrainzTagResponse>? genres = null,
List<MusicBrainzRelationResponse>? 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
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzRecordingResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzRecordingResponse"/> instances.</returns>
public List<MusicBrainzRecordingResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzRecordingSearchResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzRecordingSearchResponseFixture
{
private readonly Faker _faker = new();
private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzRecordingSearchResponse"/> instance with randomized test data.
/// </summary>
/// <param name="count">Optional. The total number of matching recordings.</param>
/// <param name="offset">Optional. The offset of the returned recordings.</param>
/// <param name="recordings">Optional. The matching recordings.</param>
/// <returns>A configured <see cref="MusicBrainzRecordingSearchResponse"/> instance.</returns>
public MusicBrainzRecordingSearchResponse Create(
int? count = null,
int? offset = null,
List<MusicBrainzRecordingResponse>? recordings = null)
{
List<MusicBrainzRecordingResponse> resolvedRecordings = recordings ?? [.. _musicBrainzRecordingResponseFixture.CreateMany(2)];
return new MusicBrainzRecordingSearchResponse
{
Count = count ?? resolvedRecordings.Count,
Offset = offset ?? _faker.Random.Int(0, 100),
Recordings = resolvedRecordings
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzRecordingSearchResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzRecordingSearchResponse"/> instances.</returns>
public List<MusicBrainzRecordingSearchResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzRelationResponse"/> record.
/// The nested artist, work and url targets are optional, because a relation usually targets only one of them.
/// </summary>
[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> _musicBrainzArtistResponseFixture = new(() => new MusicBrainzArtistResponseFixture());
private readonly Lazy<MusicBrainzWorkResponseFixture> _musicBrainzWorkResponseFixture = new(() => new MusicBrainzWorkResponseFixture());
private readonly MusicBrainzUrlResponseFixture _musicBrainzUrlResponseFixture = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzRelationResponse"/> instance with randomized test data.
/// </summary>
/// <param name="type">Optional. The type of the relationship.</param>
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
/// <param name="typeId">Optional. The MusicBrainz identifier of the type of the relationship.</param>
/// <param name="includeTypeId">Whether the type identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="direction">Optional. The direction of the relationship.</param>
/// <param name="includeDirection">Whether the direction should be included, or forced to <see langword="null"/>.</param>
/// <param name="targetType">Optional. The type of the entity the relationship targets.</param>
/// <param name="includeTargetType">Whether the target type should be included, or forced to <see langword="null"/>.</param>
/// <param name="artist">Optional. The artist the relationship targets.</param>
/// <param name="includeArtist">Whether the artist should be included, or forced to <see langword="null"/>.</param>
/// <param name="work">Optional. The work the relationship targets.</param>
/// <param name="includeWork">Whether the work should be included, or forced to <see langword="null"/>.</param>
/// <param name="url">Optional. The URL the relationship targets.</param>
/// <param name="includeUrl">Whether the URL should be included, or forced to <see langword="null"/>.</param>
/// <param name="attributes">Optional. The attributes of the relationship.</param>
/// <returns>A configured <see cref="MusicBrainzRelationResponse"/> instance.</returns>
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<string>? 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 ?? []
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzRelationResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzRelationResponse"/> instances.</returns>
public List<MusicBrainzRelationResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzReleaseBrowseResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzReleaseBrowseResponseFixture
{
private readonly Faker _faker = new();
private readonly MusicBrainzReleaseResponseFixture _musicBrainzReleaseResponseFixture = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzReleaseBrowseResponse"/> instance with randomized test data.
/// </summary>
/// <param name="releases">Optional. The releases returned by the browse request.</param>
/// <param name="releaseCount">Optional. The total number of releases linked to the browsed entity.</param>
/// <param name="releaseOffset">Optional. The offset of the returned releases.</param>
/// <returns>A configured <see cref="MusicBrainzReleaseBrowseResponse"/> instance.</returns>
public MusicBrainzReleaseBrowseResponse Create(
List<MusicBrainzReleaseResponse>? releases = null,
int? releaseCount = null,
int? releaseOffset = null)
{
List<MusicBrainzReleaseResponse> resolvedReleases = releases ?? [.. _musicBrainzReleaseResponseFixture.CreateMany(2)];
return new MusicBrainzReleaseBrowseResponse
{
Releases = resolvedReleases,
ReleaseCount = releaseCount ?? resolvedReleases.Count,
ReleaseOffset = releaseOffset ?? _faker.Random.Int(0, 100)
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzReleaseBrowseResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzReleaseBrowseResponse"/> instances.</returns>
public List<MusicBrainzReleaseBrowseResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzReleaseEventResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzReleaseEventResponseFixture
{
private readonly Faker _faker = new();
private readonly MusicBrainzAreaResponseFixture _musicBrainzAreaResponseFixture = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzReleaseEventResponse"/> instance with randomized test data.
/// </summary>
/// <param name="date">Optional. The date of the release event.</param>
/// <param name="includeDate">Whether the date should be included, or forced to <see langword="null"/>.</param>
/// <param name="area">Optional. The area of the release event.</param>
/// <param name="includeArea">Whether the area should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="MusicBrainzReleaseEventResponse"/> instance.</returns>
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
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzReleaseEventResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzReleaseEventResponse"/> instances.</returns>
public List<MusicBrainzReleaseEventResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzReleaseGroupResponse"/> record.
/// The releases of the release group default to an empty list, because they are only returned by a dedicated browse request.
/// </summary>
[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();
/// <summary>
/// Creates a new <see cref="MusicBrainzReleaseGroupResponse"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional. The MusicBrainz identifier of the release group.</param>
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="title">Optional. The title of the release group.</param>
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
/// <param name="disambiguation">Optional. The disambiguation comment of the release group.</param>
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
/// <param name="primaryType">Optional. The primary type of the release group.</param>
/// <param name="includePrimaryType">Whether the primary type should be included, or forced to <see langword="null"/>.</param>
/// <param name="secondaryTypes">Optional. The secondary types of the release group.</param>
/// <param name="firstReleaseDate">Optional. The date the release group was first released.</param>
/// <param name="includeFirstReleaseDate">Whether the first release date should be included, or forced to <see langword="null"/>.</param>
/// <param name="artistCredit">Optional. The artist credit of the release group.</param>
/// <param name="releases">Optional. The releases of the release group.</param>
/// <param name="tags">Optional. The tags of the release group.</param>
/// <param name="genres">Optional. The genres of the release group.</param>
/// <param name="rating">Optional. The aggregated rating of the release group.</param>
/// <param name="includeRating">Whether the rating should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="MusicBrainzReleaseGroupResponse"/> instance.</returns>
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<string>? secondaryTypes = null,
string? firstReleaseDate = null,
bool includeFirstReleaseDate = true,
List<MusicBrainzArtistCreditResponse>? artistCredit = null,
List<MusicBrainzReleaseResponse>? releases = null,
List<MusicBrainzTagResponse>? tags = null,
List<MusicBrainzTagResponse>? 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
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzReleaseGroupResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzReleaseGroupResponse"/> instances.</returns>
public List<MusicBrainzReleaseGroupResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzReleaseGroupSearchResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzReleaseGroupSearchResponseFixture
{
private readonly Faker _faker = new();
private readonly MusicBrainzReleaseGroupResponseFixture _musicBrainzReleaseGroupResponseFixture = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzReleaseGroupSearchResponse"/> instance with randomized test data.
/// </summary>
/// <param name="count">Optional. The total number of matching release groups.</param>
/// <param name="offset">Optional. The offset of the returned release groups.</param>
/// <param name="releaseGroups">Optional. The matching release groups.</param>
/// <returns>A configured <see cref="MusicBrainzReleaseGroupSearchResponse"/> instance.</returns>
public MusicBrainzReleaseGroupSearchResponse Create(
int? count = null,
int? offset = null,
List<MusicBrainzReleaseGroupResponse>? releaseGroups = null)
{
List<MusicBrainzReleaseGroupResponse> resolvedReleaseGroups = releaseGroups ?? [.. _musicBrainzReleaseGroupResponseFixture.CreateMany(2)];
return new MusicBrainzReleaseGroupSearchResponse
{
Count = count ?? resolvedReleaseGroups.Count,
Offset = offset ?? _faker.Random.Int(0, 100),
ReleaseGroups = resolvedReleaseGroups
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzReleaseGroupSearchResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzReleaseGroupSearchResponse"/> instances.</returns>
public List<MusicBrainzReleaseGroupSearchResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzReleaseResponse"/> record.
/// </summary>
[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();
/// <summary>
/// Creates a new <see cref="MusicBrainzReleaseResponse"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional. The MusicBrainz identifier of the release.</param>
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="title">Optional. The title of the release.</param>
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
/// <param name="disambiguation">Optional. The disambiguation comment of the release.</param>
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
/// <param name="status">Optional. The status of the release.</param>
/// <param name="includeStatus">Whether the status should be included, or forced to <see langword="null"/>.</param>
/// <param name="date">Optional. The date the release was issued.</param>
/// <param name="includeDate">Whether the date should be included, or forced to <see langword="null"/>.</param>
/// <param name="country">Optional. The ISO 3166-1 alpha-2 code of the country the release was issued in.</param>
/// <param name="includeCountry">Whether the country should be included, or forced to <see langword="null"/>.</param>
/// <param name="releaseEvents">Optional. The release events of the release.</param>
/// <param name="barcode">Optional. The barcode of the release.</param>
/// <param name="includeBarcode">Whether the barcode should be included, or forced to <see langword="null"/>.</param>
/// <param name="packaging">Optional. The outermost packaging of the release.</param>
/// <param name="includePackaging">Whether the packaging should be included, or forced to <see langword="null"/>.</param>
/// <param name="textRepresentation">Optional. The language and script of the titles of the release.</param>
/// <param name="includeTextRepresentation">Whether the text representation should be included, or forced to <see langword="null"/>.</param>
/// <param name="artistCredit">Optional. The artist credit of the release.</param>
/// <param name="releaseGroup">Optional. The release group the release belongs to.</param>
/// <param name="includeReleaseGroup">Whether the release group should be included, or forced to <see langword="null"/>.</param>
/// <param name="labelInfo">Optional. The label information of the release.</param>
/// <param name="media">Optional. The media of the release.</param>
/// <param name="asin">Optional. The ASIN of the release.</param>
/// <param name="includeAsin">Whether the ASIN should be included, or forced to <see langword="null"/>.</param>
/// <param name="tags">Optional. The tags of the release.</param>
/// <param name="genres">Optional. The genres of the release.</param>
/// <param name="relations">Optional. The relationships of the release to other entities.</param>
/// <returns>A configured <see cref="MusicBrainzReleaseResponse"/> instance.</returns>
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<MusicBrainzReleaseEventResponse>? releaseEvents = null,
string? barcode = null,
bool includeBarcode = true,
string? packaging = null,
bool includePackaging = true,
MusicBrainzTextRepresentationResponse? textRepresentation = null,
bool includeTextRepresentation = true,
List<MusicBrainzArtistCreditResponse>? artistCredit = null,
MusicBrainzReleaseGroupResponse? releaseGroup = null,
bool includeReleaseGroup = true,
List<MusicBrainzLabelInfoResponse>? labelInfo = null,
List<MusicBrainzMediumResponse>? media = null,
string? asin = null,
bool includeAsin = true,
List<MusicBrainzTagResponse>? tags = null,
List<MusicBrainzTagResponse>? genres = null,
List<MusicBrainzRelationResponse>? 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 ?? []
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzReleaseResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzReleaseResponse"/> instances.</returns>
public List<MusicBrainzReleaseResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzTagResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzTagResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzTagResponse"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional. The MusicBrainz identifier of a genre tag.</param>
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="name">Optional. The name of the tag.</param>
/// <param name="includeName">Whether the name should be included, or forced to <see langword="null"/>.</param>
/// <param name="disambiguation">Optional. The disambiguation comment of a genre tag.</param>
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
/// <param name="count">Optional. The number of votes the tag received.</param>
/// <returns>A configured <see cref="MusicBrainzTagResponse"/> instance.</returns>
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)
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzTagResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzTagResponse"/> instances.</returns>
public List<MusicBrainzTagResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzTextRepresentationResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzTextRepresentationResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzTextRepresentationResponse"/> instance with randomized test data.
/// </summary>
/// <param name="language">Optional. The ISO 639-3 language code of the release.</param>
/// <param name="includeLanguage">Whether the language should be included, or forced to <see langword="null"/>.</param>
/// <param name="script">Optional. The ISO 15924 script code of the release.</param>
/// <param name="includeScript">Whether the script should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="MusicBrainzTextRepresentationResponse"/> instance.</returns>
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
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzTextRepresentationResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzTextRepresentationResponse"/> instances.</returns>
public List<MusicBrainzTextRepresentationResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzTrackResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzTrackResponseFixture
{
private readonly Faker _faker = new();
private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzTrackResponse"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional. The MusicBrainz identifier of the track.</param>
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="number">Optional. The track number, as displayed on the medium.</param>
/// <param name="includeNumber">Whether the number should be included, or forced to <see langword="null"/>.</param>
/// <param name="position">Optional. The position of the track within its medium.</param>
/// <param name="title">Optional. The title of the track.</param>
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
/// <param name="length">Optional. The length of the track in milliseconds.</param>
/// <param name="includeLength">Whether the length should be included, or forced to <see langword="null"/>.</param>
/// <param name="recording">Optional. The recording the track is a performance of.</param>
/// <param name="includeRecording">Whether the recording should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="MusicBrainzTrackResponse"/> instance.</returns>
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
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzTrackResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzTrackResponse"/> instances.</returns>
public List<MusicBrainzTrackResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(index => Create(position: index + 1))];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzUrlResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzUrlResponseFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzUrlResponse"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional. The MusicBrainz identifier of the URL.</param>
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="resource">Optional. The resource the URL points to.</param>
/// <param name="includeResource">Whether the resource should be included, or forced to <see langword="null"/>.</param>
/// <returns>A configured <see cref="MusicBrainzUrlResponse"/> instance.</returns>
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
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzUrlResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzUrlResponse"/> instances.</returns>
public List<MusicBrainzUrlResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzWorkResponse"/> record.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzWorkResponseFixture
{
private readonly Faker _faker = new();
private readonly MusicBrainzRelationResponseFixture _musicBrainzRelationResponseFixture = new();
private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzWorkResponse"/> instance with randomized test data.
/// </summary>
/// <param name="id">Optional. The MusicBrainz identifier of the work.</param>
/// <param name="includeId">Whether the identifier should be included, or forced to <see langword="null"/>.</param>
/// <param name="title">Optional. The title of the work.</param>
/// <param name="includeTitle">Whether the title should be included, or forced to <see langword="null"/>.</param>
/// <param name="type">Optional. The MusicBrainz type of the work.</param>
/// <param name="includeType">Whether the type should be included, or forced to <see langword="null"/>.</param>
/// <param name="disambiguation">Optional. The disambiguation comment of the work.</param>
/// <param name="includeDisambiguation">Whether the disambiguation should be included, or forced to <see langword="null"/>.</param>
/// <param name="languages">Optional. The languages of the work.</param>
/// <param name="iswcs">Optional. The ISWCs of the work.</param>
/// <param name="relations">Optional. The relationships of the work to other entities.</param>
/// <param name="tags">Optional. The tags of the work.</param>
/// <param name="genres">Optional. The genres of the work.</param>
/// <returns>A configured <see cref="MusicBrainzWorkResponse"/> instance.</returns>
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<string>? languages = null,
List<string>? iswcs = null,
List<MusicBrainzRelationResponse>? relations = null,
List<MusicBrainzTagResponse>? tags = null,
List<MusicBrainzTagResponse>? 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)]
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzWorkResponse"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzWorkResponse"/> instances.</returns>
public List<MusicBrainzWorkResponse> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -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;
/// <summary>
/// Fixture class for the <see cref="MusicBrainzSettingsDto"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class MusicBrainzSettingsDtoFixture
{
private readonly Faker _faker = new();
/// <summary>
/// Creates a new <see cref="MusicBrainzSettingsDto"/> instance with randomized test data.
/// </summary>
/// <param name="baseUrl">Optional. The base URL of the MusicBrainz web service.</param>
/// <param name="doesAllowPrivateBaseUrl">Optional. Whether the base URL may point at a private or local host.</param>
/// <param name="userAgent">Optional. The user agent sent with every request.</param>
/// <param name="contactEmail">Optional. The contact email sent to the MusicBrainz API.</param>
/// <param name="includeContactEmail">Whether the contact email should be included, or forced to <see langword="null"/>.</param>
/// <param name="searchResultLimit">Optional. The maximum number of results returned by a single search.</param>
/// <param name="releaseLookupLimit">Optional. The maximum number of releases fetched for a single release group.</param>
/// <param name="minimumRequestInterval">Optional. The minimum interval between consecutive requests.</param>
/// <returns>A configured <see cref="MusicBrainzSettingsDto"/> instance.</returns>
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))
};
}
/// <summary>
/// Creates multiple <see cref="MusicBrainzSettingsDto"/> instances with randomized test data.
/// </summary>
/// <param name="count">Number of instances to create.</param>
/// <returns>List of configured <see cref="MusicBrainzSettingsDto"/> instances.</returns>
public List<MusicBrainzSettingsDto> CreateMany(int count = 3)
{
return [.. Enumerable.Range(0, count).Select(_ => Create())];
}
}
@@ -0,0 +1,25 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
<IsPackable>false</IsPackable>
<IsTestProject>false</IsTestProject>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoFixture" />
<PackageReference Include="AutoFixture.AutoNSubstitute" />
<PackageReference Include="AutoFixture.Xunit2" />
<PackageReference Include="Bogus" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\plugins\Lumina.Plugins.MusicBrainz\Lumina.Plugins.MusicBrainz.csproj" />
<ProjectReference Include="..\..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj" />
</ItemGroup>
</Project>
@@ -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")]
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzServices"/> class.
/// </summary>
[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<ArgumentNullException>(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<IMetadataProvider>(pluginId).Count());
Assert.Empty(serviceProvider.GetKeyedServices<IMetadataProvider>(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<MusicBrainzHttpClient>());
}
[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<MusicBrainzSettingsProvider>();
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));
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzAliasResponse"/> class.
/// </summary>
[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<MusicBrainzAliasResponse>(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<MusicBrainzAliasResponse>(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<MusicBrainzAliasResponse>(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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzAreaResponse"/> class.
/// </summary>
[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<MusicBrainzAreaResponse>(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<MusicBrainzAreaResponse>(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));
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzArtistCreditResponse"/> class.
/// </summary>
[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<MusicBrainzArtistCreditResponse>(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<MusicBrainzArtistCreditResponse>(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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzArtistResponse"/> class.
/// </summary>
[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<MusicBrainzArtistResponse>(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<MusicBrainzArtistResponse>(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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzArtistSearchResponse"/> class.
/// </summary>
[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<MusicBrainzArtistSearchResponse>(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<MusicBrainzArtistSearchResponse>(JSON);
// Assert
Assert.NotNull(response);
Assert.Equal(2, response.Count);
Assert.Equal(1, response.Offset);
Assert.Equal("artist-id", Assert.Single(response.Artists).Id);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzLabelInfoResponse"/> class.
/// </summary>
[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<MusicBrainzLabelInfoResponse>(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<MusicBrainzLabelInfoResponse>(JSON);
// Assert
Assert.NotNull(response);
Assert.Equal("EMC 4008", response.CatalogNumber);
Assert.NotNull(response.Label);
Assert.Equal("EMI", response.Label.Name);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzLabelResponse"/> class.
/// </summary>
[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<MusicBrainzLabelResponse>(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<MusicBrainzLabelResponse>(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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzLifeSpanResponse"/> class.
/// </summary>
[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<MusicBrainzLifeSpanResponse>(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<MusicBrainzLifeSpanResponse>(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<MusicBrainzLifeSpanResponse>(JSON);
// Assert
Assert.NotNull(response);
Assert.Equal("1970-06-27", response.Begin);
Assert.Equal("1991-11-24", response.End);
Assert.True(response.IsEnded);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzMediumResponse"/> class.
/// </summary>
[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<MusicBrainzMediumResponse>(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<MusicBrainzMediumResponse>(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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzRatingResponse"/> class.
/// </summary>
[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<MusicBrainzRatingResponse>(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<MusicBrainzRatingResponse>(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<MusicBrainzRatingResponse>(JSON);
// Assert
Assert.NotNull(response);
Assert.Equal(4.5m, response.Value);
Assert.Equal(10, response.VotesCount);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzRecordingListResponse"/> class.
/// </summary>
[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<MusicBrainzRecordingListResponse>(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<MusicBrainzRecordingListResponse>(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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzRecordingResponse"/> class.
/// </summary>
[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<MusicBrainzRecordingResponse>(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<MusicBrainzRecordingResponse>(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<MusicBrainzRecordingResponse>(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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzRecordingSearchResponse"/> class.
/// </summary>
[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<MusicBrainzRecordingSearchResponse>(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<MusicBrainzRecordingSearchResponse>(JSON);
// Assert
Assert.NotNull(response);
Assert.Equal(3, response.Count);
Assert.Equal(2, response.Offset);
Assert.Equal("recording-id", Assert.Single(response.Recordings).Id);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzRelationResponse"/> class.
/// </summary>
[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<MusicBrainzRelationResponse>(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<MusicBrainzRelationResponse>(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));
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzReleaseBrowseResponse"/> class.
/// </summary>
[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<MusicBrainzReleaseBrowseResponse>(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<MusicBrainzReleaseBrowseResponse>(JSON);
// Assert
Assert.NotNull(response);
Assert.Equal("release-id", Assert.Single(response.Releases).Id);
Assert.Equal(5, response.ReleaseCount);
Assert.Equal(2, response.ReleaseOffset);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzReleaseEventResponse"/> class.
/// </summary>
[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<MusicBrainzReleaseEventResponse>(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<MusicBrainzReleaseEventResponse>(JSON);
// Assert
Assert.NotNull(response);
Assert.Equal("1975-11-21", response.Date);
Assert.NotNull(response.Area);
Assert.Equal("area-id", response.Area.Id);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzReleaseGroupResponse"/> class.
/// </summary>
[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<MusicBrainzReleaseGroupResponse>(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<MusicBrainzReleaseGroupResponse>(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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzReleaseGroupSearchResponse"/> class.
/// </summary>
[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<MusicBrainzReleaseGroupSearchResponse>(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<MusicBrainzReleaseGroupSearchResponse>(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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzReleaseResponse"/> class.
/// </summary>
[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<MusicBrainzReleaseResponse>(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<MusicBrainzReleaseResponse>(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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzTagResponse"/> class.
/// </summary>
[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<MusicBrainzTagResponse>(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<MusicBrainzTagResponse>(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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzTextRepresentationResponse"/> class.
/// </summary>
[ExcludeFromCodeCoverage]
public class MusicBrainzTextRepresentationResponseTests
{
[Fact]
public void LanguageAndScript_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
{
// Arrange
const string JSON = """{"language":"eng","script":"Latn"}""";
// Act
MusicBrainzTextRepresentationResponse? response = JsonSerializer.Deserialize<MusicBrainzTextRepresentationResponse>(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<MusicBrainzTextRepresentationResponse>(JSON);
// Assert
Assert.NotNull(response);
Assert.Equal("eng", response.Language);
Assert.Equal("Latn", response.Script);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzTrackResponse"/> class.
/// </summary>
[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<MusicBrainzTrackResponse>(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<MusicBrainzTrackResponse>(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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzUrlResponse"/> class.
/// </summary>
[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<MusicBrainzUrlResponse>(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<MusicBrainzUrlResponse>(JSON);
// Assert
Assert.NotNull(response);
Assert.Equal("url-id", response.Id);
Assert.Equal("https://www.queenonline.com/", response.Resource);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzWorkResponse"/> class.
/// </summary>
[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<MusicBrainzWorkResponse>(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<MusicBrainzWorkResponse>(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);
}
}
@@ -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;
/// <summary>
/// Test HTTP message handler that answers every request with a canned response produced by a factory, and records the requests that were sent.
/// </summary>
[ExcludeFromCodeCoverage]
internal sealed class StubHttpMessageHandler : HttpMessageHandler
{
private readonly Func<HttpRequestMessage, int, HttpResponseMessage> _responseFactory;
private int _callCount;
/// <summary>
/// Gets the requests that were sent through the handler.
/// </summary>
public List<HttpRequestMessage> Requests { get; } = [];
/// <summary>
/// Gets the number of requests that were sent through the handler.
/// </summary>
public int CallCount => _callCount;
/// <summary>
/// Initializes a new instance of the <see cref="StubHttpMessageHandler"/> class.
/// </summary>
/// <param name="responseFactory">The factory that produces the response of a request, given the request and its one based call index.</param>
public StubHttpMessageHandler(Func<HttpRequestMessage, int, HttpResponseMessage> responseFactory)
{
_responseFactory = responseFactory;
}
/// <summary>
/// Sends the provided request, producing its response through the configured factory.
/// </summary>
/// <param name="request">The request to send.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The response produced for the request.</returns>
protected override Task<HttpResponseMessage> 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<HttpResponseMessage>(exception);
}
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzHttpClient"/> class.
/// </summary>
[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<UriFormatException>(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<OperationCanceledException>(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<HttpRequestException>(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<MusicBrainzArtistResponse> 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<MusicBrainzArtistResponse> 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<MusicBrainzReleaseGroupResponse> 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<MusicBrainzReleaseGroupResponse> 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<MusicBrainzReleaseResponse> 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<MusicBrainzReleaseResponse> 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<MusicBrainzRecordingResponse> 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<MusicBrainzRecordingResponse> 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<MusicBrainzRecordingResponse> 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<MusicBrainzRecordingResponse> 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);
}
/// <summary>
/// Creates a <see cref="MusicBrainzHttpClient"/> whose requests are answered by a stub handler, returning the recording JSON by default.
/// </summary>
/// <param name="baseUrl">The base URL of the MusicBrainz web service the client points to.</param>
/// <param name="minimumRequestInterval">The minimum request interval configured for the client.</param>
/// <param name="responseFactory">Optional. The factory that produces the response of a request.</param>
/// <param name="contactEmail">Optional. The contact email configured for the client.</param>
/// <returns>The created client, its stub handler and the underlying HTTP client.</returns>
private (MusicBrainzHttpClient Client, StubHttpMessageHandler Handler, HttpClient HttpClient) CreateClient(
string baseUrl,
TimeSpan minimumRequestInterval,
Func<HttpRequestMessage, int, HttpResponseMessage>? 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);
}
/// <summary>
/// Creates a <see cref="MusicBrainzHttpClient"/> around the provided <see cref="HttpClient"/>.
/// </summary>
/// <param name="httpClient">The underlying HTTP client.</param>
/// <param name="baseUrl">The base URL of the MusicBrainz web service the client points to.</param>
/// <param name="minimumRequestInterval">The minimum request interval configured for the client.</param>
/// <param name="contactEmail">Optional. The contact email configured for the client.</param>
/// <returns>The created client.</returns>
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());
}
/// <summary>
/// Creates an OK response with the provided JSON body.
/// </summary>
/// <param name="json">The JSON body of the response.</param>
/// <returns>The created response.</returns>
private static HttpResponseMessage Json(string json)
{
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzRequestThrottle"/> class.
/// </summary>
[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<OperationCanceledException>(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.");
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzResponseCache"/> class.
/// </summary>
[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);
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzAlbumMetadataProvider"/> class.
/// </summary>
[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<LibraryType> 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<AlbumMetadataDto> 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<AlbumMetadataDto> 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);
}
/// <summary>
/// Creates a <see cref="MusicBrainzAlbumMetadataProvider"/> whose requests are answered by the provided stub handler.
/// </summary>
/// <param name="responseFactory">The factory that produces the response of a request.</param>
/// <returns>The created provider and its stub handler.</returns>
private (MusicBrainzAlbumMetadataProvider Provider, StubHttpMessageHandler Handler) CreateProvider(Func<HttpRequestMessage, int, HttpResponseMessage> 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);
}
/// <summary>
/// Routes a request to the search, release group or release browse JSON, based on the request URI.
/// </summary>
/// <param name="request">The request to route.</param>
/// <param name="searchString">The JSON returned for a search request.</param>
/// <param name="releaseGroupJson">The JSON returned for a release group detail request.</param>
/// <param name="browseJson">The JSON returned for a release browse request.</param>
/// <returns>The JSON that answers the request.</returns>
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;
}
/// <summary>
/// Creates the JSON of a release group response.
/// </summary>
/// <param name="id">The MusicBrainz identifier of the release group.</param>
/// <param name="title">The title of the release group.</param>
/// <param name="primaryType">The primary type of the release group.</param>
/// <param name="firstReleaseDate">The first release date of the release group.</param>
/// <returns>The JSON of the release group response.</returns>
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}}"}""";
}
/// <summary>
/// Creates the JSON of a release response.
/// </summary>
/// <param name="id">The MusicBrainz identifier of the release.</param>
/// <param name="title">The title of the release.</param>
/// <param name="releaseGroupId">The MusicBrainz identifier of the release group.</param>
/// <param name="releaseGroupTitle">The title of the release group.</param>
/// <param name="releaseGroupFirstReleaseDate">The first release date of the release group.</param>
/// <param name="date">The date the release was issued.</param>
/// <param name="status">The status of the release.</param>
/// <param name="releaseDate">The date of the release.</param>
/// <param name="country">The country the release was issued in.</param>
/// <returns>The JSON of the release response.</returns>
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}}" }
}
""";
}
/// <summary>
/// Creates an OK response with the provided JSON body.
/// </summary>
/// <param name="json">The JSON body of the response.</param>
/// <returns>The created response.</returns>
private static HttpResponseMessage Json(string json)
{
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzArtistMetadataProvider"/> class.
/// </summary>
[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<LibraryType> 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<ArtistMetadataDto> 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<ArtistMetadataDto> 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<ArtistMetadataDto> 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);
}
/// <summary>
/// Creates a <see cref="MusicBrainzArtistMetadataProvider"/> whose requests are answered by the provided stub handler.
/// </summary>
/// <param name="responseFactory">The factory that produces the response of a request.</param>
/// <returns>The created provider and its stub handler.</returns>
private (MusicBrainzArtistMetadataProvider Provider, StubHttpMessageHandler Handler) CreateProvider(Func<HttpRequestMessage, int, HttpResponseMessage> 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);
}
/// <summary>
/// Creates the JSON of an artist response.
/// </summary>
/// <param name="name">The name of the artist.</param>
/// <param name="type">The MusicBrainz type of the artist.</param>
/// <param name="id">The MusicBrainz identifier of the artist.</param>
/// <returns>The JSON of the artist response.</returns>
private static string CreateArtistJson(string name, string type, string id)
{
return $$"""{"id":"{{id}}","name":"{{name}}","type":"{{type}}"}""";
}
/// <summary>
/// Creates an OK response with the provided JSON body.
/// </summary>
/// <param name="json">The JSON body of the response.</param>
/// <returns>The created response.</returns>
private static HttpResponseMessage Json(string json)
{
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzPlugin"/> class.
/// </summary>
[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<PluginSettingDescriptorDto> 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<PluginSettingDescriptorDto> 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<IMetadataProvider>(MusicBrainzPlugin.s_pluginId).Count());
Assert.Empty(serviceProvider.GetKeyedServices<IMetadataProvider>(Guid.NewGuid()));
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzTrackMetadataProvider"/> class.
/// </summary>
[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<LibraryType> 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<AudioMetadataDto> 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<AudioMetadataDto> 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);
}
/// <summary>
/// Creates a <see cref="MusicBrainzTrackMetadataProvider"/> whose requests are answered by the provided stub handler.
/// </summary>
/// <param name="responseFactory">The factory that produces the response of a request.</param>
/// <returns>The created provider and its stub handler.</returns>
private (MusicBrainzTrackMetadataProvider Provider, StubHttpMessageHandler Handler) CreateProvider(Func<HttpRequestMessage, int, HttpResponseMessage> 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);
}
/// <summary>
/// Creates the JSON of a release with two tracks, each with its own recording.
/// </summary>
/// <returns>The JSON of the release.</returns>
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" } }
] } ]
}
""";
}
/// <summary>
/// Creates the JSON of a recording response.
/// </summary>
/// <param name="id">The MusicBrainz identifier of the recording.</param>
/// <param name="title">The title of the recording.</param>
/// <returns>The JSON of the recording response.</returns>
private static string RecordingJson(Guid id, string title)
{
return $$"""{"id":"{{id:D}}","title":"{{title}}"}""";
}
/// <summary>
/// Creates an OK response with the provided JSON body.
/// </summary>
/// <param name="json">The JSON body of the response.</param>
/// <returns>The created response.</returns>
private static HttpResponseMessage Json(string json)
{
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
}
}
@@ -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;
/// <summary>
/// Contains unit tests for the <see cref="MusicBrainzSettingsProvider"/> class.
/// </summary>
[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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns((IReadOnlyDictionary<string, string>?)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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string>
{
[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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string>
{
[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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [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<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(new Dictionary<string, string>());
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<Guid>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task GetAsync_WhenCalledConcurrently_ShouldReadTheStoreOnlyOnce()
{
// Arrange
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(new Dictionary<string, string>());
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<Guid>(), Arg.Any<CancellationToken>());
}
[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<OperationCanceledException>(Act);
}
}
/// <summary>
/// Creates the default settings used by the tests of the provider.
/// </summary>
/// <returns>The default settings.</returns>
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));
}
}
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more