diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/DependencyInjection/MusicBrainzServices.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/DependencyInjection/MusicBrainzServices.cs
new file mode 100644
index 00000000..f4364382
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/DependencyInjection/MusicBrainzServices.cs
@@ -0,0 +1,60 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.Contracts.Core.Metadata;
+using Lumina.Plugins.Contracts.Core.Plugins;
+using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
+using Lumina.Plugins.MusicBrainz.Core;
+using Lumina.Plugins.MusicBrainz.Core.Api;
+using Lumina.Plugins.MusicBrainz.Core.Settings;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.DependencyInjection.Extensions;
+using System;
+using System.Net.Http;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.DependencyInjection;
+
+///
+/// Utility class for registering the services of the MusicBrainz metadata provider into the Dependency Injection container.
+///
+internal static class MusicBrainzServices
+{
+ ///
+ /// Registers the services of the MusicBrainz metadata providers into the Dependency Injection container.
+ ///
+ /// The service collection to add the services to.
+ /// The unique identifier of the plugin that provides the metadata.
+ /// Action used to configure the .
+ /// The updated .
+ internal static IServiceCollection AddMusicBrainzMetadataProviders(this IServiceCollection services, Guid pluginId, Action? settingsCallback = null)
+ {
+ ArgumentNullException.ThrowIfNull(services);
+
+ // Build the runtime settings provider per scope, overlaying the settings persisted by the host over the defaults and the optional callback.
+ services.TryAddScoped(serviceProvider =>
+ {
+ MusicBrainzSettingsDto defaults = new();
+ settingsCallback?.Invoke(defaults);
+
+ IPluginSettingsStore? settingsStore = serviceProvider.GetService();
+ return new MusicBrainzSettingsProvider(settingsStore, pluginId, defaults);
+ });
+
+ // The throttle must be process-wide, because the MusicBrainz web service enforces its request policy across all callers, not per scope.
+ services.TryAddSingleton();
+
+ // The response cache is process-wide, so that an entity shared by many items, like a release shared by all its tracks, is fetched only once.
+ services.TryAddSingleton();
+
+ // Redirects are not followed, so the configurable base URL cannot be used to reach an internal address through a redirect from a mirror.
+ services.AddHttpClient()
+ .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
+
+ // Register the metadata providers as keyed by pluginId transient services, so they can be resolved specifically among other IMetadataProvider implementations.
+ // A single plugin exposes one provider per entity type, because the metadata contract is typed to a single lookup and metadata pair.
+ services.AddKeyedTransient(pluginId);
+ services.AddKeyedTransient(pluginId);
+ services.AddKeyedTransient(pluginId);
+
+ return services;
+ }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAliasResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAliasResponse.cs
new file mode 100644
index 00000000..80aa0157
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAliasResponse.cs
@@ -0,0 +1,59 @@
+#region ========================================================================= USING =====================================================================================
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for an alias of a MusicBrainz entity.
+///
+internal sealed record MusicBrainzAliasResponse
+{
+ ///
+ /// Gets the name of the alias.
+ ///
+ [JsonPropertyName("name")]
+ public string? Name { get; init; }
+
+ ///
+ /// Gets the sort name of the alias.
+ ///
+ [JsonPropertyName("sort-name")]
+ public string? SortName { get; init; }
+
+ ///
+ /// Gets the type of the alias.
+ ///
+ [JsonPropertyName("type")]
+ public string? Type { get; init; }
+
+ ///
+ /// Gets the locale the alias is used in.
+ ///
+ [JsonPropertyName("locale")]
+ public string? Locale { get; init; }
+
+ ///
+ /// Gets a value indicating whether this is the primary alias.
+ ///
+ [JsonPropertyName("primary")]
+ public bool? IsPrimary { get; init; }
+
+ ///
+ /// Gets the begin date of the alias.
+ ///
+ [JsonPropertyName("begin")]
+ public string? Begin { get; init; }
+
+ ///
+ /// Gets the end date of the alias.
+ ///
+ [JsonPropertyName("end")]
+ public string? End { get; init; }
+
+ ///
+ /// Gets a value indicating whether the alias has ended.
+ ///
+ [JsonPropertyName("ended")]
+ public bool? IsEnded { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAreaResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAreaResponse.cs
new file mode 100644
index 00000000..1049e58a
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzAreaResponse.cs
@@ -0,0 +1,54 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for an area from the MusicBrainz API.
+///
+internal sealed record MusicBrainzAreaResponse
+{
+ ///
+ /// Gets the MusicBrainz identifier of the area.
+ ///
+ [JsonPropertyName("id")]
+ public string? Id { get; init; }
+
+ ///
+ /// Gets the name of the area.
+ ///
+ [JsonPropertyName("name")]
+ public string? Name { get; init; }
+
+ ///
+ /// Gets the sort name of the area.
+ ///
+ [JsonPropertyName("sort-name")]
+ public string? SortName { get; init; }
+
+ ///
+ /// Gets the disambiguation comment of the area.
+ ///
+ [JsonPropertyName("disambiguation")]
+ public string? Disambiguation { get; init; }
+
+ ///
+ /// Gets the MusicBrainz type of the area.
+ ///
+ [JsonPropertyName("type")]
+ public string? Type { get; init; }
+
+ ///
+ /// Gets the ISO 3166-1 codes of the area.
+ ///
+ [JsonPropertyName("iso-3166-1-codes")]
+ public List Iso3166Part1Codes { get; init; } = [];
+
+ ///
+ /// Gets the ISO 3166-2 codes of the area.
+ ///
+ [JsonPropertyName("iso-3166-2-codes")]
+ public List Iso3166Part2Codes { get; init; } = [];
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponse.cs
new file mode 100644
index 00000000..b659ba13
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponse.cs
@@ -0,0 +1,29 @@
+#region ========================================================================= USING =====================================================================================
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for a single credit in the artist credit of a MusicBrainz entity.
+///
+internal sealed record MusicBrainzArtistCreditResponse
+{
+ ///
+ /// Gets the credited name of the artist.
+ ///
+ [JsonPropertyName("name")]
+ public string? Name { get; init; }
+
+ ///
+ /// Gets the join phrase that follows the credit.
+ ///
+ [JsonPropertyName("joinphrase")]
+ public string? JoinPhrase { get; init; }
+
+ ///
+ /// Gets the artist the credit refers to.
+ ///
+ [JsonPropertyName("artist")]
+ public MusicBrainzArtistResponse? Artist { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistResponse.cs
new file mode 100644
index 00000000..bfedacfd
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistResponse.cs
@@ -0,0 +1,120 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for an artist from the MusicBrainz API.
+///
+internal sealed record MusicBrainzArtistResponse
+{
+ ///
+ /// Gets the MusicBrainz identifier of the artist.
+ ///
+ [JsonPropertyName("id")]
+ public string? Id { get; init; }
+
+ ///
+ /// Gets the name of the artist.
+ ///
+ [JsonPropertyName("name")]
+ public string? Name { get; init; }
+
+ ///
+ /// Gets the sort name of the artist.
+ ///
+ [JsonPropertyName("sort-name")]
+ public string? SortName { get; init; }
+
+ ///
+ /// Gets the disambiguation comment of the artist.
+ ///
+ [JsonPropertyName("disambiguation")]
+ public string? Disambiguation { get; init; }
+
+ ///
+ /// Gets the MusicBrainz type of the artist.
+ ///
+ [JsonPropertyName("type")]
+ public string? Type { get; init; }
+
+ ///
+ /// Gets the gender of the artist.
+ ///
+ [JsonPropertyName("gender")]
+ public string? Gender { get; init; }
+
+ ///
+ /// Gets the ISO 3166-1 alpha-2 code of the country of the artist.
+ ///
+ [JsonPropertyName("country")]
+ public string? Country { get; init; }
+
+ ///
+ /// Gets the area the artist is primarily identified with.
+ ///
+ [JsonPropertyName("area")]
+ public MusicBrainzAreaResponse? Area { get; init; }
+
+ ///
+ /// Gets the area the artist began in.
+ ///
+ [JsonPropertyName("begin-area")]
+ public MusicBrainzAreaResponse? BeginArea { get; init; }
+
+ ///
+ /// Gets the area the artist ended in.
+ ///
+ [JsonPropertyName("end-area")]
+ public MusicBrainzAreaResponse? EndArea { get; init; }
+
+ ///
+ /// Gets the life span of the artist.
+ ///
+ [JsonPropertyName("life-span")]
+ public MusicBrainzLifeSpanResponse? LifeSpan { get; init; }
+
+ ///
+ /// Gets the ISNI codes of the artist.
+ ///
+ [JsonPropertyName("isnis")]
+ public List Isnis { get; init; } = [];
+
+ ///
+ /// Gets the IPI codes of the artist.
+ ///
+ [JsonPropertyName("ipis")]
+ public List Ipis { get; init; } = [];
+
+ ///
+ /// Gets the alternative names of the artist.
+ ///
+ [JsonPropertyName("aliases")]
+ public List Aliases { get; init; } = [];
+
+ ///
+ /// Gets the tags of the artist.
+ ///
+ [JsonPropertyName("tags")]
+ public List Tags { get; init; } = [];
+
+ ///
+ /// Gets the genres of the artist.
+ ///
+ [JsonPropertyName("genres")]
+ public List Genres { get; init; } = [];
+
+ ///
+ /// Gets the relationships of the artist to other entities.
+ ///
+ [JsonPropertyName("relations")]
+ public List Relations { get; init; } = [];
+
+ ///
+ /// Gets the aggregated rating of the artist.
+ ///
+ [JsonPropertyName("rating")]
+ public MusicBrainzRatingResponse? Rating { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponse.cs
new file mode 100644
index 00000000..21abdaa3
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponse.cs
@@ -0,0 +1,30 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for an artist search from the MusicBrainz API.
+///
+internal sealed record MusicBrainzArtistSearchResponse
+{
+ ///
+ /// Gets the total number of matching artists.
+ ///
+ [JsonPropertyName("count")]
+ public int Count { get; init; }
+
+ ///
+ /// Gets the offset of the returned artists.
+ ///
+ [JsonPropertyName("offset")]
+ public int Offset { get; init; }
+
+ ///
+ /// Gets the matching artists.
+ ///
+ [JsonPropertyName("artists")]
+ public List Artists { get; init; } = [];
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponse.cs
new file mode 100644
index 00000000..3a45cd2a
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponse.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for the label information of a MusicBrainz release.
+///
+internal sealed record MusicBrainzLabelInfoResponse
+{
+ ///
+ /// Gets the catalog number assigned by the label.
+ ///
+ [JsonPropertyName("catalog-number")]
+ public string? CatalogNumber { get; init; }
+
+ ///
+ /// Gets the label that issued the release.
+ ///
+ [JsonPropertyName("label")]
+ public MusicBrainzLabelResponse? Label { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelResponse.cs
new file mode 100644
index 00000000..2a9c49e8
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLabelResponse.cs
@@ -0,0 +1,35 @@
+#region ========================================================================= USING =====================================================================================
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for a label from the MusicBrainz API.
+///
+internal sealed record MusicBrainzLabelResponse
+{
+ ///
+ /// Gets the MusicBrainz identifier of the label.
+ ///
+ [JsonPropertyName("id")]
+ public string? Id { get; init; }
+
+ ///
+ /// Gets the name of the label.
+ ///
+ [JsonPropertyName("name")]
+ public string? Name { get; init; }
+
+ ///
+ /// Gets the disambiguation comment of the label.
+ ///
+ [JsonPropertyName("disambiguation")]
+ public string? Disambiguation { get; init; }
+
+ ///
+ /// Gets the label code of the label.
+ ///
+ [JsonPropertyName("label-code")]
+ public int? LabelCode { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponse.cs
new file mode 100644
index 00000000..1a8ef2c5
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponse.cs
@@ -0,0 +1,29 @@
+#region ========================================================================= USING =====================================================================================
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for the life span of a MusicBrainz artist, label, or area.
+///
+internal sealed record MusicBrainzLifeSpanResponse
+{
+ ///
+ /// Gets the begin date of the life span.
+ ///
+ [JsonPropertyName("begin")]
+ public string? Begin { get; init; }
+
+ ///
+ /// Gets the end date of the life span.
+ ///
+ [JsonPropertyName("end")]
+ public string? End { get; init; }
+
+ ///
+ /// Gets a value indicating whether the life span has ended.
+ ///
+ [JsonPropertyName("ended")]
+ public bool? IsEnded { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzMediumResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzMediumResponse.cs
new file mode 100644
index 00000000..e7e2f675
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzMediumResponse.cs
@@ -0,0 +1,42 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for a medium of a MusicBrainz release.
+///
+internal sealed record MusicBrainzMediumResponse
+{
+ ///
+ /// Gets the position of the medium within its release.
+ ///
+ [JsonPropertyName("position")]
+ public int Position { get; init; }
+
+ ///
+ /// Gets the title of the medium.
+ ///
+ [JsonPropertyName("title")]
+ public string? Title { get; init; }
+
+ ///
+ /// Gets the format of the medium (e.g., CD, Vinyl, Digital Media).
+ ///
+ [JsonPropertyName("format")]
+ public string? Format { get; init; }
+
+ ///
+ /// Gets the number of tracks of the medium.
+ ///
+ [JsonPropertyName("track-count")]
+ public int TrackCount { get; init; }
+
+ ///
+ /// Gets the tracks of the medium. The tracks are only returned when the recordings are included in the request.
+ ///
+ [JsonPropertyName("tracks")]
+ public List Tracks { get; init; } = [];
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRatingResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRatingResponse.cs
new file mode 100644
index 00000000..f0983b8a
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRatingResponse.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for the aggregated rating of a MusicBrainz entity.
+///
+internal sealed record MusicBrainzRatingResponse
+{
+ ///
+ /// Gets the average rating value.
+ ///
+ [JsonPropertyName("value")]
+ public decimal? Value { get; init; }
+
+ ///
+ /// Gets the number of votes that contributed to the rating.
+ ///
+ [JsonPropertyName("votes-count")]
+ public int? VotesCount { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponse.cs
new file mode 100644
index 00000000..a1dbc913
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponse.cs
@@ -0,0 +1,18 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for the recordings returned by an ISRC lookup from the MusicBrainz API.
+///
+internal sealed record MusicBrainzRecordingListResponse
+{
+ ///
+ /// Gets the recordings that carry the looked up ISRC.
+ ///
+ [JsonPropertyName("recordings")]
+ public List Recordings { get; init; } = [];
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingResponse.cs
new file mode 100644
index 00000000..9b773f15
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingResponse.cs
@@ -0,0 +1,90 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for a recording from the MusicBrainz API.
+///
+internal sealed record MusicBrainzRecordingResponse
+{
+ ///
+ /// Gets the MusicBrainz identifier of the recording.
+ ///
+ [JsonPropertyName("id")]
+ public string? Id { get; init; }
+
+ ///
+ /// Gets the title of the recording.
+ ///
+ [JsonPropertyName("title")]
+ public string? Title { get; init; }
+
+ ///
+ /// Gets the disambiguation comment of the recording.
+ ///
+ [JsonPropertyName("disambiguation")]
+ public string? Disambiguation { get; init; }
+
+ ///
+ /// Gets the length of the recording in milliseconds.
+ ///
+ [JsonPropertyName("length")]
+ public long? Length { get; init; }
+
+ ///
+ /// Gets a value indicating whether the recording is a video recording.
+ ///
+ [JsonPropertyName("video")]
+ public bool? IsVideo { get; init; }
+
+ ///
+ /// Gets the date the recording was first released.
+ ///
+ [JsonPropertyName("first-release-date")]
+ public string? FirstReleaseDate { get; init; }
+
+ ///
+ /// Gets the artist credit of the recording.
+ ///
+ [JsonPropertyName("artist-credit")]
+ public List ArtistCredit { get; init; } = [];
+
+ ///
+ /// Gets the ISRC (International Standard Recording Code) of the recording.
+ ///
+ [JsonPropertyName("isrcs")]
+ public List Isrcs { get; init; } = [];
+
+ ///
+ /// Gets the releases the recording appears on.
+ ///
+ [JsonPropertyName("releases")]
+ public List Releases { get; init; } = [];
+
+ ///
+ /// Gets the tags of the recording.
+ ///
+ [JsonPropertyName("tags")]
+ public List Tags { get; init; } = [];
+
+ ///
+ /// Gets the genres of the recording.
+ ///
+ [JsonPropertyName("genres")]
+ public List Genres { get; init; } = [];
+
+ ///
+ /// Gets the relationships of the recording to other entities (e.g., its work, and its performers).
+ ///
+ [JsonPropertyName("relations")]
+ public List Relations { get; init; } = [];
+
+ ///
+ /// Gets the aggregated rating of the recording.
+ ///
+ [JsonPropertyName("rating")]
+ public MusicBrainzRatingResponse? Rating { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponse.cs
new file mode 100644
index 00000000..6e9fe611
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponse.cs
@@ -0,0 +1,30 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for a recording search from the MusicBrainz API.
+///
+internal sealed record MusicBrainzRecordingSearchResponse
+{
+ ///
+ /// Gets the total number of matching recordings.
+ ///
+ [JsonPropertyName("count")]
+ public int Count { get; init; }
+
+ ///
+ /// Gets the offset of the returned recordings.
+ ///
+ [JsonPropertyName("offset")]
+ public int Offset { get; init; }
+
+ ///
+ /// Gets the matching recordings.
+ ///
+ [JsonPropertyName("recordings")]
+ public List Recordings { get; init; } = [];
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRelationResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRelationResponse.cs
new file mode 100644
index 00000000..269fcc50
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzRelationResponse.cs
@@ -0,0 +1,60 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for a relationship between a MusicBrainz entity and another entity.
+///
+internal sealed record MusicBrainzRelationResponse
+{
+ ///
+ /// Gets the type of the relationship (e.g., producer, composer, member of band).
+ ///
+ [JsonPropertyName("type")]
+ public string? Type { get; init; }
+
+ ///
+ /// Gets the MusicBrainz identifier of the type of the relationship.
+ ///
+ [JsonPropertyName("type-id")]
+ public string? TypeId { get; init; }
+
+ ///
+ /// Gets the direction of the relationship.
+ ///
+ [JsonPropertyName("direction")]
+ public string? Direction { get; init; }
+
+ ///
+ /// Gets the type of the entity the relationship targets.
+ ///
+ [JsonPropertyName("target-type")]
+ public string? TargetType { get; init; }
+
+ ///
+ /// Gets the artist the relationship targets, when the target is an artist.
+ ///
+ [JsonPropertyName("artist")]
+ public MusicBrainzArtistResponse? Artist { get; init; }
+
+ ///
+ /// Gets the work the relationship targets, when the target is a work.
+ ///
+ [JsonPropertyName("work")]
+ public MusicBrainzWorkResponse? Work { get; init; }
+
+ ///
+ /// Gets the URL the relationship targets, when the target is a URL.
+ ///
+ [JsonPropertyName("url")]
+ public MusicBrainzUrlResponse? Url { get; init; }
+
+ ///
+ /// Gets the attributes of the relationship (e.g., the instrument that was performed).
+ ///
+ [JsonPropertyName("attributes")]
+ public List Attributes { get; init; } = [];
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponse.cs
new file mode 100644
index 00000000..9735cb3a
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponse.cs
@@ -0,0 +1,30 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for the result of browsing the releases linked to another MusicBrainz entity.
+///
+internal sealed record MusicBrainzReleaseBrowseResponse
+{
+ ///
+ /// Gets the releases returned by the browse request.
+ ///
+ [JsonPropertyName("releases")]
+ public List Releases { get; init; } = [];
+
+ ///
+ /// Gets the total number of releases linked to the browsed entity.
+ ///
+ [JsonPropertyName("release-count")]
+ public int ReleaseCount { get; init; }
+
+ ///
+ /// Gets the offset of the returned releases.
+ ///
+ [JsonPropertyName("release-offset")]
+ public int ReleaseOffset { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponse.cs
new file mode 100644
index 00000000..fd4722c7
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponse.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for a release event of a MusicBrainz release.
+///
+internal sealed record MusicBrainzReleaseEventResponse
+{
+ ///
+ /// Gets the date of the release event.
+ ///
+ [JsonPropertyName("date")]
+ public string? Date { get; init; }
+
+ ///
+ /// Gets the area of the release event.
+ ///
+ [JsonPropertyName("area")]
+ public MusicBrainzAreaResponse? Area { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponse.cs
new file mode 100644
index 00000000..50e8e909
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponse.cs
@@ -0,0 +1,78 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for a release group from the MusicBrainz API.
+///
+internal sealed record MusicBrainzReleaseGroupResponse
+{
+ ///
+ /// Gets the MusicBrainz identifier of the release group.
+ ///
+ [JsonPropertyName("id")]
+ public string? Id { get; init; }
+
+ ///
+ /// Gets the title of the release group.
+ ///
+ [JsonPropertyName("title")]
+ public string? Title { get; init; }
+
+ ///
+ /// Gets the disambiguation comment of the release group.
+ ///
+ [JsonPropertyName("disambiguation")]
+ public string? Disambiguation { get; init; }
+
+ ///
+ /// Gets the primary type of the release group.
+ ///
+ [JsonPropertyName("primary-type")]
+ public string? PrimaryType { get; init; }
+
+ ///
+ /// Gets the secondary types of the release group.
+ ///
+ [JsonPropertyName("secondary-types")]
+ public List SecondaryTypes { get; init; } = [];
+
+ ///
+ /// Gets the date the release group was first released.
+ ///
+ [JsonPropertyName("first-release-date")]
+ public string? FirstReleaseDate { get; init; }
+
+ ///
+ /// Gets the artist credit of the release group.
+ ///
+ [JsonPropertyName("artist-credit")]
+ public List ArtistCredit { get; init; } = [];
+
+ ///
+ /// Gets the releases of the release group.
+ ///
+ [JsonPropertyName("releases")]
+ public List Releases { get; init; } = [];
+
+ ///
+ /// Gets the tags of the release group.
+ ///
+ [JsonPropertyName("tags")]
+ public List Tags { get; init; } = [];
+
+ ///
+ /// Gets the genres of the release group.
+ ///
+ [JsonPropertyName("genres")]
+ public List Genres { get; init; } = [];
+
+ ///
+ /// Gets the aggregated rating of the release group.
+ ///
+ [JsonPropertyName("rating")]
+ public MusicBrainzRatingResponse? Rating { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponse.cs
new file mode 100644
index 00000000..eafa8cf9
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponse.cs
@@ -0,0 +1,30 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for a release group search from the MusicBrainz API.
+///
+internal sealed record MusicBrainzReleaseGroupSearchResponse
+{
+ ///
+ /// Gets the total number of matching release groups.
+ ///
+ [JsonPropertyName("count")]
+ public int Count { get; init; }
+
+ ///
+ /// Gets the offset of the returned release groups.
+ ///
+ [JsonPropertyName("offset")]
+ public int Offset { get; init; }
+
+ ///
+ /// Gets the matching release groups.
+ ///
+ [JsonPropertyName("release-groups")]
+ public List ReleaseGroups { get; init; } = [];
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseResponse.cs
new file mode 100644
index 00000000..529b7373
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzReleaseResponse.cs
@@ -0,0 +1,120 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for a release from the MusicBrainz API.
+///
+internal sealed record MusicBrainzReleaseResponse
+{
+ ///
+ /// Gets the MusicBrainz identifier of the release.
+ ///
+ [JsonPropertyName("id")]
+ public string? Id { get; init; }
+
+ ///
+ /// Gets the title of the release.
+ ///
+ [JsonPropertyName("title")]
+ public string? Title { get; init; }
+
+ ///
+ /// Gets the disambiguation comment of the release.
+ ///
+ [JsonPropertyName("disambiguation")]
+ public string? Disambiguation { get; init; }
+
+ ///
+ /// Gets the status of the release (e.g., Official, Bootleg).
+ ///
+ [JsonPropertyName("status")]
+ public string? Status { get; init; }
+
+ ///
+ /// Gets the date the release was issued.
+ ///
+ [JsonPropertyName("date")]
+ public string? Date { get; init; }
+
+ ///
+ /// Gets the ISO 3166-1 alpha-2 code of the country the release was issued in.
+ ///
+ [JsonPropertyName("country")]
+ public string? Country { get; init; }
+
+ ///
+ /// Gets the release events of the release.
+ ///
+ [JsonPropertyName("release-events")]
+ public List ReleaseEvents { get; init; } = [];
+
+ ///
+ /// Gets the barcode of the release.
+ ///
+ [JsonPropertyName("barcode")]
+ public string? Barcode { get; init; }
+
+ ///
+ /// Gets the outermost packaging of the release.
+ ///
+ [JsonPropertyName("packaging")]
+ public string? Packaging { get; init; }
+
+ ///
+ /// Gets the language and script of the titles of the release.
+ ///
+ [JsonPropertyName("text-representation")]
+ public MusicBrainzTextRepresentationResponse? TextRepresentation { get; init; }
+
+ ///
+ /// Gets the artist credit of the release.
+ ///
+ [JsonPropertyName("artist-credit")]
+ public List ArtistCredit { get; init; } = [];
+
+ ///
+ /// Gets the release group the release belongs to.
+ ///
+ [JsonPropertyName("release-group")]
+ public MusicBrainzReleaseGroupResponse? ReleaseGroup { get; init; }
+
+ ///
+ /// Gets the label information of the release.
+ ///
+ [JsonPropertyName("label-info")]
+ public List LabelInfo { get; init; } = [];
+
+ ///
+ /// Gets the media of the release.
+ ///
+ [JsonPropertyName("media")]
+ public List Media { get; init; } = [];
+
+ ///
+ /// Gets the ASIN (Amazon Standard Identification Number) of the release.
+ ///
+ [JsonPropertyName("asin")]
+ public string? Asin { get; init; }
+
+ ///
+ /// Gets the tags of the release.
+ ///
+ [JsonPropertyName("tags")]
+ public List Tags { get; init; } = [];
+
+ ///
+ /// Gets the genres of the release.
+ ///
+ [JsonPropertyName("genres")]
+ public List Genres { get; init; } = [];
+
+ ///
+ /// Gets the relationships of the release to other entities (e.g., its producers and engineers).
+ ///
+ [JsonPropertyName("relations")]
+ public List Relations { get; init; } = [];
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTagResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTagResponse.cs
new file mode 100644
index 00000000..a14387ba
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTagResponse.cs
@@ -0,0 +1,35 @@
+#region ========================================================================= USING =====================================================================================
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for a tag or a genre of a MusicBrainz entity.
+///
+internal sealed record MusicBrainzTagResponse
+{
+ ///
+ /// Gets the MusicBrainz identifier of the genre, when the tag is a genre.
+ ///
+ [JsonPropertyName("id")]
+ public string? Id { get; init; }
+
+ ///
+ /// Gets the name of the tag.
+ ///
+ [JsonPropertyName("name")]
+ public string? Name { get; init; }
+
+ ///
+ /// Gets the disambiguation comment of the genre, when the tag is a genre.
+ ///
+ [JsonPropertyName("disambiguation")]
+ public string? Disambiguation { get; init; }
+
+ ///
+ /// Gets the number of votes the tag received.
+ ///
+ [JsonPropertyName("count")]
+ public int Count { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponse.cs
new file mode 100644
index 00000000..ab04f364
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponse.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for the language and script of the titles of a MusicBrainz release.
+///
+internal sealed record MusicBrainzTextRepresentationResponse
+{
+ ///
+ /// Gets the ISO 639-3 language code of the release.
+ ///
+ [JsonPropertyName("language")]
+ public string? Language { get; init; }
+
+ ///
+ /// Gets the ISO 15924 script code of the release.
+ ///
+ [JsonPropertyName("script")]
+ public string? Script { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTrackResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTrackResponse.cs
new file mode 100644
index 00000000..0015672f
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzTrackResponse.cs
@@ -0,0 +1,47 @@
+#region ========================================================================= USING =====================================================================================
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for a track of a medium of a MusicBrainz release, including the recording it is a performance of.
+///
+internal sealed record MusicBrainzTrackResponse
+{
+ ///
+ /// Gets the MusicBrainz identifier of the track.
+ ///
+ [JsonPropertyName("id")]
+ public string? Id { get; init; }
+
+ ///
+ /// Gets the track number, as displayed on the medium (for example, "1" or "A1").
+ ///
+ [JsonPropertyName("number")]
+ public string? Number { get; init; }
+
+ ///
+ /// Gets the position of the track within its medium.
+ ///
+ [JsonPropertyName("position")]
+ public int Position { get; init; }
+
+ ///
+ /// Gets the title of the track.
+ ///
+ [JsonPropertyName("title")]
+ public string? Title { get; init; }
+
+ ///
+ /// Gets the length of the track in milliseconds.
+ ///
+ [JsonPropertyName("length")]
+ public long? Length { get; init; }
+
+ ///
+ /// Gets the recording the track is a performance of.
+ ///
+ [JsonPropertyName("recording")]
+ public MusicBrainzRecordingResponse? Recording { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzUrlResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzUrlResponse.cs
new file mode 100644
index 00000000..f7d4e06c
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzUrlResponse.cs
@@ -0,0 +1,23 @@
+#region ========================================================================= USING =====================================================================================
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for a URL from the MusicBrainz API.
+///
+internal sealed record MusicBrainzUrlResponse
+{
+ ///
+ /// Gets the MusicBrainz identifier of the URL.
+ ///
+ [JsonPropertyName("id")]
+ public string? Id { get; init; }
+
+ ///
+ /// Gets the resource the URL points to.
+ ///
+ [JsonPropertyName("resource")]
+ public string? Resource { get; init; }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzWorkResponse.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzWorkResponse.cs
new file mode 100644
index 00000000..09c43be2
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/Contracts/Responses/MusicBrainzWorkResponse.cs
@@ -0,0 +1,66 @@
+#region ========================================================================= USING =====================================================================================
+using System.Collections.Generic;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+
+///
+/// Represents a response for a work from the MusicBrainz API.
+///
+internal sealed record MusicBrainzWorkResponse
+{
+ ///
+ /// Gets the MusicBrainz identifier of the work.
+ ///
+ [JsonPropertyName("id")]
+ public string? Id { get; init; }
+
+ ///
+ /// Gets the title of the work.
+ ///
+ [JsonPropertyName("title")]
+ public string? Title { get; init; }
+
+ ///
+ /// Gets the MusicBrainz type of the work.
+ ///
+ [JsonPropertyName("type")]
+ public string? Type { get; init; }
+
+ ///
+ /// Gets the disambiguation comment of the work.
+ ///
+ [JsonPropertyName("disambiguation")]
+ public string? Disambiguation { get; init; }
+
+ ///
+ /// Gets the languages of the work.
+ ///
+ [JsonPropertyName("languages")]
+ public List Languages { get; init; } = [];
+
+ ///
+ /// Gets the ISWC (International Standard Musical Work Code) of the work.
+ ///
+ [JsonPropertyName("iswcs")]
+ public List Iswcs { get; init; } = [];
+
+ ///
+ /// Gets the relationships of the work to other entities (e.g., its composers and lyricists).
+ ///
+ [JsonPropertyName("relations")]
+ public List Relations { get; init; } = [];
+
+ ///
+ /// Gets the tags of the work.
+ ///
+ [JsonPropertyName("tags")]
+ public List Tags { get; init; } = [];
+
+ ///
+ /// Gets the genres of the work.
+ ///
+ [JsonPropertyName("genres")]
+ public List Genres { get; init; } = [];
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/Models/DTO/Settings/MusicBrainzSettingsDto.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/DTO/Settings/MusicBrainzSettingsDto.cs
new file mode 100644
index 00000000..2c97fbab
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Common/Models/DTO/Settings/MusicBrainzSettingsDto.cs
@@ -0,0 +1,49 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
+
+///
+/// Data transfer object for the settings that configure the MusicBrainz metadata plugin.
+///
+internal sealed class MusicBrainzSettingsDto
+{
+ ///
+ /// Gets or sets the base URL of the MusicBrainz web service the requests are sent to.
+ /// Defaults to the public MusicBrainz web service, and can point to a self hosted mirror instead.
+ ///
+ public string BaseUrl { get; set; } = "https://musicbrainz.org/ws/2/";
+
+ ///
+ /// Gets or sets a value indicating whether the base URL is allowed to point at a private or local host, for a self hosted mirror on a local
+ /// network. Defaults to , so that a misconfigured base URL cannot silently reach a local service.
+ ///
+ public bool DoesAllowPrivateBaseUrl { get; set; }
+
+ ///
+ /// Gets or sets the user agent sent with every request to the MusicBrainz API.
+ ///
+ public string UserAgent { get; set; } = "Lumina-MusicBrainz/1.0";
+
+ ///
+ /// Gets or sets the contact email sent with every request to the MusicBrainz API.
+ ///
+ public string? ContactEmail { get; set; }
+
+ ///
+ /// Gets or sets the maximum number of results returned by a single search.
+ ///
+ public int SearchResultLimit { get; set; } = 10;
+
+ ///
+ /// Gets or sets the maximum number of releases fetched for a single release group.
+ ///
+ public int ReleaseLookupLimit { get; set; } = 25;
+
+ ///
+ /// Gets or sets the minimum interval between consecutive requests to the MusicBrainz API.
+ /// MusicBrainz requires client applications to make no more than one request per second.
+ ///
+ public TimeSpan MinimumRequestInterval { get; set; } = TimeSpan.FromSeconds(1.0);
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzHttpClient.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzHttpClient.cs
new file mode 100644
index 00000000..70407049
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzHttpClient.cs
@@ -0,0 +1,336 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
+using Lumina.Plugins.MusicBrainz.Core.Settings;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Core.Api;
+
+///
+/// HTTP client that calls the MusicBrainz web service and deserializes its JSON responses into typed response models.
+///
+internal sealed class MusicBrainzHttpClient
+{
+ private readonly HttpClient _httpClient;
+ private readonly MusicBrainzSettingsProvider _settingsProvider;
+ private readonly MusicBrainzRequestThrottle _requestThrottle;
+ private readonly MusicBrainzResponseCache _responseCache;
+
+ private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web)
+ {
+ NumberHandling = JsonNumberHandling.AllowReadingFromString
+ };
+
+ // Transient failures and rate limiting are retried with an exponential backoff, so a single hiccup does not mark an item as failed to enrich.
+ private const int MAXIMUM_ATTEMPT_COUNT = 4;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The used to send requests to the MusicBrainz web service.
+ /// The provider of the settings that configure the MusicBrainz web service requests.
+ /// The process-wide throttle that spaces out the requests sent to the MusicBrainz web service.
+ /// The process-wide cache that avoids fetching the same entity more than once during a run.
+ public MusicBrainzHttpClient(HttpClient httpClient, MusicBrainzSettingsProvider settingsProvider, MusicBrainzRequestThrottle requestThrottle, MusicBrainzResponseCache responseCache)
+ {
+ _httpClient = httpClient;
+ _settingsProvider = settingsProvider;
+ _requestThrottle = requestThrottle;
+ _responseCache = responseCache;
+ }
+
+ ///
+ /// Looks up the artist identified by .
+ ///
+ /// The MusicBrainz identifier of the artist.
+ /// Cancellation token that can be used to stop the execution.
+ /// The artist, or when no artist was found.
+ public Task GetArtistAsync(Guid musicBrainzArtistId, CancellationToken cancellationToken)
+ {
+ return GetJsonOrNullAsync(
+ $"artist/{musicBrainzArtistId:D}?inc=aliases+tags+genres+url-rels+artist-rels+ratings&fmt=json", cancellationToken);
+ }
+
+ ///
+ /// Searches MusicBrainz for artists matching the provided query.
+ ///
+ /// The search query.
+ /// The maximum number of results to return.
+ /// Cancellation token that can be used to stop the execution.
+ /// The list of matching artists.
+ public async Task> SearchArtistsAsync(string query, int limit, CancellationToken cancellationToken)
+ {
+ MusicBrainzArtistSearchResponse? response = await GetJsonOrNullAsync(
+ $"artist?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
+ cancellationToken).ConfigureAwait(false);
+ return response?.Artists ?? [];
+ }
+
+ ///
+ /// Looks up the release group identified by .
+ ///
+ /// The MusicBrainz identifier of the release group.
+ /// Cancellation token that can be used to stop the execution.
+ /// The release group, or when no release group was found.
+ public Task GetReleaseGroupAsync(Guid musicBrainzReleaseGroupId, CancellationToken cancellationToken)
+ {
+ return GetJsonOrNullAsync(
+ $"release-group/{musicBrainzReleaseGroupId:D}?inc=artist-credits+tags+genres+ratings&fmt=json", cancellationToken);
+ }
+
+ ///
+ /// Searches MusicBrainz for release groups matching the provided query.
+ ///
+ /// The search query.
+ /// The maximum number of results to return.
+ /// Cancellation token that can be used to stop the execution.
+ /// The list of matching release groups.
+ public async Task> SearchReleaseGroupsAsync(string query, int limit, CancellationToken cancellationToken)
+ {
+ MusicBrainzReleaseGroupSearchResponse? response = await GetJsonOrNullAsync(
+ $"release-group?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
+ cancellationToken).ConfigureAwait(false);
+ return response?.ReleaseGroups ?? [];
+ }
+
+ ///
+ /// Looks up the release identified by .
+ ///
+ /// The MusicBrainz identifier of the release.
+ /// Cancellation token that can be used to stop the execution.
+ /// The release, or when no release was found.
+ public Task GetReleaseAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken)
+ {
+ return GetJsonOrNullAsync(
+ $"release/{musicBrainzReleaseId:D}?inc=artist-credits+labels+release-groups+media+tags+genres+artist-rels&fmt=json", cancellationToken);
+ }
+
+ ///
+ /// Browses the releases that belong to the release group identified by .
+ ///
+ /// The MusicBrainz identifier of the release group.
+ /// The maximum number of releases to return.
+ /// Cancellation token that can be used to stop the execution.
+ /// The list of releases of the release group.
+ public async Task> BrowseReleasesByReleaseGroupAsync(Guid musicBrainzReleaseGroupId, int limit, CancellationToken cancellationToken)
+ {
+ MusicBrainzReleaseBrowseResponse? response = await GetJsonOrNullAsync(
+ $"release?release-group={musicBrainzReleaseGroupId:D}&inc=artist-credits+labels+media&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
+ cancellationToken).ConfigureAwait(false);
+ return response?.Releases ?? [];
+ }
+
+ ///
+ /// Looks up the recording identified by .
+ ///
+ /// The MusicBrainz identifier of the recording.
+ /// Cancellation token that can be used to stop the execution.
+ /// The recording, or when no recording was found.
+ public Task GetRecordingAsync(Guid musicBrainzRecordingId, CancellationToken cancellationToken)
+ {
+ return GetJsonOrNullAsync(
+ $"recording/{musicBrainzRecordingId:D}?inc=artist-credits+isrcs+releases+tags+genres+work-rels+artist-rels+ratings&fmt=json", cancellationToken);
+ }
+
+ ///
+ /// Searches MusicBrainz for recordings matching the provided query.
+ ///
+ /// The search query.
+ /// The maximum number of results to return.
+ /// Cancellation token that can be used to stop the execution.
+ /// The list of matching recordings.
+ public async Task> SearchRecordingsAsync(string query, int limit, CancellationToken cancellationToken)
+ {
+ MusicBrainzRecordingSearchResponse? response = await GetJsonOrNullAsync(
+ $"recording?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
+ cancellationToken).ConfigureAwait(false);
+ return response?.Recordings ?? [];
+ }
+
+ ///
+ /// Looks up the recordings that carry the provided ISRC.
+ ///
+ /// The ISRC to look up.
+ /// Cancellation token that can be used to stop the execution.
+ /// The list of recordings that carry the ISRC.
+ public async Task> GetRecordingsByIsrcAsync(string isrc, CancellationToken cancellationToken)
+ {
+ MusicBrainzRecordingListResponse? response = await GetJsonOrNullAsync(
+ $"isrc/{Uri.EscapeDataString(isrc)}?inc=artist-credits+isrcs+work-rels+artist-rels&fmt=json", cancellationToken).ConfigureAwait(false);
+ return response?.Recordings ?? [];
+ }
+
+ ///
+ /// Looks up the work identified by , together with its credited contributors.
+ ///
+ /// The MusicBrainz identifier of the work.
+ /// Cancellation token that can be used to stop the execution.
+ /// The work, or when no work was found.
+ public Task GetWorkAsync(Guid musicBrainzWorkId, CancellationToken cancellationToken)
+ {
+ return GetJsonOrNullAsync(
+ $"work/{musicBrainzWorkId:D}?inc=artist-rels+tags+genres&fmt=json", cancellationToken);
+ }
+
+ ///
+ /// Looks up the release identified by , together with its media, tracks, recordings and all the data needed
+ /// to enrich those tracks, so that every track of the release is enriched from a single request.
+ ///
+ /// The MusicBrainz identifier of the release.
+ /// Cancellation token that can be used to stop the execution.
+ /// The release, with its media, tracks and recordings, or when no release was found.
+ public Task GetReleaseWithRecordingsAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken)
+ {
+ return GetJsonOrNullAsync(
+ $"release/{musicBrainzReleaseId:D}?inc=recordings+isrcs+artist-credits+tags+genres+ratings+work-rels+recording-level-rels+work-level-rels+artist-rels+release-groups+labels+media&fmt=json", cancellationToken);
+ }
+
+ ///
+ /// Gets the JSON resource at the given relative URL and deserializes it into .
+ ///
+ /// The type to deserialize the JSON response into.
+ /// The URL of the resource, relative to the base address.
+ /// Cancellation token that can be used to stop the execution.
+ /// The deserialized resource, or when the resource was not found.
+ /// Transient failures and rate limiting are handled by retrying the request up to three times.
+ private async Task GetJsonOrNullAsync(string relativeUrl, CancellationToken cancellationToken)
+ {
+ MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
+ string cacheKey = string.Concat(settings.BaseUrl, relativeUrl);
+ if (_responseCache.TryGet(cacheKey, out string? cachedJson) && cachedJson is not null)
+ return JsonSerializer.Deserialize(cachedJson, s_serializerOptions);
+
+ using HttpResponseMessage response = await SendAsync(settings, relativeUrl, cancellationToken).ConfigureAwait(false);
+ // A 404 means the entity does not exist in MusicBrainz, which is a normal miss rather than an error, so it is reported as no result.
+ if (response.StatusCode == HttpStatusCode.NotFound)
+ return default;
+ response.EnsureSuccessStatusCode();
+
+ string json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
+ _responseCache.Set(cacheKey, json);
+ return JsonSerializer.Deserialize(json, s_serializerOptions);
+ }
+
+ ///
+ /// Sends a GET request to the MusicBrainz web service, throttled to respect the configured minimum request interval unless the configured
+ /// base URL is not the real MusicBrainz service, in which case no rate limit is imposed. Transient failures, rate limiting and transport
+ /// exceptions are retried, preferring the delay requested by the web service when it is provided.
+ ///
+ /// The settings that configure the MusicBrainz web service requests.
+ /// The URL of the resource, relative to the base address.
+ /// Cancellation token that can be used to stop the execution.
+ /// The HTTP response message for the request.
+ private async Task SendAsync(MusicBrainzSettingsDto settings, string relativeUrl, CancellationToken cancellationToken)
+ {
+ EnsureRequestHeaders(settings);
+ // The rate limit is enforced by the MusicBrainz web service itself, so it is only observed when the requests actually reach it; a self hosted
+ // mirror, or any other configured base URL that is not the real service, is not limited by this process.
+ bool shouldThrottle = IsRealMusicBrainzService(settings.BaseUrl);
+
+ // A fresh request is created for every attempt, because an HTTP request cannot be sent more than once, and the throttle is applied to every
+ // attempt, so that the retries of a failed request cannot burst past the rate limit of the real MusicBrainz web service.
+ for (int attempt = 1; ; attempt++)
+ {
+ if (shouldThrottle)
+ await _requestThrottle.WaitAsync(settings.MinimumRequestInterval, cancellationToken).ConfigureAwait(false);
+
+ bool isLastAttempt = attempt >= MAXIMUM_ATTEMPT_COUNT;
+ HttpResponseMessage response;
+ try
+ {
+ HttpRequestMessage request = new(HttpMethod.Get, BuildRequestUri(settings.BaseUrl, relativeUrl));
+ request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
+ response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
+ }
+ catch (HttpRequestException) when (!isLastAttempt)
+ {
+ await Task.Delay(GetRetryDelay(attempt, null), cancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ if (!isLastAttempt && (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500))
+ {
+ TimeSpan retryDelay = GetRetryDelay(attempt, response);
+ // The response of a failed attempt is not returned, so it must be disposed here to release its connection.
+ response.Dispose();
+ await Task.Delay(retryDelay, cancellationToken).ConfigureAwait(false);
+ continue;
+ }
+
+ return response;
+ }
+ }
+
+ ///
+ /// Gets the delay to wait before the next attempt, preferring the delay requested by the MusicBrainz web service when it is provided.
+ ///
+ /// The one based number of the attempt that just failed.
+ /// The response of the failed attempt, when the failure was a response rather than a transport exception.
+ /// The delay to wait before the next attempt.
+ private static TimeSpan GetRetryDelay(int attempt, HttpResponseMessage? response)
+ {
+ if (response?.Headers.RetryAfter is { } retryAfter)
+ {
+ if (retryAfter.Delta is TimeSpan delta)
+ return delta;
+ if (retryAfter.Date is DateTimeOffset date)
+ {
+ TimeSpan wait = date - DateTimeOffset.UtcNow;
+ if (wait > TimeSpan.Zero)
+ return wait;
+ }
+ }
+ return TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt));
+ }
+
+ ///
+ /// Determines whether the provided base URL points to the real MusicBrainz web service, which is the only one whose rate limit is observed.
+ ///
+ /// The base URL of the MusicBrainz web service the requests are sent to.
+ /// when the base URL points to the real MusicBrainz web service, otherwise .
+ private static bool IsRealMusicBrainzService(string baseUrl)
+ {
+ if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out Uri? baseUri))
+ return false;
+ return baseUri.Host.Equals("musicbrainz.org", StringComparison.OrdinalIgnoreCase)
+ || baseUri.Host.EndsWith(".musicbrainz.org", StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Applies the request headers configured in the onto the underlying HTTP client, unless they are already set.
+ ///
+ /// The settings that configure the MusicBrainz web service requests.
+ private void EnsureRequestHeaders(MusicBrainzSettingsDto settings)
+ {
+ // The headers live on the underlying HttpClient, which is reused across the calls of this client, so they are applied only once.
+ if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0)
+ {
+ string userAgent = string.IsNullOrWhiteSpace(settings.ContactEmail)
+ ? settings.UserAgent
+ : $"{settings.UserAgent} ( {settings.ContactEmail} )";
+ _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent);
+ }
+ }
+
+ ///
+ /// Combines the configured base URL with the given relative URL into the absolute URI of a request.
+ ///
+ /// The base URL of the MusicBrainz web service the requests are sent to.
+ /// The URL of the resource, relative to the base URL.
+ /// The absolute URI of the request.
+ private static Uri BuildRequestUri(string baseUrl, string relativeUrl)
+ {
+ string normalizedBaseUrl = baseUrl.EndsWith('/') ? baseUrl : string.Concat(baseUrl, "/");
+ return new Uri(new Uri(normalizedBaseUrl, UriKind.Absolute), relativeUrl);
+ }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzRequestThrottle.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzRequestThrottle.cs
new file mode 100644
index 00000000..43801c05
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzRequestThrottle.cs
@@ -0,0 +1,49 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Core.Api;
+
+///
+/// Spaces out the requests sent to the MusicBrainz web service, so the configured minimum request interval is respected across every caller in the process.
+///
+internal sealed class MusicBrainzRequestThrottle
+{
+ private readonly SemaphoreSlim _gate = new(1, 1);
+
+ // The timestamp of the last reserved request slot, shared process wide, so the configured interval is enforced between requests no matter
+ // which caller sends them.
+ private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue;
+
+ ///
+ /// Waits until the minimum interval elapsed since the previous reserved request, then reserves the next request slot.
+ ///
+ /// The minimum amount of time that must elapse between two consecutive requests.
+ /// Cancellation token that can be used to stop the execution.
+ /// A task that completes once the caller may send its request.
+ public async Task WaitAsync(TimeSpan minimumRequestInterval, CancellationToken cancellationToken)
+ {
+ // The gate is held across the delay, so concurrent callers queue up and each one is released only once the interval elapsed since the
+ // previous reserved slot.
+ await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ // A non positive interval means the callers are not spaced out at all, and it must not be added to the initial timestamp, which would underflow it.
+ if (minimumRequestInterval > TimeSpan.Zero)
+ {
+ DateTimeOffset earliestNextRequest = _lastRequestAt + minimumRequestInterval;
+ TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow;
+ if (delay > TimeSpan.Zero)
+ await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
+ }
+
+ _lastRequestAt = DateTimeOffset.UtcNow;
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzResponseCache.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzResponseCache.cs
new file mode 100644
index 00000000..06b87f9c
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzResponseCache.cs
@@ -0,0 +1,140 @@
+#region ========================================================================= USING =====================================================================================
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Core.Api;
+
+///
+/// In-memory cache of the responses returned by the MusicBrainz web service, keyed by the requested URL.
+/// It removes the repeated lookups of the same entity during a run, and expires its entries after a bounded time.
+///
+internal sealed class MusicBrainzResponseCache
+{
+ ///
+ /// The maximum number of responses the cache keeps.
+ ///
+ internal const int MAXIMUM_ENTRY_COUNT = 20_000;
+
+ ///
+ /// The maximum total number of characters of the cached response bodies.
+ ///
+ internal const long MAXIMUM_CHARACTER_COUNT = 100_000_000;
+
+ ///
+ /// The percentage of a budget that the cache is trimmed down to when it exceeds that budget. Trimming to a lower water mark keeps the
+ /// eviction from running on every write once a budget is reached.
+ ///
+ private const int TRIM_TARGET_PERCENT = 90;
+
+ private static readonly TimeSpan s_timeToLive = TimeSpan.FromMinutes(15);
+
+ private readonly int _maximumEntryCount;
+ private readonly long _maximumCharacterCount;
+ private readonly TimeSpan _timeToLive;
+ private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal);
+
+ // The dictionary is thread safe on its own, but the character budget is a read modify write over it, so the size bookkeeping and the eviction
+ // are guarded by a lock, while reads stay lock free.
+ private readonly Lock _sizeGate = new();
+ private long _cachedCharacterCount;
+
+ // Monotonically increasing insertion stamp, used to evict the oldest entries first.
+ private long _sequence;
+
+ ///
+ /// Initializes a new instance of the class with the default budgets and time to live.
+ ///
+ public MusicBrainzResponseCache()
+ {
+ _maximumEntryCount = MAXIMUM_ENTRY_COUNT;
+ _maximumCharacterCount = MAXIMUM_CHARACTER_COUNT;
+ _timeToLive = s_timeToLive;
+ }
+
+ ///
+ /// Initializes a new instance of the class with the provided budgets and time to live.
+ ///
+ /// The maximum number of responses the cache keeps.
+ /// The maximum total number of characters of the cached response bodies.
+ /// The amount of time a cached response stays valid.
+ internal MusicBrainzResponseCache(int maximumEntryCount, long maximumCharacterCount, TimeSpan timeToLive)
+ {
+ _maximumEntryCount = maximumEntryCount;
+ _maximumCharacterCount = maximumCharacterCount;
+ _timeToLive = timeToLive;
+ }
+
+ ///
+ /// Tries to get the cached response body for .
+ ///
+ /// The key of the cached response.
+ /// The cached response body, when found.
+ /// when an unexpired response was found, otherwise .
+ public bool TryGet(string key, out string? json)
+ {
+ // An expired entry is treated as a miss instead of being removed here, so readers never take the lock; a later write reclaims it.
+ if (_entries.TryGetValue(key, out CacheEntry? entry) && entry.ExpiresOnUtc > DateTime.UtcNow)
+ {
+ json = entry.Json;
+ return true;
+ }
+ json = null;
+ return false;
+ }
+
+ ///
+ /// Adds or replaces the cached response body for , then trims the cache back to its budgets.
+ ///
+ /// The key of the cached response.
+ /// The response body to cache.
+ public void Set(string key, string json)
+ {
+ // A single response larger than the whole character budget can never be admitted, so it is rejected before it disturbs the cache.
+ if (json.Length > _maximumCharacterCount)
+ return;
+
+ lock (_sizeGate)
+ {
+ if (_entries.TryRemove(key, out CacheEntry? existing))
+ _cachedCharacterCount -= existing.Json.Length;
+
+ _entries[key] = new CacheEntry(json, DateTime.UtcNow.Add(_timeToLive), ++_sequence);
+ _cachedCharacterCount += json.Length;
+
+ if (_entries.Count > _maximumEntryCount || _cachedCharacterCount > _maximumCharacterCount)
+ TrimToBudget();
+ }
+ }
+
+ ///
+ /// Removes the expired entries, and then the oldest unexpired entries, until the cache is back within its entry count and character budgets.
+ ///
+ private void TrimToBudget()
+ {
+ DateTime utcNow = DateTime.UtcNow;
+ bool isOverEntryCount = _entries.Count > _maximumEntryCount;
+ bool isOverCharacterCount = _cachedCharacterCount > _maximumCharacterCount;
+ int entryTarget = Math.Max(1, _maximumEntryCount * TRIM_TARGET_PERCENT / 100);
+ long characterTarget = Math.Max(1, _maximumCharacterCount * TRIM_TARGET_PERCENT / 100);
+
+ // Entries are evicted in insertion order, so the most recently cached responses survive; an expired entry is always removed, even when
+ // a budget was not exceeded, so the cache keeps reclaiming dead entries.
+ foreach (KeyValuePair candidate in _entries.OrderBy(entry => entry.Value.Sequence))
+ {
+ bool isExpired = candidate.Value.ExpiresOnUtc <= utcNow;
+ bool needsEntryTrim = isOverEntryCount && _entries.Count > entryTarget;
+ bool needsCharacterTrim = isOverCharacterCount && _cachedCharacterCount > characterTarget;
+ if (!isExpired && !needsEntryTrim && !needsCharacterTrim)
+ break;
+
+ if (_entries.TryRemove(candidate.Key, out CacheEntry? removed))
+ _cachedCharacterCount -= removed.Json.Length;
+ }
+ }
+
+ private sealed record CacheEntry(string Json, DateTime ExpiresOnUtc, long Sequence);
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs
new file mode 100644
index 00000000..5b6a363a
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Mapping/MusicBrainzMapper.cs
@@ -0,0 +1,759 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.Common;
+using Lumina.Contracts.DTO.MediaContributors;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.Common;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text.RegularExpressions;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Core.Mapping;
+
+///
+/// Maps MusicBrainz web service responses into the application's media metadata DTOs.
+///
+internal static partial class MusicBrainzMapper
+{
+ ///
+ /// The neutral cultures of the process, indexed by both their two letter and three letter ISO 639 codes.
+ /// Built once, because the available cultures do not change during the lifetime of the process.
+ ///
+ private static readonly IReadOnlyDictionary s_neutralCulturesByCode = BuildNeutralCultureLookup();
+
+ ///
+ /// Matches a four digit year.
+ ///
+ [GeneratedRegex(@"\b(?:1[0-9]{3}|20[0-9]{2}|2100)\b")]
+ private static partial Regex YearPattern();
+
+ ///
+ /// Maps a MusicBrainz artist response into artist metadata.
+ ///
+ /// The artist response to map.
+ /// The mapped artist metadata.
+ public static ArtistMetadataDto MapArtist(MusicBrainzArtistResponse artist)
+ {
+ (List contributors, string? website) = MapArtistRelations(artist.Relations);
+ return new ArtistMetadataDto(
+ Name: NullIfWhiteSpace(artist.Name),
+ SortName: NullIfWhiteSpace(artist.SortName),
+ Disambiguation: NullIfWhiteSpace(artist.Disambiguation),
+ Type: MapArtistType(artist.Type),
+ Gender: MapArtistGender(artist.Gender),
+ Country: NullIfWhiteSpace(artist.Country),
+ Area: MapArea(artist.Area),
+ BeginArea: MapArea(artist.BeginArea),
+ EndArea: MapArea(artist.EndArea),
+ LifeSpanBegin: ParseDate(artist.LifeSpan?.Begin).Date,
+ LifeSpanEnd: ParseDate(artist.LifeSpan?.End).Date,
+ IsEnded: artist.LifeSpan?.IsEnded ?? false,
+ Website: website,
+ MusicBrainzArtistId: ParseGuid(artist.Id),
+ Ipis: [.. artist.Ipis.Where(ipi => !string.IsNullOrWhiteSpace(ipi))],
+ Isnis: [.. artist.Isnis.Where(isni => !string.IsNullOrWhiteSpace(isni))],
+ Aliases: [.. artist.Aliases.Select(MapAlias)],
+ Genres: MapGenres(artist.Genres),
+ Tags: MapTags(artist.Tags),
+ Ratings: MapRating(artist.Rating),
+ Contributors: contributors);
+ }
+
+ ///
+ /// Maps a MusicBrainz release group, and optionally one of its releases, into album metadata.
+ ///
+ /// The release group response to map.
+ /// The selected release of the release group, or when no release was selected.
+ /// The mapped album metadata.
+ public static AlbumMetadataDto MapAlbum(MusicBrainzReleaseGroupResponse releaseGroup, MusicBrainzReleaseResponse? release)
+ {
+ (DateOnly? originalDate, int? originalYear) = ParseDate(releaseGroup.FirstReleaseDate);
+ (DateOnly? reReleaseDate, int? reReleaseYear) = ParseDate(release?.Date);
+ if (reReleaseDate is not null && originalDate is not null && reReleaseDate.Value.Year == originalDate.Value.Year)
+ {
+ reReleaseDate = null;
+ reReleaseYear = null;
+ }
+
+ string? releaseArtistId = releaseGroup.ArtistCredit.Select(credit => credit.Artist?.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id))
+ ?? release?.ArtistCredit.Select(credit => credit.Artist?.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id));
+
+ List contributors = MapArtistCredit(releaseGroup.ArtistCredit);
+ if (contributors.Count == 0 && release is not null)
+ contributors = MapArtistCredit(release.ArtistCredit);
+ if (release is not null)
+ AddContributors(contributors, MapContributorsFromRelations(release.Relations));
+
+ List media = release?.Media ?? [];
+ int totalTracks = media.Sum(medium => medium.TrackCount);
+ // A MusicBrainz release can carry several labels and catalog numbers: the label stores the first one, while every catalog number is kept.
+ string? label = release?.LabelInfo.FirstOrDefault()?.Label?.Name;
+ List catalogNumbers = [.. (release?.LabelInfo ?? [])
+ .Select(labelInfo => NullIfWhiteSpace(labelInfo.CatalogNumber))
+ .Where(catalogNumber => catalogNumber is not null)
+ .Select(catalogNumber => catalogNumber!)
+ .Distinct(StringComparer.OrdinalIgnoreCase)];
+
+ return new AlbumMetadataDto(
+ Title: NullIfWhiteSpace(releaseGroup.Title) ?? NullIfWhiteSpace(release?.Title),
+ OriginalTitle: null,
+ Description: null,
+ Disambiguation: NullIfWhiteSpace(releaseGroup.Disambiguation),
+ ReleaseInfo: new ReleaseInfoDto(
+ OriginalReleaseDate: originalDate,
+ OriginalReleaseYear: originalYear,
+ ReReleaseDate: reReleaseDate,
+ ReReleaseYear: reReleaseYear,
+ ReleaseCountry: MapReleaseCountry(release?.Country),
+ ReleaseVersion: NullIfWhiteSpace(release?.Disambiguation)),
+ Language: MapLanguage(release?.TextRepresentation?.Language),
+ OriginalLanguage: null,
+ Tags: MapTags(releaseGroup.Tags),
+ Genres: MapGenres(releaseGroup.Genres),
+ Script: NullIfWhiteSpace(release?.TextRepresentation?.Script),
+ ReleaseTypes: MapReleaseTypes(releaseGroup.PrimaryType, releaseGroup.SecondaryTypes),
+ ReleaseStatus: MapReleaseStatus(release?.Status),
+ MediaFormat: MapMediaFormat(media.FirstOrDefault()?.Format),
+ Packaging: MapPackaging(release?.Packaging),
+ TotalDiscs: media.Count > 0 ? media.Count : null,
+ TotalTracks: totalTracks > 0 ? totalTracks : null,
+ Barcode: NullIfWhiteSpace(release?.Barcode),
+ CatalogNumbers: catalogNumbers,
+ Label: NullIfWhiteSpace(label),
+ ASIN: NullIfWhiteSpace(release?.Asin),
+ MusicBrainzReleaseId: ParseGuid(release?.Id),
+ MusicBrainzReleaseGroupId: ParseGuid(releaseGroup.Id),
+ MusicBrainzReleaseArtistId: ParseGuid(releaseArtistId),
+ Contributors: contributors,
+ Ratings: MapRating(releaseGroup.Rating),
+ ReleaseTitle: NullIfWhiteSpace(release?.Title));
+ }
+
+ ///
+ /// Maps a MusicBrainz recording, and optionally its work and release, into track metadata.
+ ///
+ /// The recording response to map.
+ /// The work the recording is an instance of, or when the recording has no work.
+ /// The release the recording appears on, or when it is not known.
+ /// The mapped track metadata.
+ public static AudioMetadataDto MapTrack(MusicBrainzRecordingResponse recording, MusicBrainzWorkResponse? work, MusicBrainzReleaseResponse? release)
+ {
+ (DateOnly? releaseDate, int? releaseYear) = ParseDate(recording.FirstReleaseDate);
+ // A recording embedded in a release lookup does not carry its own first release date, so the date of the release the track appears on is used
+ // instead, rather than leaving the track without any release date at all.
+ if (releaseYear is null)
+ (releaseDate, releaseYear) = ParseDate(release?.Date);
+
+ List contributors = MapArtistCredit(recording.ArtistCredit);
+ AddContributors(contributors, MapContributorsFromRelations(recording.Relations));
+ if (work is not null)
+ AddContributors(contributors, MapContributorsFromRelations(work.Relations));
+
+ return new AudioMetadataDto(
+ Title: NullIfWhiteSpace(recording.Title),
+ OriginalTitle: null,
+ Description: null,
+ Disambiguation: NullIfWhiteSpace(recording.Disambiguation),
+ ReleaseInfo: new ReleaseInfoDto(
+ OriginalReleaseDate: releaseDate,
+ OriginalReleaseYear: releaseYear,
+ ReReleaseDate: null,
+ ReReleaseYear: null,
+ ReleaseCountry: null,
+ ReleaseVersion: null),
+ Language: MapLanguage(release?.TextRepresentation?.Language),
+ OriginalLanguage: null,
+ Tags: MapTags(recording.Tags),
+ Genres: MapGenres(recording.Genres),
+ Script: NullIfWhiteSpace(release?.TextRepresentation?.Script),
+ Key: null,
+ Bpm: null,
+ IsVideo: recording.IsVideo ?? false,
+ Work: work is null ? null : MapWork(work),
+ Isrcs: [.. recording.Isrcs.Where(isrc => !string.IsNullOrWhiteSpace(isrc)).Select(isrc => new IsrcDto(isrc))],
+ Moods: null,
+ DurationInSeconds: recording.Length is long length && length > 0 ? (int)(length / 1000) : null,
+ SampleRate: null,
+ Channels: null,
+ BitDepth: null,
+ AudioCodec: null,
+ Bitrate: null,
+ MusicBrainzRecordingId: ParseGuid(recording.Id),
+ MusicBrainzTrackId: null,
+ Contributors: contributors,
+ Ratings: MapRating(recording.Rating));
+ }
+
+ ///
+ /// Maps a MusicBrainz work into a work DTO.
+ ///
+ /// The work response to map.
+ /// The mapped work.
+ public static MusicWorkDto MapWork(MusicBrainzWorkResponse work)
+ {
+ return new MusicWorkDto(
+ MusicBrainzWorkId: ParseGuid(work.Id),
+ Title: NullIfWhiteSpace(work.Title),
+ Type: NullIfWhiteSpace(work.Type),
+ Languages: [.. work.Languages.Select(MapLanguage).Where(language => language is not null).Select(language => language!)],
+ Iswcs: [.. work.Iswcs.Where(iswc => !string.IsNullOrWhiteSpace(iswc))]);
+ }
+
+ ///
+ /// Maps a MusicBrainz area into an area DTO.
+ ///
+ /// The area response to map.
+ /// The mapped area, or when no area is provided.
+ public static MusicAreaDto? MapArea(MusicBrainzAreaResponse? area)
+ {
+ if (area is null)
+ return null;
+
+ string? isoCode = area.Iso3166Part1Codes.FirstOrDefault() ?? area.Iso3166Part2Codes.FirstOrDefault();
+ return new MusicAreaDto(
+ MusicBrainzAreaId: ParseGuid(area.Id),
+ Name: NullIfWhiteSpace(area.Name),
+ SortName: NullIfWhiteSpace(area.SortName),
+ Disambiguation: NullIfWhiteSpace(area.Disambiguation),
+ Type: NullIfWhiteSpace(area.Type),
+ Iso3166Code: NullIfWhiteSpace(isoCode));
+ }
+
+ ///
+ /// Maps a MusicBrainz alias into an alias DTO.
+ ///
+ /// The alias response to map.
+ /// The mapped alias.
+ private static MusicArtistAliasDto MapAlias(MusicBrainzAliasResponse alias)
+ {
+ return new MusicArtistAliasDto(
+ Name: NullIfWhiteSpace(alias.Name),
+ SortName: NullIfWhiteSpace(alias.SortName),
+ Type: NullIfWhiteSpace(alias.Type),
+ Locale: NullIfWhiteSpace(alias.Locale),
+ IsPrimary: alias.IsPrimary ?? false,
+ BeginDate: ParseDate(alias.Begin).Date,
+ EndDate: ParseDate(alias.End).Date,
+ IsEnded: alias.IsEnded ?? false);
+ }
+
+ ///
+ /// Maps the genres of a MusicBrainz entity into genre DTOs.
+ ///
+ /// The genre responses to map.
+ /// The mapped genre DTOs.
+ private static List MapGenres(IReadOnlyCollection genres)
+ {
+ return [.. genres
+ .Where(genre => !string.IsNullOrWhiteSpace(genre.Name))
+ .Select(genre => new GenreDto(genre.Name))
+ .DistinctBy(genre => genre.Name, StringComparer.OrdinalIgnoreCase)];
+ }
+
+ ///
+ /// Maps the tags of a MusicBrainz entity into tag DTOs.
+ ///
+ /// The tag responses to map.
+ /// The mapped tag DTOs.
+ private static List MapTags(IReadOnlyCollection tags)
+ {
+ return [.. tags
+ .Where(tag => !string.IsNullOrWhiteSpace(tag.Name))
+ .Select(tag => new TagDto(tag.Name))
+ .DistinctBy(tag => tag.Name, StringComparer.OrdinalIgnoreCase)];
+ }
+
+ ///
+ /// Maps the rating of a MusicBrainz entity into a rating DTO.
+ ///
+ /// The rating response to map.
+ /// The mapped rating DTO, or an empty list when no rating is provided.
+ private static List MapRating(MusicBrainzRatingResponse? rating)
+ {
+ if (rating is null || (rating.Value is null && rating.VotesCount is null))
+ return [];
+ return [new AudioRatingDto(rating.Value, 5m, AudioRatingSource.MusicBrainz, rating.VotesCount)];
+ }
+
+ ///
+ /// Maps an ISO 639-3 language code into a language DTO.
+ ///
+ /// The code to map.
+ /// The mapped language, or when the code is empty.
+ private static LanguageInfoDto? MapLanguage(string? rawCode)
+ {
+ if (string.IsNullOrWhiteSpace(rawCode))
+ return null;
+
+ string code = rawCode.Trim().ToLowerInvariant();
+ // A language code can list several languages, such as "eng/ara"; the first one is the language of the release.
+ string primaryCode = code.Split('/').Select(part => part.Trim()).FirstOrDefault(part => part.Length > 0) ?? code;
+
+ // These ISO 639-3 codes describe a language absence rather than a culture, so they cannot be resolved through a culture.
+ switch (primaryCode)
+ {
+ case "zxx":
+ return new LanguageInfoDto(primaryCode, "No linguistic content", null);
+ case "mul":
+ return new LanguageInfoDto(primaryCode, "Multiple languages", null);
+ case "und":
+ return new LanguageInfoDto(primaryCode, "Undetermined", null);
+ default:
+ break;
+ }
+
+ // Only neutral cultures are matched, because a specific culture would resolve to an arbitrary regional name such as "German (Austria)".
+ return s_neutralCulturesByCode.TryGetValue(primaryCode, out CultureInfo? culture)
+ ? new LanguageInfoDto(culture.TwoLetterISOLanguageName, culture.EnglishName, culture.NativeName)
+ : new LanguageInfoDto(primaryCode, primaryCode, null);
+ }
+
+ ///
+ /// Builds the lookup of the process' neutral cultures, indexed by both their two letter and three letter ISO 639 codes.
+ ///
+ /// The neutral cultures, indexed by their ISO 639 codes.
+ private static IReadOnlyDictionary BuildNeutralCultureLookup()
+ {
+ Dictionary culturesByCode = new(StringComparer.OrdinalIgnoreCase);
+ foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.NeutralCultures))
+ {
+ // A culture without a two letter ISO 639 code is not a language, so it is skipped; the two letter code is the one carried by the DTOs.
+ if (culture.TwoLetterISOLanguageName.Length != 2)
+ continue;
+ culturesByCode.TryAdd(culture.ThreeLetterISOLanguageName, culture);
+ culturesByCode.TryAdd(culture.TwoLetterISOLanguageName, culture);
+ }
+ return culturesByCode;
+ }
+
+ ///
+ /// Maps the artist credit of a MusicBrainz entity into attributed performing contributors.
+ ///
+ /// The artist credit to map.
+ /// The mapped contributors.
+ private static List MapArtistCredit(IReadOnlyCollection artistCredit)
+ {
+ List contributors = [];
+ foreach (MusicBrainzArtistCreditResponse credit in artistCredit)
+ {
+ string? name = NullIfWhiteSpace(credit.Name) ?? NullIfWhiteSpace(credit.Artist?.Name);
+ if (name is null)
+ continue;
+ AddContributor(contributors, name, MediaContributorRole.Performer);
+ }
+ return contributors;
+ }
+
+ ///
+ /// Maps the artist relations of a MusicBrainz entity into contributors, excluding the URL relations.
+ ///
+ /// The relations to map.
+ /// The mapped contributors.
+ private static List MapContributorsFromRelations(IReadOnlyCollection relations)
+ {
+ List contributors = [];
+ foreach (MusicBrainzRelationResponse relation in relations)
+ {
+ if (!string.Equals(relation.TargetType, "artist", StringComparison.OrdinalIgnoreCase))
+ continue;
+
+ string? name = NullIfWhiteSpace(relation.Artist?.Name);
+ if (name is null)
+ continue;
+ AddContributor(contributors, name, MapRole(relation.Type, relation.Attributes));
+ }
+ return contributors;
+ }
+
+ ///
+ /// Maps the relations of an artist into its contributing members, and its official homepage.
+ ///
+ /// The relations of the artist.
+ /// The mapped contributors, and the official homepage of the artist.
+ private static (List Contributors, string? Website) MapArtistRelations(IReadOnlyCollection relations)
+ {
+ List contributors = [];
+ string? website = null;
+ foreach (MusicBrainzRelationResponse relation in relations)
+ {
+ if (string.Equals(relation.TargetType, "url", StringComparison.OrdinalIgnoreCase))
+ {
+ if (website is null && string.Equals(relation.Type, "official homepage", StringComparison.OrdinalIgnoreCase))
+ website = NullIfWhiteSpace(relation.Url?.Resource);
+ continue;
+ }
+
+ if (!string.Equals(relation.TargetType, "artist", StringComparison.OrdinalIgnoreCase))
+ continue;
+
+ string? name = NullIfWhiteSpace(relation.Artist?.Name);
+ if (name is null)
+ continue;
+ AddContributor(contributors, name, MapRole(relation.Type, relation.Attributes));
+ }
+ return (contributors, website);
+ }
+
+ ///
+ /// Adds a contributor to the provided list, unless an identical name and role pair is already present.
+ ///
+ /// The contributors collected so far.
+ /// The display name of the contributor.
+ /// The role the contributor played.
+ private static void AddContributor(List contributors, string displayName, MediaContributorRole role)
+ {
+ if (contributors.Any(contributor =>
+ string.Equals(contributor.Name?.DisplayName, displayName, StringComparison.OrdinalIgnoreCase) &&
+ contributor.Role == role))
+ return;
+ contributors.Add(new MediaContributorDto(new MediaContributorNameDto(displayName, null), role));
+ }
+
+ ///
+ /// Adds the contributors to , skipping the duplicate name and role pairs.
+ ///
+ /// The contributors collected so far.
+ /// The contributors to add.
+ private static void AddContributors(List contributors, IReadOnlyCollection incoming)
+ {
+ foreach (MediaContributorDto contributor in incoming)
+ {
+ if (contributor.Name?.DisplayName is not string displayName)
+ continue;
+ AddContributor(contributors, displayName, contributor.Role ?? MediaContributorRole.Other);
+ }
+ }
+
+ ///
+ /// Maps a MusicBrainz relationship type, and its attributes, into a canonical media contributor role.
+ ///
+ /// The relationship type to map.
+ /// The attributes of the relationship.
+ /// The mapped contributor role.
+ private static MediaContributorRole MapRole(string? relationType, IReadOnlyCollection attributes)
+ {
+ // An instrument attribute is more specific than the generic relationship type, so it is preferred.
+ foreach (string attribute in attributes)
+ {
+ MediaContributorRole? attributed = MapInstrument(attribute);
+ if (attributed is not null)
+ return attributed.Value;
+ }
+
+ if (string.IsNullOrWhiteSpace(relationType))
+ return MediaContributorRole.Other;
+
+ string type = relationType.Trim().ToLowerInvariant();
+ if (type.Contains("executive producer", StringComparison.Ordinal))
+ return MediaContributorRole.ExecutiveProducer;
+ if (type.Contains("producer", StringComparison.Ordinal))
+ return MediaContributorRole.Producer;
+ if (type.Contains("remixer", StringComparison.Ordinal))
+ return MediaContributorRole.Remixer;
+ if (type.Contains("mix", StringComparison.Ordinal))
+ return MediaContributorRole.Mixer;
+ if (type.Contains("engineer", StringComparison.Ordinal) || type.Contains("mastering", StringComparison.Ordinal))
+ return MediaContributorRole.Engineer;
+ if (type.Contains("composer", StringComparison.Ordinal))
+ return MediaContributorRole.Composer;
+ if (type.Contains("writer", StringComparison.Ordinal))
+ return MediaContributorRole.Author;
+ if (type.Contains("lyricist", StringComparison.Ordinal))
+ return MediaContributorRole.Lyricist;
+ if (type.Contains("librettist", StringComparison.Ordinal))
+ return MediaContributorRole.Lyricist;
+ if (type.Contains("arranger", StringComparison.Ordinal))
+ return MediaContributorRole.Arranger;
+ if (type.Contains("conductor", StringComparison.Ordinal))
+ return MediaContributorRole.Conductor;
+ if (type.Contains("orchestrator", StringComparison.Ordinal))
+ return MediaContributorRole.Orchestrator;
+ if (type.Contains("backing vocals", StringComparison.Ordinal))
+ return MediaContributorRole.BackingVocals;
+ if (type.Contains("vocal", StringComparison.Ordinal))
+ return MediaContributorRole.Vocals;
+ if (type.Contains("member of band", StringComparison.Ordinal) || type.Contains("performer", StringComparison.Ordinal) || type.Contains("orchestra", StringComparison.Ordinal) || type.Contains("choir", StringComparison.Ordinal))
+ return MediaContributorRole.Performer;
+ return MediaContributorRole.Other;
+ }
+
+ ///
+ /// Maps a MusicBrainz instrument attribute into a canonical media contributor role.
+ ///
+ /// The instrument attribute to map.
+ /// The mapped contributor role, or when the attribute is not an instrument.
+ private static MediaContributorRole? MapInstrument(string? attribute)
+ {
+ if (string.IsNullOrWhiteSpace(attribute))
+ return null;
+
+ string value = attribute.Trim().ToLowerInvariant();
+ if (value.Contains("backing vocal", StringComparison.Ordinal))
+ return MediaContributorRole.BackingVocals;
+ if (value.Contains("vocal", StringComparison.Ordinal))
+ return MediaContributorRole.Vocals;
+ if (value.Contains("bass guitar", StringComparison.Ordinal))
+ return MediaContributorRole.BassGuitar;
+ if (value.Contains("guitar", StringComparison.Ordinal))
+ return MediaContributorRole.Guitar;
+ if (value.Contains("drum", StringComparison.Ordinal))
+ return MediaContributorRole.Drums;
+ if (value.Contains("percussion", StringComparison.Ordinal))
+ return MediaContributorRole.Percussion;
+ if (value.Contains("keyboard", StringComparison.Ordinal))
+ return MediaContributorRole.Keyboards;
+ if (value.Contains("piano", StringComparison.Ordinal))
+ return MediaContributorRole.Piano;
+ if (value.Contains("synthesizer", StringComparison.Ordinal) || value.Contains("synth", StringComparison.Ordinal))
+ return MediaContributorRole.Synthesizer;
+ if (value.Contains("string", StringComparison.Ordinal) || value.Contains("violin", StringComparison.Ordinal) || value.Contains("cello", StringComparison.Ordinal) || value.Contains("viola", StringComparison.Ordinal))
+ return MediaContributorRole.Strings;
+ if (value.Contains("brass", StringComparison.Ordinal) || value.Contains("trumpet", StringComparison.Ordinal) || value.Contains("trombone", StringComparison.Ordinal) || value.Contains("horn", StringComparison.Ordinal))
+ return MediaContributorRole.Brass;
+ if (value.Contains("woodwind", StringComparison.Ordinal) || value.Contains("flute", StringComparison.Ordinal) || value.Contains("saxophone", StringComparison.Ordinal) || value.Contains("clarinet", StringComparison.Ordinal))
+ return MediaContributorRole.Woodwinds;
+ return null;
+ }
+
+ ///
+ /// Maps a MusicBrainz artist type into the application enum.
+ ///
+ /// The artist type to map.
+ /// The mapped artist type, or when the type is unknown.
+ private static MusicArtistType? MapArtistType(string? type)
+ {
+ if (string.IsNullOrWhiteSpace(type))
+ return null;
+ return type.Trim().ToLowerInvariant() switch
+ {
+ "person" => MusicArtistType.Person,
+ "group" => MusicArtistType.Group,
+ "orchestra" => MusicArtistType.Orchestra,
+ "choir" => MusicArtistType.Choir,
+ "character" => MusicArtistType.Character,
+ "other" => MusicArtistType.Other,
+ _ => null
+ };
+ }
+
+ ///
+ /// Maps a MusicBrainz gender into the application enum.
+ ///
+ /// The gender to map.
+ /// The mapped gender, or when the gender is unknown.
+ private static MusicArtistGender? MapArtistGender(string? gender)
+ {
+ if (string.IsNullOrWhiteSpace(gender))
+ return null;
+ return gender.Trim().ToLowerInvariant() switch
+ {
+ "male" => MusicArtistGender.Male,
+ "female" => MusicArtistGender.Female,
+ "other" => MusicArtistGender.Other,
+ "not applicable" => MusicArtistGender.NotApplicable,
+ _ => null
+ };
+ }
+
+ ///
+ /// Maps the primary and secondary types of a release group into the application enum.
+ ///
+ /// The primary type of the release group.
+ /// The secondary types of the release group.
+ /// The mapped release types.
+ private static List MapReleaseTypes(string? primaryType, IReadOnlyCollection secondaryTypes)
+ {
+ List releaseTypes = [];
+ MusicReleaseType? primary = MapReleaseType(primaryType);
+ if (primary is not null)
+ releaseTypes.Add(primary.Value);
+
+ foreach (string secondaryType in secondaryTypes)
+ {
+ MusicReleaseType? mapped = MapReleaseType(secondaryType);
+ if (mapped is not null && !releaseTypes.Contains(mapped.Value))
+ releaseTypes.Add(mapped.Value);
+ }
+ return releaseTypes;
+ }
+
+ ///
+ /// Maps a single MusicBrainz release type into the application enum.
+ ///
+ /// The release type to map.
+ /// The mapped release type, or when the type is unknown.
+ private static MusicReleaseType? MapReleaseType(string? type)
+ {
+ if (string.IsNullOrWhiteSpace(type))
+ return null;
+ return type.Trim().ToLowerInvariant() switch
+ {
+ "album" => MusicReleaseType.Album,
+ "single" => MusicReleaseType.Single,
+ "ep" => MusicReleaseType.Ep,
+ "broadcast" => MusicReleaseType.Broadcast,
+ "other" => MusicReleaseType.Other,
+ "compilation" => MusicReleaseType.Compilation,
+ "live" => MusicReleaseType.Live,
+ "soundtrack" => MusicReleaseType.Soundtrack,
+ "spokenword" => MusicReleaseType.SpokenWord,
+ "audio drama" => MusicReleaseType.AudioDrama,
+ "audiobook" => MusicReleaseType.AudioBook,
+ "demo" => MusicReleaseType.Demo,
+ "dj-mix" => MusicReleaseType.DjMix,
+ "field recording" => MusicReleaseType.FieldRecording,
+ "interview" => MusicReleaseType.Interview,
+ "mixtape/street" => MusicReleaseType.Mixtape,
+ "remix" => MusicReleaseType.Remix,
+ _ => null
+ };
+ }
+
+ ///
+ /// Maps a MusicBrainz release status into the application enum.
+ ///
+ /// The release status to map.
+ /// The mapped release status, or when the status is unknown.
+ private static MusicReleaseStatus? MapReleaseStatus(string? status)
+ {
+ if (string.IsNullOrWhiteSpace(status))
+ return null;
+ return status.Trim().ToLowerInvariant() switch
+ {
+ "official" => MusicReleaseStatus.Official,
+ "promotion" => MusicReleaseStatus.Promotion,
+ "bootleg" => MusicReleaseStatus.Bootleg,
+ "pseudo-release" => MusicReleaseStatus.PseudoRelease,
+ "withdrawn" => MusicReleaseStatus.Withdrawn,
+ "cancelled" => MusicReleaseStatus.Cancelled,
+ "expunged" => MusicReleaseStatus.Expunged,
+ _ => null
+ };
+ }
+
+ ///
+ /// Maps a MusicBrainz medium format into the application enum.
+ ///
+ /// The format to map.
+ /// The mapped media format, or when the format is unknown.
+ private static MusicMediaFormat? MapMediaFormat(string? format)
+ {
+ if (string.IsNullOrWhiteSpace(format))
+ return null;
+ return format.Trim().ToLowerInvariant() switch
+ {
+ "cd" => MusicMediaFormat.CD,
+ "vinyl" => MusicMediaFormat.Vinyl,
+ "12\" vinyl" => MusicMediaFormat.Inch12Vinyl,
+ "10\" vinyl" => MusicMediaFormat.Inch10Vinyl,
+ "7\" vinyl" => MusicMediaFormat.Inch7Vinyl,
+ "digital media" => MusicMediaFormat.DigitalMedia,
+ "cassette" => MusicMediaFormat.Cassette,
+ "dvd" => MusicMediaFormat.DVD,
+ "dvd-video" => MusicMediaFormat.DVDVideo,
+ "dvd-audio" => MusicMediaFormat.DVDAudio,
+ "sacd" => MusicMediaFormat.SACD,
+ "hybrid sacd" => MusicMediaFormat.HybridSACD,
+ "blu-ray" => MusicMediaFormat.BluRay,
+ "minidisc" => MusicMediaFormat.MiniDisc,
+ "8cm cd" => MusicMediaFormat.Cm8CD,
+ "dat" => MusicMediaFormat.DAT,
+ "other" => MusicMediaFormat.Other,
+ _ => MusicMediaFormat.Other
+ };
+ }
+
+ ///
+ /// Maps a MusicBrainz release packaging into the application enum.
+ ///
+ /// The packaging to map.
+ /// The mapped packaging, or when the packaging is unknown.
+ private static MusicReleasePackaging? MapPackaging(string? packaging)
+ {
+ if (string.IsNullOrWhiteSpace(packaging))
+ return null;
+ return packaging.Trim().ToLowerInvariant() switch
+ {
+ "book" => MusicReleasePackaging.Book,
+ "box" => MusicReleasePackaging.Box,
+ "cardboard/paper sleeve" => MusicReleasePackaging.CardboardPaperSleeve,
+ "cassette case" => MusicReleasePackaging.CassetteCase,
+ "clamshell case" => MusicReleasePackaging.ClamshellCase,
+ "digibook" => MusicReleasePackaging.Digibook,
+ "digifile" => MusicReleasePackaging.Digifile,
+ "digipak" => MusicReleasePackaging.Digipak,
+ "discbox slider" => MusicReleasePackaging.DiscboxSlider,
+ "fatbox" => MusicReleasePackaging.Fatbox,
+ "gatefold cover" => MusicReleasePackaging.GatefoldCover,
+ "jewel case" => MusicReleasePackaging.JewelCase,
+ "keep case" => MusicReleasePackaging.KeepCase,
+ "longbox" => MusicReleasePackaging.Longbox,
+ "metal tin" => MusicReleasePackaging.MetalTin,
+ "plastic sleeve" => MusicReleasePackaging.PlasticSleeve,
+ "slidepack" => MusicReleasePackaging.Slidepack,
+ "slim jewel case" => MusicReleasePackaging.SlimJewelCase,
+ "slipcase" => MusicReleasePackaging.Slipcase,
+ "snap case" => MusicReleasePackaging.SnapCase,
+ "snappack" => MusicReleasePackaging.SnapPack,
+ "super jewel box" => MusicReleasePackaging.SuperJewelBox,
+ "none" => MusicReleasePackaging.None,
+ "other" => MusicReleasePackaging.Other,
+ _ => MusicReleasePackaging.Other
+ };
+ }
+
+ ///
+ /// Maps an ISO 3166-1 alpha-2 country code into the application enum.
+ ///
+ /// The country code to map.
+ /// The mapped release country, or when the code is unknown.
+ private static ReleaseCountry? MapReleaseCountry(string? country)
+ {
+ if (string.IsNullOrWhiteSpace(country))
+ return null;
+ return Enum.TryParse(country.Trim(), ignoreCase: true, out ReleaseCountry releaseCountry) ? releaseCountry : null;
+ }
+
+ ///
+ /// Parses a MusicBrainz identifier into a .
+ ///
+ /// The MusicBrainz identifier to parse.
+ /// The parsed identifier, or when the value is not a valid identifier.
+ private static Guid? ParseGuid(string? value)
+ {
+ return Guid.TryParse(value, out Guid parsed) ? parsed : null;
+ }
+
+ ///
+ /// Parses a MusicBrainz date string into a date and a year.
+ ///
+ /// The date string to parse.
+ /// The parsed date and year, or values when the string could not be parsed.
+ private static (DateOnly? Date, int? Year) ParseDate(string? value)
+ {
+ if (string.IsNullOrWhiteSpace(value))
+ return (null, null);
+
+ if (DateOnly.TryParse(value.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly exact))
+ return (exact, exact.Year);
+
+ Match yearMatch = YearPattern().Match(value);
+ return yearMatch.Success && int.TryParse(yearMatch.Value, CultureInfo.InvariantCulture, out int year) ? (null, year) : (null, null);
+ }
+
+ ///
+ /// Returns the trimmed value, or when the value is empty or white space.
+ ///
+ /// The value to process.
+ /// The trimmed value, or .
+ private static string? NullIfWhiteSpace(string? value)
+ {
+ return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
+ }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzAlbumMetadataProvider.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzAlbumMetadataProvider.cs
new file mode 100644
index 00000000..ccdef688
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzAlbumMetadataProvider.cs
@@ -0,0 +1,206 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Plugins.Contracts.Core.Metadata;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
+using Lumina.Plugins.MusicBrainz.Core.Api;
+using Lumina.Plugins.MusicBrainz.Core.Mapping;
+using Lumina.Plugins.MusicBrainz.Core.Settings;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Core;
+
+///
+/// Provides album metadata from MusicBrainz by resolving lookups into album metadata DTOs.
+/// A MusicBrainz release group is the logical album, while one of its releases is selected as the edition the local files match.
+///
+internal sealed class MusicBrainzAlbumMetadataProvider : IMetadataProvider
+{
+ private readonly MusicBrainzHttpClient _musicBrainzHttpClient;
+ private readonly MusicBrainzSettingsProvider _settingsProvider;
+
+ ///
+ /// Gets the display name of the metadata provider.
+ ///
+ public string Name => "MusicBrainz";
+
+ ///
+ /// Gets the media library types this metadata provider supports.
+ ///
+ public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music];
+
+ ///
+ /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
+ ///
+ public bool RequiresWebAccess => true;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The HTTP client used to call the MusicBrainz web service.
+ /// The provider of the settings that configure the MusicBrainz web service requests.
+ public MusicBrainzAlbumMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider)
+ {
+ _musicBrainzHttpClient = musicBrainzHttpClient;
+ _settingsProvider = settingsProvider;
+ }
+
+ ///
+ /// Searches for the metadata of the album described by .
+ ///
+ /// The lookup describing the album to search for.
+ /// Cancellation token that can be used to stop the execution.
+ /// The collection of album metadata candidates found.
+ public async Task> GetSearchResultsAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
+ {
+ if (string.IsNullOrWhiteSpace(lookup.Title))
+ return [];
+
+ MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
+ IReadOnlyList releaseGroups = await _musicBrainzHttpClient
+ .SearchReleaseGroupsAsync(BuildReleaseGroupQuery(lookup.Title, lookup.ArtistName), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
+
+ List candidates = [];
+ foreach (MusicBrainzReleaseGroupResponse releaseGroup in releaseGroups)
+ if (!string.IsNullOrWhiteSpace(releaseGroup.Title))
+ candidates.Add(MusicBrainzMapper.MapAlbum(releaseGroup, null));
+
+ return candidates;
+ }
+
+ ///
+ /// Gets the metadata of the album described by .
+ ///
+ /// The lookup describing the album to get the metadata for.
+ /// Cancellation token that can be used to stop the execution.
+ /// The metadata of the album, or when no album was found.
+ public async Task GetMetadataAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
+ {
+ MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
+ MusicBrainzReleaseResponse? release = null;
+ MusicBrainzReleaseGroupResponse? releaseGroup = null;
+
+ // A release identifier pins the exact edition, so it is fetched first, and its release group is then resolved for the album level fields.
+ // The release is fetched together with its recordings, so that the track level enrichment of the same release is served from the response cache.
+ if (lookup.MusicBrainzReleaseId is not null)
+ release = await _musicBrainzHttpClient.GetReleaseWithRecordingsAsync(lookup.MusicBrainzReleaseId.Value, cancellationToken).ConfigureAwait(false);
+
+ Guid? releaseGroupId = lookup.MusicBrainzReleaseGroupId;
+ if (releaseGroupId is null && release?.ReleaseGroup?.Id is string releaseGroupIdValue && Guid.TryParse(releaseGroupIdValue, out Guid parsedReleaseGroupId))
+ releaseGroupId = parsedReleaseGroupId;
+
+ if (releaseGroupId is not null)
+ releaseGroup = await _musicBrainzHttpClient.GetReleaseGroupAsync(releaseGroupId.Value, cancellationToken).ConfigureAwait(false);
+
+ // Without any identifier, the album is searched by title and artist, and the first match is resolved in full.
+ if (release is null && releaseGroup is null && !string.IsNullOrWhiteSpace(lookup.Title))
+ {
+ IReadOnlyList results = await _musicBrainzHttpClient
+ .SearchReleaseGroupsAsync(BuildReleaseGroupQuery(lookup.Title, lookup.ArtistName), 1, cancellationToken).ConfigureAwait(false);
+ MusicBrainzReleaseGroupResponse? searchResult = results.Count > 0 ? results[0] : null;
+ if (searchResult?.Id is string searchResultId && Guid.TryParse(searchResultId, out Guid parsedSearchResultId))
+ releaseGroup = await _musicBrainzHttpClient.GetReleaseGroupAsync(parsedSearchResultId, cancellationToken).ConfigureAwait(false);
+ }
+
+ if (releaseGroup is null)
+ return release is null ? null : MusicBrainzMapper.MapAlbum(new MusicBrainzReleaseGroupResponse { Id = release.ReleaseGroup?.Id, Title = release.Title }, release);
+
+ // When the exact release was not pinned by the lookup, the best edition of the release group is selected.
+ if (release is null && releaseGroup.Id is string releaseGroupIdentifier && Guid.TryParse(releaseGroupIdentifier, out Guid releaseGroupGuid))
+ {
+ IReadOnlyList releases = await _musicBrainzHttpClient
+ .BrowseReleasesByReleaseGroupAsync(releaseGroupGuid, settings.ReleaseLookupLimit, cancellationToken).ConfigureAwait(false);
+ release = SelectRelease(releases, lookup);
+ }
+
+ return MusicBrainzMapper.MapAlbum(releaseGroup, release);
+ }
+
+ ///
+ /// Selects the release of a release group that best matches the lookup, favoring official releases and those released in the lookup year.
+ ///
+ /// The releases to select from.
+ /// The lookup the selected release must match.
+ /// The best matching release, or when no release was provided.
+ private static MusicBrainzReleaseResponse? SelectRelease(IReadOnlyList releases, AlbumMetadataLookupDto lookup)
+ {
+ // Only a release whose tracklist matches the local album is selected, so that an edition of the release group that does not correspond to the
+ // local files is never attached to the album; without a known local track count, no release can be confidently matched, so none is selected.
+ if (lookup.TrackCount is not int trackCount)
+ return null;
+
+ List matchingReleases = [.. releases.Where(release => release.Media.Sum(medium => medium.TrackCount) == trackCount)];
+ if (matchingReleases.Count == 0)
+ return null;
+
+ return matchingReleases
+ .Select((release, index) => new
+ {
+ Release = release,
+ Index = index,
+ Score = ScoreRelease(release, lookup)
+ })
+ .OrderByDescending(item => item.Score)
+ .ThenBy(item => item.Index)
+ .Select(item => item.Release)
+ .First();
+ }
+
+ ///
+ /// Scores a release against the lookup to rank how well it matches.
+ ///
+ /// The release to score.
+ /// The lookup the release must match.
+ /// The match score of the release, where a higher score is a better match.
+ private static int ScoreRelease(MusicBrainzReleaseResponse release, AlbumMetadataLookupDto lookup)
+ {
+ int score = 0;
+ if (string.Equals(release.Status, "Official", StringComparison.OrdinalIgnoreCase))
+ score += 10_000;
+
+ if (lookup.ReleaseYear is int wantedYear && TryGetYear(release.Date) is int releaseYear && releaseYear == wantedYear)
+ score += 1_000;
+
+ if (!string.IsNullOrWhiteSpace(release.Barcode))
+ score += 100;
+ if (release.LabelInfo.Count > 0)
+ score += 50;
+ if (release.Media.Count > 0)
+ score += 10;
+ return score;
+ }
+
+ ///
+ /// Gets the year of a MusicBrainz date string.
+ ///
+ /// The date string to read.
+ /// The year of the date, or when it could not be read.
+ private static int? TryGetYear(string? date)
+ {
+ if (string.IsNullOrWhiteSpace(date))
+ return null;
+ string year = date.Length >= 4 ? date[..4] : date;
+ return int.TryParse(year, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed) ? parsed : null;
+ }
+
+ ///
+ /// Builds the MusicBrainz release group search query for the provided title and artist.
+ ///
+ /// The title of the release group.
+ /// The name of the artist, if applicable.
+ /// The built search query.
+ private static string BuildReleaseGroupQuery(string title, string? artistName)
+ {
+ string query = $"releasegroup:\"{title.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"";
+ if (!string.IsNullOrWhiteSpace(artistName))
+ query += $" AND artist:\"{artistName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"";
+ return query;
+ }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzArtistMetadataProvider.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzArtistMetadataProvider.cs
new file mode 100644
index 00000000..30ef2ff9
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzArtistMetadataProvider.cs
@@ -0,0 +1,103 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Plugins.Contracts.Core.Metadata;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
+using Lumina.Plugins.MusicBrainz.Core.Api;
+using Lumina.Plugins.MusicBrainz.Core.Mapping;
+using Lumina.Plugins.MusicBrainz.Core.Settings;
+using System.Collections.Generic;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Core;
+
+///
+/// Provides music artist metadata from MusicBrainz by resolving lookups into artist metadata DTOs.
+///
+internal sealed class MusicBrainzArtistMetadataProvider : IMetadataProvider
+{
+ private readonly MusicBrainzHttpClient _musicBrainzHttpClient;
+ private readonly MusicBrainzSettingsProvider _settingsProvider;
+
+ ///
+ /// Gets the display name of the metadata provider.
+ ///
+ public string Name => "MusicBrainz";
+
+ ///
+ /// Gets the media library types this metadata provider supports.
+ ///
+ public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music];
+
+ ///
+ /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
+ ///
+ public bool RequiresWebAccess => true;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The HTTP client used to call the MusicBrainz web service.
+ /// The provider of the settings that configure the MusicBrainz web service requests.
+ public MusicBrainzArtistMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider)
+ {
+ _musicBrainzHttpClient = musicBrainzHttpClient;
+ _settingsProvider = settingsProvider;
+ }
+
+ ///
+ /// Searches for the metadata of the artist described by .
+ ///
+ /// The lookup describing the artist to search for.
+ /// Cancellation token that can be used to stop the execution.
+ /// The collection of artist metadata candidates found.
+ public async Task> GetSearchResultsAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
+ {
+ if (string.IsNullOrWhiteSpace(lookup.Name))
+ return [];
+
+ MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
+ IReadOnlyList artists = await _musicBrainzHttpClient
+ .SearchArtistsAsync(lookup.Name.Trim(), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
+
+ List candidates = [];
+ foreach (MusicBrainzArtistResponse artist in artists)
+ if (!string.IsNullOrWhiteSpace(artist.Name))
+ candidates.Add(MusicBrainzMapper.MapArtist(artist));
+ return candidates;
+ }
+
+ ///
+ /// Gets the metadata of the artist described by .
+ ///
+ /// The lookup describing the artist to get the metadata for.
+ /// Cancellation token that can be used to stop the execution.
+ /// The metadata of the artist, or when no artist was found.
+ public async Task GetMetadataAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
+ {
+ // A MusicBrainz identifier is the most precise lookup, so it is used first, if present.
+ if (lookup.MusicBrainzArtistId is not null)
+ {
+ MusicBrainzArtistResponse? artist = await _musicBrainzHttpClient.GetArtistAsync(lookup.MusicBrainzArtistId.Value, cancellationToken).ConfigureAwait(false);
+ return artist is null ? null : MusicBrainzMapper.MapArtist(artist);
+ }
+
+ if (string.IsNullOrWhiteSpace(lookup.Name))
+ return null;
+
+ // Without an identifier, the artist is searched by name, and the first match is resolved in full.
+ IReadOnlyList artists = await _musicBrainzHttpClient
+ .SearchArtistsAsync(lookup.Name.Trim(), 1, cancellationToken).ConfigureAwait(false);
+ MusicBrainzArtistResponse? searchResult = artists.Count > 0 ? artists[0] : null;
+ if (searchResult?.Id is null)
+ return null;
+
+ MusicBrainzArtistResponse? detailedArtist = System.Guid.TryParse(searchResult.Id, out System.Guid artistId)
+ ? await _musicBrainzHttpClient.GetArtistAsync(artistId, cancellationToken).ConfigureAwait(false)
+ : null;
+ return detailedArtist is null ? MusicBrainzMapper.MapArtist(searchResult) : MusicBrainzMapper.MapArtist(detailedArtist);
+ }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzPlugin.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzPlugin.cs
new file mode 100644
index 00000000..e582c0d9
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzPlugin.cs
@@ -0,0 +1,97 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
+using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
+using Lumina.Plugins.Contracts.Core.Plugins;
+using Lumina.Plugins.MusicBrainz.Common.DependencyInjection;
+using Lumina.Plugins.MusicBrainz.Core.Settings;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Collections.Generic;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Core;
+
+///
+/// Plugin that provides music metadata retrieval from MusicBrainz.
+///
+public sealed class MusicBrainzPlugin : IPlugin, IPluginServiceRegistrator
+{
+ ///
+ /// The unique identifier of the plugin.
+ ///
+ public static readonly Guid s_pluginId = new("f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3");
+
+ ///
+ /// Gets the unique identifier of the plugin.
+ ///
+ public Guid Id => s_pluginId;
+
+ ///
+ /// Gets the display name of the plugin.
+ ///
+ public string Name => "MusicBrainz Metadata";
+
+ ///
+ /// Gets the author of the plugin.
+ ///
+ public string Author => "Lumina";
+
+ ///
+ /// Gets the version of the plugin.
+ ///
+ public Version Version => new(1, 0, 0);
+
+ ///
+ /// Gets the description of the plugin.
+ ///
+ public string Description => "Retrieves artist, album and track metadata from MusicBrainz.";
+
+ ///
+ /// Gets the settings schema of the plugin.
+ ///
+ /// The settings descriptors of the plugin.
+ public IReadOnlyList GetSettingsSchema()
+ {
+ return
+ [
+ new PluginSettingDescriptorDto(
+ Key: MusicBrainzSettingsKeys.BASE_URL,
+ Label: "Base URL",
+ Type: PluginSettingType.Text,
+ DefaultValue: "https://musicbrainz.org/ws/2/"),
+ new PluginSettingDescriptorDto(
+ Key: MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL,
+ Label: "Allow LAN/Private Base URL",
+ Type: PluginSettingType.Boolean,
+ DefaultValue: "false"),
+ new PluginSettingDescriptorDto(
+ Key: MusicBrainzSettingsKeys.CONTACT_EMAIL,
+ Label: "Contact Email",
+ Type: PluginSettingType.Text),
+ new PluginSettingDescriptorDto(
+ Key: MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT,
+ Label: "Search Result Limit",
+ Type: PluginSettingType.Number,
+ DefaultValue: "10"),
+ new PluginSettingDescriptorDto(
+ Key: MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT,
+ Label: "Release Lookup Limit",
+ Type: PluginSettingType.Number,
+ DefaultValue: "25"),
+ new PluginSettingDescriptorDto(
+ Key: MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS,
+ Label: "Minimum Request Interval (seconds)",
+ Type: PluginSettingType.Number,
+ DefaultValue: "1.0")
+ ];
+ }
+
+ ///
+ /// Registers the services required by the plugin.
+ ///
+ /// The service collection to register the services into.
+ public void RegisterServices(IServiceCollection services)
+ {
+ services.AddMusicBrainzMetadataProviders(pluginId: Id);
+ }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzTrackMetadataProvider.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzTrackMetadataProvider.cs
new file mode 100644
index 00000000..25a0c763
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Core/MusicBrainzTrackMetadataProvider.cs
@@ -0,0 +1,270 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
+using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
+using Lumina.Plugins.Contracts.Core.Metadata;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
+using Lumina.Plugins.MusicBrainz.Core.Api;
+using Lumina.Plugins.MusicBrainz.Core.Mapping;
+using Lumina.Plugins.MusicBrainz.Core.Settings;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Core;
+
+///
+/// Provides track metadata from MusicBrainz by resolving lookups into audio metadata DTOs.
+///
+internal sealed class MusicBrainzTrackMetadataProvider : IMetadataProvider
+{
+ private readonly MusicBrainzHttpClient _musicBrainzHttpClient;
+ private readonly MusicBrainzSettingsProvider _settingsProvider;
+
+ ///
+ /// Gets the display name of the metadata provider.
+ ///
+ public string Name => "MusicBrainz";
+
+ ///
+ /// Gets the media library types this metadata provider supports.
+ ///
+ public IReadOnlyList SupportedLibraryTypes => [LibraryType.Music];
+
+ ///
+ /// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
+ ///
+ public bool RequiresWebAccess => true;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The HTTP client used to call the MusicBrainz web service.
+ /// The provider of the settings that configure the MusicBrainz web service requests.
+ public MusicBrainzTrackMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider)
+ {
+ _musicBrainzHttpClient = musicBrainzHttpClient;
+ _settingsProvider = settingsProvider;
+ }
+
+ ///
+ /// Searches for the metadata of the track described by .
+ ///
+ /// The lookup describing the track to search for.
+ /// Cancellation token that can be used to stop the execution.
+ /// The collection of track metadata candidates found.
+ public async Task> GetSearchResultsAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
+ {
+ if (string.IsNullOrWhiteSpace(lookup.Title))
+ return [];
+
+ MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
+ IReadOnlyList recordings = await _musicBrainzHttpClient
+ .SearchRecordingsAsync(BuildRecordingQuery(lookup), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
+
+ List candidates = [];
+ foreach (MusicBrainzRecordingResponse recording in recordings)
+ if (!string.IsNullOrWhiteSpace(recording.Title))
+ candidates.Add(MusicBrainzMapper.MapTrack(recording, null, null));
+ return candidates;
+ }
+
+ ///
+ /// Gets the metadata of the track described by .
+ ///
+ /// The lookup describing the track to get the metadata for.
+ /// Cancellation token that can be used to stop the execution.
+ /// The metadata of the track, or when no track was found.
+ public async Task GetMetadataAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
+ {
+ // When the release the track belongs to is known, the release is fetched once, with all its recordings, and the track is resolved from its
+ // tracklist; the recording of that response already carries its work, so every track of the release is enriched from a single request.
+ if (lookup.MusicBrainzReleaseId is not null)
+ {
+ MusicBrainzReleaseResponse? release = await _musicBrainzHttpClient.GetReleaseWithRecordingsAsync(lookup.MusicBrainzReleaseId.Value, cancellationToken).ConfigureAwait(false);
+ MusicBrainzTrackResponse? releaseTrack = release is null ? null : FindTrack(release, lookup);
+ if (releaseTrack?.Recording is not null)
+ {
+ MusicBrainzWorkResponse? inlineWork = await ResolveFallbackWorkAsync(ResolveInlineWork(releaseTrack.Recording), lookup, cancellationToken).ConfigureAwait(false);
+ return MusicBrainzMapper.MapTrack(releaseTrack.Recording, inlineWork, release);
+ }
+ }
+
+ MusicBrainzRecordingResponse? recording = null;
+
+ // A recording identifier is the most precise lookup, so it is used next, if present.
+ if (lookup.MusicBrainzRecordingId is not null)
+ recording = await _musicBrainzHttpClient.GetRecordingAsync(lookup.MusicBrainzRecordingId.Value, cancellationToken).ConfigureAwait(false);
+
+ // An ISRC lookup returns the recordings that carry the code, the first of which is then resolved in full.
+ if (recording is null && !string.IsNullOrWhiteSpace(lookup.Isrc))
+ {
+ IReadOnlyList recordings = await _musicBrainzHttpClient
+ .GetRecordingsByIsrcAsync(lookup.Isrc.Trim(), cancellationToken).ConfigureAwait(false);
+ MusicBrainzRecordingResponse? match = recordings.FirstOrDefault();
+ recording = await ResolveRecordingAsync(match, cancellationToken).ConfigureAwait(false);
+ }
+
+ // Without an identifier or a code, the track is searched, and the first match is resolved in full.
+ if (recording is null && !string.IsNullOrWhiteSpace(lookup.Title))
+ {
+ IReadOnlyList recordings = await _musicBrainzHttpClient
+ .SearchRecordingsAsync(BuildRecordingQuery(lookup), 1, cancellationToken).ConfigureAwait(false);
+ recording = await ResolveRecordingAsync(recordings.FirstOrDefault(), cancellationToken).ConfigureAwait(false);
+ }
+
+ if (recording is null)
+ return null;
+
+ MusicBrainzWorkResponse? work = await ResolveWorkAsync(recording, cancellationToken).ConfigureAwait(false);
+ work = await ResolveFallbackWorkAsync(work, lookup, cancellationToken).ConfigureAwait(false);
+ MusicBrainzReleaseResponse? resolvedRelease = await ResolveReleaseAsync(recording, cancellationToken).ConfigureAwait(false);
+ return MusicBrainzMapper.MapTrack(recording, work, resolvedRelease);
+ }
+
+ ///
+ /// Falls back to the work identifier of the tags when MusicBrainz did not link the recording to a work.
+ ///
+ /// The work resolved from MusicBrainz, if any.
+ /// The lookup describing the local track.
+ /// Cancellation token that can be used to stop the execution.
+ /// The provided work, the work resolved from the work identifier of the tags, or when neither is available.
+ private async Task ResolveFallbackWorkAsync(MusicBrainzWorkResponse? work, TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
+ {
+ // The title of the tags means the work of the tags is already complete, so it is kept as is and MusicBrainz is not queried again for it.
+ if (work is not null || lookup.MusicBrainzWorkId is not Guid musicBrainzWorkId || !string.IsNullOrWhiteSpace(lookup.WorkTitle))
+ return work;
+ return await _musicBrainzHttpClient.GetWorkAsync(musicBrainzWorkId, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Finds the track of that matches the provided , matching the recording identifier first,
+ /// then the disc and track numbers, then the title, and finally the duration.
+ ///
+ /// The release whose tracklist is searched.
+ /// The lookup describing the local track.
+ /// The matching track, or when no track matched.
+ private static MusicBrainzTrackResponse? FindTrack(MusicBrainzReleaseResponse release, TrackMetadataLookupDto lookup)
+ {
+ // The recording identifier is the most precise match, so it is used first, if present.
+ if (lookup.MusicBrainzRecordingId is Guid musicBrainzRecordingId)
+ {
+ foreach (MusicBrainzMediumResponse medium in release.Media)
+ foreach (MusicBrainzTrackResponse track in medium.Tracks)
+ if (track.Recording?.Id is string recordingId && Guid.TryParse(recordingId, out Guid trackRecordingId) && trackRecordingId == musicBrainzRecordingId)
+ return track;
+ }
+
+ List candidates = [];
+ foreach (MusicBrainzMediumResponse medium in release.Media)
+ {
+ if (lookup.DiscNumber is int discNumber && medium.Position != discNumber)
+ continue;
+ foreach (MusicBrainzTrackResponse track in medium.Tracks)
+ {
+ if (lookup.TrackNumber is int trackNumber && track.Position != trackNumber)
+ continue;
+ candidates.Add(track);
+ }
+ }
+ if (candidates.Count <= 1)
+ return candidates.Count == 1 ? candidates[0] : null;
+
+ // The disc and track numbers were not enough to single the track out, so the title is used next, and the duration breaks any remaining tie.
+ if (!string.IsNullOrWhiteSpace(lookup.Title))
+ {
+ List titledCandidates = [.. candidates.Where(candidate => string.Equals(candidate.Title, lookup.Title, StringComparison.OrdinalIgnoreCase))];
+ if (titledCandidates.Count == 1)
+ return titledCandidates[0];
+ if (titledCandidates.Count > 1)
+ candidates = titledCandidates;
+ }
+ if (candidates.Count > 1 && lookup.DurationInSeconds is int duration)
+ return candidates.OrderBy(candidate => Math.Abs((candidate.Length ?? 0) / 1000 - duration)).First();
+ return candidates[0];
+ }
+
+ ///
+ /// Gets the work the provided is a performance of, from the relations already embedded in the response.
+ ///
+ /// The recording whose work is resolved.
+ /// The embedded work, or when the recording has no work.
+ private static MusicBrainzWorkResponse? ResolveInlineWork(MusicBrainzRecordingResponse recording)
+ {
+ return recording.Relations
+ .Where(relation => string.Equals(relation.TargetType, "work", StringComparison.OrdinalIgnoreCase))
+ .Select(relation => relation.Work)
+ .FirstOrDefault(work => work is not null);
+ }
+
+ ///
+ /// Resolves the full recording of the provided search or ISRC lookup result.
+ ///
+ /// The partial recording to resolve.
+ /// Cancellation token that can be used to stop the execution.
+ /// The full recording, or when the recording could not be resolved.
+ private async Task ResolveRecordingAsync(MusicBrainzRecordingResponse? recording, CancellationToken cancellationToken)
+ {
+ if (recording?.Id is null || !Guid.TryParse(recording.Id, out Guid recordingId))
+ return recording;
+
+ return await _musicBrainzHttpClient.GetRecordingAsync(recordingId, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Resolves the work the provided recording is an instance of, together with its credited contributors.
+ ///
+ /// The recording whose work is resolved.
+ /// Cancellation token that can be used to stop the execution.
+ /// The work of the recording, or when the recording has no work.
+ private async Task ResolveWorkAsync(MusicBrainzRecordingResponse recording, CancellationToken cancellationToken)
+ {
+ string? workId = recording.Relations
+ .Where(relation => string.Equals(relation.TargetType, "work", StringComparison.OrdinalIgnoreCase))
+ .Select(relation => relation.Work?.Id)
+ .FirstOrDefault(id => !string.IsNullOrWhiteSpace(id));
+
+ if (workId is null || !Guid.TryParse(workId, out Guid parsedWorkId))
+ return recording.Relations
+ .Where(relation => string.Equals(relation.TargetType, "work", StringComparison.OrdinalIgnoreCase))
+ .Select(relation => relation.Work)
+ .FirstOrDefault(work => work is not null);
+
+ return await _musicBrainzHttpClient.GetWorkAsync(parsedWorkId, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Resolves the release the provided recording appears on, for the release level language and script.
+ ///
+ /// The recording whose release is resolved.
+ /// Cancellation token that can be used to stop the execution.
+ /// The release of the recording, or when the recording does not reference a release.
+ private async Task ResolveReleaseAsync(MusicBrainzRecordingResponse recording, CancellationToken cancellationToken)
+ {
+ string? releaseId = recording.Releases.Select(release => release.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id));
+ if (releaseId is null || !Guid.TryParse(releaseId, out Guid parsedReleaseId))
+ return null;
+
+ return await _musicBrainzHttpClient.GetReleaseAsync(parsedReleaseId, cancellationToken).ConfigureAwait(false);
+ }
+
+ ///
+ /// Builds the MusicBrainz recording search query for the provided lookup.
+ ///
+ /// The lookup describing the track.
+ /// The built search query.
+ private static string BuildRecordingQuery(TrackMetadataLookupDto lookup)
+ {
+ List parts = [];
+ if (!string.IsNullOrWhiteSpace(lookup.Title))
+ parts.Add($"recording:\"{lookup.Title.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"");
+ if (!string.IsNullOrWhiteSpace(lookup.ArtistName))
+ parts.Add($"artist:\"{lookup.ArtistName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"");
+ if (!string.IsNullOrWhiteSpace(lookup.ReleaseName))
+ parts.Add($"release:\"{lookup.ReleaseName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"");
+ return string.Join(" AND ", parts);
+ }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsKeys.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsKeys.cs
new file mode 100644
index 00000000..2ddd79e1
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsKeys.cs
@@ -0,0 +1,37 @@
+namespace Lumina.Plugins.MusicBrainz.Core.Settings;
+
+///
+/// Keys of the settings of the MusicBrainz metadata plugin, shared by the settings schema and the settings loader.
+///
+internal static class MusicBrainzSettingsKeys
+{
+ ///
+ /// The key of the setting defining the base URL of the MusicBrainz web service.
+ ///
+ internal const string BASE_URL = "BaseUrl";
+
+ ///
+ /// The key of the setting that allows the base URL to point at a private or local host, for a self hosted mirror on a local network.
+ ///
+ internal const string DOES_ALLOW_PRIVATE_BASE_URL = "DoesAllowPrivateBaseUrl";
+
+ ///
+ /// The key of the setting defining the contact email sent to the MusicBrainz API.
+ ///
+ internal const string CONTACT_EMAIL = "ContactEmail";
+
+ ///
+ /// The key of the setting defining the maximum number of results returned by a single search.
+ ///
+ internal const string SEARCH_RESULT_LIMIT = "SearchResultLimit";
+
+ ///
+ /// The key of the setting defining the maximum number of releases fetched for a single release group.
+ ///
+ internal const string RELEASE_LOOKUP_LIMIT = "ReleaseLookupLimit";
+
+ ///
+ /// The key of the setting defining the minimum interval between consecutive requests to the MusicBrainz API, in seconds.
+ ///
+ internal const string MINIMUM_REQUEST_INTERVAL_SECONDS = "MinimumRequestIntervalSeconds";
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsProvider.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsProvider.cs
new file mode 100644
index 00000000..95830b04
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsProvider.cs
@@ -0,0 +1,210 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.Contracts.Core.Plugins;
+using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Core.Settings;
+
+///
+/// Provides the runtime settings of the MusicBrainz metadata plugin, overlaying the settings persisted by the host over the configured defaults.
+///
+internal sealed class MusicBrainzSettingsProvider
+{
+ private readonly IPluginSettingsStore? _settingsStore;
+ private readonly Guid _pluginId;
+ private readonly MusicBrainzSettingsDto _defaults;
+
+ // The resolved settings are read on every request, so the resolved instance is published through Volatile to keep the common, already
+ // resolved path lock free; the gate is only needed by the first callers that race to resolve it.
+ private readonly SemaphoreSlim _gate = new(1, 1);
+ private MusicBrainzSettingsDto? _runtimeSettings;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The store of the settings persisted by the host, or when no store is available.
+ /// The unique identifier of the plugin whose settings are read.
+ /// The runtime settings with the default values and the optional configuration callback already applied.
+ public MusicBrainzSettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, MusicBrainzSettingsDto defaults)
+ {
+ _settingsStore = settingsStore;
+ _pluginId = pluginId;
+ _defaults = defaults;
+ }
+
+ ///
+ /// Gets the runtime settings of the plugin, reading and applying the settings persisted by the host on the first call.
+ ///
+ /// Cancellation token that can be used to stop the execution.
+ /// The runtime settings of the plugin.
+ public async Task GetAsync(CancellationToken cancellationToken)
+ {
+ // Lock free first check: reading through Volatile guarantees that a fully resolved instance published by another thread is observed intact.
+ MusicBrainzSettingsDto? runtimeSettings = Volatile.Read(ref _runtimeSettings);
+ if (runtimeSettings is not null)
+ return runtimeSettings;
+
+ // Only the first callers reach this point, and the gate serializes them, so the settings store is queried exactly once.
+ await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ // Second check inside the gate: another caller may have resolved the settings while this one was waiting for it.
+ runtimeSettings = Volatile.Read(ref _runtimeSettings);
+ if (runtimeSettings is null)
+ {
+ // The defaults are cloned so that applying the persisted settings never mutates the instance shared with the other scopes.
+ runtimeSettings = Clone(_defaults);
+ if (_settingsStore is not null)
+ {
+ IReadOnlyDictionary? storedSettings = await _settingsStore.GetSettingsAsync(_pluginId, cancellationToken).ConfigureAwait(false);
+ if (storedSettings is not null)
+ Apply(runtimeSettings, storedSettings);
+ }
+
+ // Publishing through Volatile makes the fully built instance visible to the lock free readers above.
+ Volatile.Write(ref _runtimeSettings, runtimeSettings);
+ }
+
+ return runtimeSettings;
+ }
+ finally
+ {
+ _gate.Release();
+ }
+ }
+
+ ///
+ /// Overlays the persisted settings onto the provided runtime settings, keeping the default values of the settings that were not persisted.
+ ///
+ /// The runtime settings onto which the persisted settings are applied.
+ /// The settings persisted by the host, keyed by setting key.
+ private static void Apply(MusicBrainzSettingsDto settings, IReadOnlyDictionary storedSettings)
+ {
+ // The private host opt-in must be resolved first, because it governs whether a private base URL is accepted below.
+ if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL, out string? doesAllowPrivateBaseUrl) &&
+ bool.TryParse(doesAllowPrivateBaseUrl, out bool doesAllowPrivateBaseUrlValue))
+ settings.DoesAllowPrivateBaseUrl = doesAllowPrivateBaseUrlValue;
+
+ if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.BASE_URL, out string? baseUrl) &&
+ Uri.TryCreate(baseUrl?.Trim(), UriKind.Absolute, out Uri? parsedBaseUrl) &&
+ (parsedBaseUrl.Scheme == Uri.UriSchemeHttp || parsedBaseUrl.Scheme == Uri.UriSchemeHttps) &&
+ (settings.DoesAllowPrivateBaseUrl || IsPublicHost(parsedBaseUrl.Host)))
+ settings.BaseUrl = parsedBaseUrl.AbsoluteUri;
+
+ if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.CONTACT_EMAIL, out string? contactEmail))
+ {
+ string? trimmedContactEmail = string.IsNullOrWhiteSpace(contactEmail) ? null : contactEmail.Trim();
+ settings.ContactEmail = trimmedContactEmail is not null && IsSafeContactEmail(trimmedContactEmail) ? trimmedContactEmail : null;
+ }
+
+ if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT, out string? searchResultLimit) &&
+ int.TryParse(searchResultLimit, NumberStyles.Integer, CultureInfo.InvariantCulture, out int searchResultLimitValue))
+ settings.SearchResultLimit = Math.Max(1, searchResultLimitValue);
+
+ if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT, out string? releaseLookupLimit) &&
+ int.TryParse(releaseLookupLimit, NumberStyles.Integer, CultureInfo.InvariantCulture, out int releaseLookupLimitValue))
+ settings.ReleaseLookupLimit = Math.Max(1, releaseLookupLimitValue);
+
+ if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, out string? minimumRequestInterval) &&
+ double.TryParse(minimumRequestInterval, NumberStyles.Float, CultureInfo.InvariantCulture, out double minimumRequestIntervalValue))
+ settings.MinimumRequestInterval = TimeSpan.FromSeconds(Math.Max(0, minimumRequestIntervalValue));
+ }
+
+ ///
+ /// Determines whether the host of the persisted base URL is a public host, so the setting cannot be used to reach a local or private service.
+ ///
+ /// The host of the persisted base URL.
+ /// when the host is public, otherwise .
+ ///
+ /// A host name is accepted as is, because it cannot be classified without resolving it, which is deliberately not done here.
+ /// A private or local host is accepted when is enabled, which supports self hosted
+ /// mirrors on a local network.
+ ///
+ private static bool IsPublicHost(string host)
+ {
+ if (string.IsNullOrWhiteSpace(host))
+ return false;
+
+ // Uri.Host surrounds an IPv6 literal with brackets, which IPAddress.TryParse does not accept.
+ string normalizedHost = host.Trim('[', ']');
+ if (string.Equals(normalizedHost, "localhost", StringComparison.OrdinalIgnoreCase))
+ return false;
+
+ if (!IPAddress.TryParse(normalizedHost, out IPAddress? address))
+ return true;
+
+ if (address.IsIPv4MappedToIPv6)
+ address = address.MapToIPv4();
+
+ if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
+ return false;
+
+ if (address.AddressFamily == AddressFamily.InterNetwork)
+ {
+ byte[] octets = address.GetAddressBytes();
+ // The unspecified, private, loopback, link local and carrier grade NAT ranges are rejected, as they are the common targets of an SSRF.
+ return octets[0] switch
+ {
+ 0 => false,
+ 10 => false,
+ 100 when octets[1] is >= 64 and <= 127 => false,
+ 127 => false,
+ 169 when octets[1] == 254 => false,
+ 172 when octets[1] is >= 16 and <= 31 => false,
+ 192 when octets[1] == 168 => false,
+ _ => true
+ };
+ }
+
+ if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal)
+ return false;
+
+ byte[] addressBytes = address.GetAddressBytes();
+ // The fc00::/7 unique local range is rejected, matching the private IPv4 ranges.
+ if ((addressBytes[0] & 0xFE) == 0xFC)
+ return false;
+
+ return true;
+ }
+
+ ///
+ /// Determines whether the persisted contact email only contains characters that are safe inside the request user agent header.
+ ///
+ /// The persisted contact email.
+ /// when the email is safe, otherwise .
+ private static bool IsSafeContactEmail(string contactEmail)
+ {
+ // The email is embedded in the User-Agent header, and an invalid character there throws when the header is parsed, which would break every request of the plugin,
+ // so anything outside a conservative email charset is rejected.
+ foreach (char character in contactEmail)
+ if (!char.IsAsciiLetterOrDigit(character) && character is not ('@' or '.' or '_' or '-' or '+'))
+ return false;
+ return true;
+ }
+
+ ///
+ /// Creates a copy of the given runtime settings.
+ ///
+ /// The runtime settings to copy.
+ /// A copy of the given runtime settings.
+ private static MusicBrainzSettingsDto Clone(MusicBrainzSettingsDto source)
+ {
+ return new MusicBrainzSettingsDto
+ {
+ BaseUrl = source.BaseUrl,
+ DoesAllowPrivateBaseUrl = source.DoesAllowPrivateBaseUrl,
+ UserAgent = source.UserAgent,
+ ContactEmail = source.ContactEmail,
+ SearchResultLimit = source.SearchResultLimit,
+ ReleaseLookupLimit = source.ReleaseLookupLimit,
+ MinimumRequestInterval = source.MinimumRequestInterval
+ };
+ }
+}
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Lumina.Plugins.MusicBrainz.csproj b/plugins/Lumina.Plugins.MusicBrainz/Lumina.Plugins.MusicBrainz.csproj
new file mode 100644
index 00000000..bed7d79c
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Lumina.Plugins.MusicBrainz.csproj
@@ -0,0 +1,34 @@
+
+
+ net10.0
+ disable
+ enable
+ $(SolutionDir)..\bin\plugins\
+ false
+ true
+ true
+ $(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ false
+ runtime
+
+
+
+
+
+
+
diff --git a/plugins/Lumina.Plugins.MusicBrainz/Properties/AssemblyInfo.cs b/plugins/Lumina.Plugins.MusicBrainz/Properties/AssemblyInfo.cs
new file mode 100644
index 00000000..e4c7f52a
--- /dev/null
+++ b/plugins/Lumina.Plugins.MusicBrainz/Properties/AssemblyInfo.cs
@@ -0,0 +1,6 @@
+using System.Runtime.CompilerServices;
+
+[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.UnitTests")]
+[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.Fixtures")]
+[assembly: InternalsVisibleTo("Lumina.Presentation.Api.SecurityTests")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAliasResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAliasResponseFixture.cs
new file mode 100644
index 00000000..bf3e9d50
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAliasResponseFixture.cs
@@ -0,0 +1,80 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzAliasResponseFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The name of the alias.
+ /// Whether the name should be included, or forced to .
+ /// Optional. The sort name of the alias.
+ /// Whether the sort name should be included, or forced to .
+ /// Optional. The type of the alias.
+ /// Whether the type should be included, or forced to .
+ /// Optional. The locale the alias is used in.
+ /// Whether the locale should be included, or forced to .
+ /// Optional. Whether this is the primary alias.
+ /// Whether the primary flag should be included, or forced to .
+ /// Optional. The begin date of the alias.
+ /// Whether the begin date should be included, or forced to .
+ /// Optional. The end date of the alias.
+ /// Whether the end date should be included, or forced to .
+ /// Optional. Whether the alias has ended.
+ /// Whether the ended flag should be included, or forced to .
+ /// A configured instance.
+ public MusicBrainzAliasResponse Create(
+ string? name = null,
+ bool includeName = true,
+ string? sortName = null,
+ bool includeSortName = true,
+ string? type = null,
+ bool includeType = true,
+ string? locale = null,
+ bool includeLocale = true,
+ bool? isPrimary = null,
+ bool includePrimary = true,
+ string? begin = null,
+ bool includeBegin = true,
+ string? end = null,
+ bool includeEnd = true,
+ bool? isEnded = null,
+ bool includeEnded = true)
+ {
+ return new MusicBrainzAliasResponse
+ {
+ Name = includeName ? name ?? _faker.Name.FullName() : null,
+ SortName = includeSortName ? sortName ?? _faker.Name.FullName() : null,
+ Type = includeType ? type ?? _faker.PickRandom("Artist name", "Legal name") : null,
+ Locale = includeLocale ? locale ?? _faker.PickRandom("en", "de", "fr") : null,
+ IsPrimary = includePrimary ? isPrimary ?? _faker.Random.Bool() : null,
+ Begin = includeBegin ? begin ?? _faker.Date.Past(50).ToString("yyyy-MM-dd") : null,
+ End = includeEnd ? end ?? _faker.Date.Past(5).ToString("yyyy-MM-dd") : null,
+ IsEnded = includeEnded ? isEnded ?? _faker.Random.Bool() : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAreaResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAreaResponseFixture.cs
new file mode 100644
index 00000000..865b2068
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzAreaResponseFixture.cs
@@ -0,0 +1,71 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzAreaResponseFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The MusicBrainz identifier of the area.
+ /// Whether the identifier should be included, or forced to .
+ /// Optional. The name of the area.
+ /// Whether the name should be included, or forced to .
+ /// Optional. The sort name of the area.
+ /// Whether the sort name should be included, or forced to .
+ /// Optional. The disambiguation comment of the area.
+ /// Whether the disambiguation should be included, or forced to .
+ /// Optional. The MusicBrainz type of the area.
+ /// Whether the type should be included, or forced to .
+ /// Optional. The ISO 3166-1 codes of the area.
+ /// Optional. The ISO 3166-2 codes of the area.
+ /// A configured instance.
+ public MusicBrainzAreaResponse Create(
+ string? id = null,
+ bool includeId = true,
+ string? name = null,
+ bool includeName = true,
+ string? sortName = null,
+ bool includeSortName = true,
+ string? disambiguation = null,
+ bool includeDisambiguation = true,
+ string? type = null,
+ bool includeType = true,
+ List? iso3166Part1Codes = null,
+ List? iso3166Part2Codes = null)
+ {
+ return new MusicBrainzAreaResponse
+ {
+ Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
+ Name = includeName ? name ?? _faker.Address.Country() : null,
+ SortName = includeSortName ? sortName ?? _faker.Address.Country() : null,
+ Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
+ Type = includeType ? type ?? _faker.PickRandom("Country", "City", "Area") : null,
+ Iso3166Part1Codes = iso3166Part1Codes ?? [_faker.Address.CountryCode()],
+ Iso3166Part2Codes = iso3166Part2Codes ?? [_faker.Random.String2(5, "ABCDEFGHIJKLMNOPQRSTUVWXYZ")]
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseFixture.cs
new file mode 100644
index 00000000..a813a61b
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseFixture.cs
@@ -0,0 +1,57 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzArtistCreditResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MusicBrainzArtistResponseFixture _musicBrainzArtistResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The credited name of the artist.
+ /// Whether the name should be included, or forced to .
+ /// Optional. The join phrase that follows the credit.
+ /// Whether the join phrase should be included, or forced to .
+ /// Optional. The artist the credit refers to.
+ /// Whether the artist should be included, or forced to .
+ /// A configured instance.
+ public MusicBrainzArtistCreditResponse Create(
+ string? name = null,
+ bool includeName = true,
+ string? joinPhrase = null,
+ bool includeJoinPhrase = true,
+ MusicBrainzArtistResponse? artist = null,
+ bool includeArtist = true)
+ {
+ string? resolvedName = includeName ? name ?? _faker.Name.FullName() : null;
+ return new MusicBrainzArtistCreditResponse
+ {
+ Name = resolvedName,
+ JoinPhrase = includeJoinPhrase ? joinPhrase ?? _faker.PickRandom(" & ", " feat. ", ", ") : null,
+ Artist = includeArtist ? artist ?? _musicBrainzArtistResponseFixture.Create(name: resolvedName) : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistResponseFixture.cs
new file mode 100644
index 00000000..aac8125e
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistResponseFixture.cs
@@ -0,0 +1,124 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzArtistResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MusicBrainzAreaResponseFixture _musicBrainzAreaResponseFixture = new();
+ private readonly MusicBrainzAliasResponseFixture _musicBrainzAliasResponseFixture = new();
+ private readonly MusicBrainzRelationResponseFixture _musicBrainzRelationResponseFixture = new();
+ private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new();
+ private readonly MusicBrainzLifeSpanResponseFixture _musicBrainzLifeSpanResponseFixture = new();
+ private readonly MusicBrainzRatingResponseFixture _musicBrainzRatingResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The MusicBrainz identifier of the artist.
+ /// Whether the identifier should be included, or forced to .
+ /// Optional. The name of the artist.
+ /// Whether the name should be included, or forced to .
+ /// Optional. The sort name of the artist.
+ /// Whether the sort name should be included, or forced to .
+ /// Optional. The disambiguation comment of the artist.
+ /// Whether the disambiguation should be included, or forced to .
+ /// Optional. The MusicBrainz type of the artist.
+ /// Whether the type should be included, or forced to .
+ /// Optional. The gender of the artist.
+ /// Whether the gender should be included, or forced to .
+ /// Optional. The ISO 3166-1 alpha-2 code of the country of the artist.
+ /// Whether the country should be included, or forced to .
+ /// Optional. The area the artist is primarily identified with.
+ /// Whether the area should be included, or forced to .
+ /// Optional. The area the artist began in.
+ /// Whether the begin area should be included, or forced to .
+ /// Optional. The area the artist ended in.
+ /// Whether the end area should be included, or forced to .
+ /// Optional. The life span of the artist.
+ /// Whether the life span should be included, or forced to .
+ /// Optional. The ISNI codes of the artist.
+ /// Optional. The IPI codes of the artist.
+ /// Optional. The alternative names of the artist.
+ /// Optional. The tags of the artist.
+ /// Optional. The genres of the artist.
+ /// Optional. The relationships of the artist to other entities.
+ /// Optional. The aggregated rating of the artist.
+ /// Whether the rating should be included, or forced to .
+ /// A configured instance.
+ public MusicBrainzArtistResponse Create(
+ string? id = null,
+ bool includeId = true,
+ string? name = null,
+ bool includeName = true,
+ string? sortName = null,
+ bool includeSortName = true,
+ string? disambiguation = null,
+ bool includeDisambiguation = true,
+ string? type = null,
+ bool includeType = true,
+ string? gender = null,
+ bool includeGender = true,
+ string? country = null,
+ bool includeCountry = true,
+ MusicBrainzAreaResponse? area = null,
+ bool includeArea = false,
+ MusicBrainzAreaResponse? beginArea = null,
+ bool includeBeginArea = false,
+ MusicBrainzAreaResponse? endArea = null,
+ bool includeEndArea = false,
+ MusicBrainzLifeSpanResponse? lifeSpan = null,
+ bool includeLifeSpan = false,
+ List? isnis = null,
+ List? ipis = null,
+ List? aliases = null,
+ List? tags = null,
+ List? genres = null,
+ List? relations = null,
+ MusicBrainzRatingResponse? rating = null,
+ bool includeRating = false)
+ {
+ return new MusicBrainzArtistResponse
+ {
+ Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
+ Name = includeName ? name ?? _faker.Name.FullName() : null,
+ SortName = includeSortName ? sortName ?? _faker.Name.FullName() : null,
+ Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
+ Type = includeType ? type ?? _faker.PickRandom("Person", "Group", "Orchestra") : null,
+ Gender = includeGender ? gender ?? _faker.PickRandom("Male", "Female") : null,
+ Country = includeCountry ? country ?? _faker.Address.CountryCode() : null,
+ Area = includeArea ? area ?? _musicBrainzAreaResponseFixture.Create() : null,
+ BeginArea = includeBeginArea ? beginArea ?? _musicBrainzAreaResponseFixture.Create() : null,
+ EndArea = includeEndArea ? endArea ?? _musicBrainzAreaResponseFixture.Create() : null,
+ LifeSpan = includeLifeSpan ? lifeSpan ?? _musicBrainzLifeSpanResponseFixture.Create() : null,
+ Isnis = isnis ?? [_faker.Random.String2(16, "0123456789")],
+ Ipis = ipis ?? [_faker.Random.String2(11, "0123456789")],
+ Aliases = aliases ?? [.. _musicBrainzAliasResponseFixture.CreateMany(2)],
+ Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
+ Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
+ Relations = relations ?? [.. _musicBrainzRelationResponseFixture.CreateMany(2)],
+ Rating = includeRating ? rating ?? _musicBrainzRatingResponseFixture.Create() : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseFixture.cs
new file mode 100644
index 00000000..41612d35
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseFixture.cs
@@ -0,0 +1,51 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzArtistSearchResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MusicBrainzArtistResponseFixture _musicBrainzArtistResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The total number of matching artists.
+ /// Optional. The offset of the returned artists.
+ /// Optional. The matching artists.
+ /// A configured instance.
+ public MusicBrainzArtistSearchResponse Create(
+ int? count = null,
+ int? offset = null,
+ List? artists = null)
+ {
+ List resolvedArtists = artists ?? [.. _musicBrainzArtistResponseFixture.CreateMany(2)];
+ return new MusicBrainzArtistSearchResponse
+ {
+ Count = count ?? resolvedArtists.Count,
+ Offset = offset ?? _faker.Random.Int(0, 100),
+ Artists = resolvedArtists
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseFixture.cs
new file mode 100644
index 00000000..d6e16399
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseFixture.cs
@@ -0,0 +1,51 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzLabelInfoResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MusicBrainzLabelResponseFixture _musicBrainzLabelResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The catalog number assigned by the label.
+ /// Whether the catalog number should be included, or forced to .
+ /// Optional. The label that issued the release.
+ /// Whether the label should be included, or forced to .
+ /// A configured instance.
+ public MusicBrainzLabelInfoResponse Create(
+ string? catalogNumber = null,
+ bool includeCatalogNumber = true,
+ MusicBrainzLabelResponse? label = null,
+ bool includeLabel = true)
+ {
+ return new MusicBrainzLabelInfoResponse
+ {
+ CatalogNumber = includeCatalogNumber ? catalogNumber ?? _faker.Random.AlphaNumeric(8).ToUpperInvariant() : null,
+ Label = includeLabel ? label ?? _musicBrainzLabelResponseFixture.Create() : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelResponseFixture.cs
new file mode 100644
index 00000000..438c0390
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLabelResponseFixture.cs
@@ -0,0 +1,60 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzLabelResponseFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The MusicBrainz identifier of the label.
+ /// Whether the identifier should be included, or forced to .
+ /// Optional. The name of the label.
+ /// Whether the name should be included, or forced to .
+ /// Optional. The disambiguation comment of the label.
+ /// Whether the disambiguation should be included, or forced to .
+ /// Optional. The label code of the label.
+ /// Whether the label code should be included, or forced to .
+ /// A configured instance.
+ public MusicBrainzLabelResponse Create(
+ string? id = null,
+ bool includeId = true,
+ string? name = null,
+ bool includeName = true,
+ string? disambiguation = null,
+ bool includeDisambiguation = true,
+ int? labelCode = null,
+ bool includeLabelCode = true)
+ {
+ return new MusicBrainzLabelResponse
+ {
+ Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
+ Name = includeName ? name ?? _faker.Company.CompanyName() : null,
+ Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
+ LabelCode = includeLabelCode ? labelCode ?? _faker.Random.Int(1, 9999) : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseFixture.cs
new file mode 100644
index 00000000..b5bb5346
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseFixture.cs
@@ -0,0 +1,55 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzLifeSpanResponseFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The begin date of the life span.
+ /// Whether the begin date should be included, or forced to .
+ /// Optional. The end date of the life span.
+ /// Whether the end date should be included, or forced to .
+ /// Optional. Whether the life span has ended.
+ /// Whether the ended flag should be included, or forced to .
+ /// A configured instance.
+ public MusicBrainzLifeSpanResponse Create(
+ string? begin = null,
+ bool includeBegin = true,
+ string? end = null,
+ bool includeEnd = true,
+ bool? isEnded = null,
+ bool includeEnded = true)
+ {
+ return new MusicBrainzLifeSpanResponse
+ {
+ Begin = includeBegin ? begin ?? _faker.Date.Past(60).ToString("yyyy-MM-dd") : null,
+ End = includeEnd ? end ?? _faker.Date.Past(5).ToString("yyyy-MM-dd") : null,
+ IsEnded = includeEnded ? isEnded ?? _faker.Random.Bool() : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzMediumResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzMediumResponseFixture.cs
new file mode 100644
index 00000000..55ca6bf6
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzMediumResponseFixture.cs
@@ -0,0 +1,61 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzMediumResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MusicBrainzTrackResponseFixture _musicBrainzTrackResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The position of the medium within its release.
+ /// Optional. The title of the medium.
+ /// Whether the title should be included, or forced to .
+ /// Optional. The format of the medium.
+ /// Whether the format should be included, or forced to .
+ /// Optional. The number of tracks of the medium.
+ /// Optional. The tracks of the medium.
+ /// A configured instance.
+ public MusicBrainzMediumResponse Create(
+ int? position = null,
+ string? title = null,
+ bool includeTitle = true,
+ string? format = null,
+ bool includeFormat = true,
+ int? trackCount = null,
+ List? tracks = null)
+ {
+ List resolvedTracks = tracks ?? [.. _musicBrainzTrackResponseFixture.CreateMany(2)];
+ return new MusicBrainzMediumResponse
+ {
+ Position = position ?? _faker.Random.Int(1, 4),
+ Title = includeTitle ? title ?? _faker.Lorem.Sentence(2) : null,
+ Format = includeFormat ? format ?? _faker.PickRandom("CD", "Vinyl", "Digital Media") : null,
+ TrackCount = trackCount ?? resolvedTracks.Count,
+ Tracks = resolvedTracks
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(index => Create(position: index + 1))];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRatingResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRatingResponseFixture.cs
new file mode 100644
index 00000000..4dd684ff
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRatingResponseFixture.cs
@@ -0,0 +1,50 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzRatingResponseFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The average rating value.
+ /// Whether the value should be included, or forced to .
+ /// Optional. The number of votes that contributed to the rating.
+ /// Whether the votes count should be included, or forced to .
+ /// A configured instance.
+ public MusicBrainzRatingResponse Create(
+ decimal? value = null,
+ bool includeValue = true,
+ int? votesCount = null,
+ bool includeVotesCount = true)
+ {
+ return new MusicBrainzRatingResponse
+ {
+ Value = includeValue ? value ?? _faker.Random.Decimal(1m, 5m) : null,
+ VotesCount = includeVotesCount ? votesCount ?? _faker.Random.Int(1, 500) : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseFixture.cs
new file mode 100644
index 00000000..5556e4e5
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseFixture.cs
@@ -0,0 +1,41 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzRecordingListResponseFixture
+{
+ private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The recordings that carry the looked up ISRC.
+ /// A configured instance.
+ public MusicBrainzRecordingListResponse Create(List? recordings = null)
+ {
+ return new MusicBrainzRecordingListResponse
+ {
+ Recordings = recordings ?? [.. _musicBrainzRecordingResponseFixture.CreateMany(2)]
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseFixture.cs
new file mode 100644
index 00000000..07a2e22a
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseFixture.cs
@@ -0,0 +1,98 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+/// The releases of the recording default to an empty list, because a recording embedded in a release does not carry them.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzRecordingResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MusicBrainzArtistCreditResponseFixture _musicBrainzArtistCreditResponseFixture = new();
+ private readonly MusicBrainzRelationResponseFixture _musicBrainzRelationResponseFixture = new();
+ private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new();
+ private readonly MusicBrainzRatingResponseFixture _musicBrainzRatingResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The MusicBrainz identifier of the recording.
+ /// Whether the identifier should be included, or forced to .
+ /// Optional. The title of the recording.
+ /// Whether the title should be included, or forced to .
+ /// Optional. The disambiguation comment of the recording.
+ /// Whether the disambiguation should be included, or forced to .
+ /// Optional. The length of the recording in milliseconds.
+ /// Whether the length should be included, or forced to .
+ /// Optional. Whether the recording is a video recording.
+ /// Whether the video flag should be included, or forced to .
+ /// Optional. The date the recording was first released.
+ /// Whether the first release date should be included, or forced to .
+ /// Optional. The artist credit of the recording.
+ /// Optional. The ISRCs of the recording.
+ /// Optional. The releases the recording appears on.
+ /// Optional. The tags of the recording.
+ /// Optional. The genres of the recording.
+ /// Optional. The relationships of the recording to other entities.
+ /// Optional. The aggregated rating of the recording.
+ /// Whether the rating should be included, or forced to .
+ /// A configured instance.
+ public MusicBrainzRecordingResponse Create(
+ string? id = null,
+ bool includeId = true,
+ string? title = null,
+ bool includeTitle = true,
+ string? disambiguation = null,
+ bool includeDisambiguation = true,
+ long? length = null,
+ bool includeLength = true,
+ bool? isVideo = null,
+ bool includeVideo = true,
+ string? firstReleaseDate = null,
+ bool includeFirstReleaseDate = true,
+ List? artistCredit = null,
+ List? isrcs = null,
+ List? releases = null,
+ List? tags = null,
+ List? genres = null,
+ List? relations = null,
+ MusicBrainzRatingResponse? rating = null,
+ bool includeRating = false)
+ {
+ return new MusicBrainzRecordingResponse
+ {
+ Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
+ Title = includeTitle ? title ?? _faker.Lorem.Sentence(3) : null,
+ Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
+ Length = includeLength ? length ?? _faker.Random.Long(30_000, 600_000) : null,
+ IsVideo = includeVideo ? isVideo ?? _faker.Random.Bool() : null,
+ FirstReleaseDate = includeFirstReleaseDate ? firstReleaseDate ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null,
+ ArtistCredit = artistCredit ?? [.. _musicBrainzArtistCreditResponseFixture.CreateMany(2)],
+ Isrcs = isrcs ?? [$"US{_faker.Random.AlphaNumeric(10).ToUpperInvariant()}"],
+ Releases = releases ?? [],
+ Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
+ Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
+ Relations = relations ?? [.. _musicBrainzRelationResponseFixture.CreateMany(2)],
+ Rating = includeRating ? rating ?? _musicBrainzRatingResponseFixture.Create() : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseFixture.cs
new file mode 100644
index 00000000..a2f2750f
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseFixture.cs
@@ -0,0 +1,51 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzRecordingSearchResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The total number of matching recordings.
+ /// Optional. The offset of the returned recordings.
+ /// Optional. The matching recordings.
+ /// A configured instance.
+ public MusicBrainzRecordingSearchResponse Create(
+ int? count = null,
+ int? offset = null,
+ List? recordings = null)
+ {
+ List resolvedRecordings = recordings ?? [.. _musicBrainzRecordingResponseFixture.CreateMany(2)];
+ return new MusicBrainzRecordingSearchResponse
+ {
+ Count = count ?? resolvedRecordings.Count,
+ Offset = offset ?? _faker.Random.Int(0, 100),
+ Recordings = resolvedRecordings
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRelationResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRelationResponseFixture.cs
new file mode 100644
index 00000000..b8e7afea
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzRelationResponseFixture.cs
@@ -0,0 +1,85 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+/// The nested artist, work and url targets are optional, because a relation usually targets only one of them.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzRelationResponseFixture
+{
+ private readonly Faker _faker = new();
+
+ // The artist and work fixtures each compose a relation fixture of their own, so holding them eagerly here would recurse forever; they are
+ // therefore created on first use. The URL fixture has no such dependency, so it is held directly.
+ private readonly Lazy _musicBrainzArtistResponseFixture = new(() => new MusicBrainzArtistResponseFixture());
+ private readonly Lazy _musicBrainzWorkResponseFixture = new(() => new MusicBrainzWorkResponseFixture());
+ private readonly MusicBrainzUrlResponseFixture _musicBrainzUrlResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The type of the relationship.
+ /// Whether the type should be included, or forced to .
+ /// Optional. The MusicBrainz identifier of the type of the relationship.
+ /// Whether the type identifier should be included, or forced to .
+ /// Optional. The direction of the relationship.
+ /// Whether the direction should be included, or forced to .
+ /// Optional. The type of the entity the relationship targets.
+ /// Whether the target type should be included, or forced to .
+ /// Optional. The artist the relationship targets.
+ /// Whether the artist should be included, or forced to .
+ /// Optional. The work the relationship targets.
+ /// Whether the work should be included, or forced to .
+ /// Optional. The URL the relationship targets.
+ /// Whether the URL should be included, or forced to .
+ /// Optional. The attributes of the relationship.
+ /// A configured instance.
+ public MusicBrainzRelationResponse Create(
+ string? type = null,
+ bool includeType = true,
+ string? typeId = null,
+ bool includeTypeId = true,
+ string? direction = null,
+ bool includeDirection = true,
+ string? targetType = null,
+ bool includeTargetType = true,
+ MusicBrainzArtistResponse? artist = null,
+ bool includeArtist = false,
+ MusicBrainzWorkResponse? work = null,
+ bool includeWork = false,
+ MusicBrainzUrlResponse? url = null,
+ bool includeUrl = false,
+ List? attributes = null)
+ {
+ return new MusicBrainzRelationResponse
+ {
+ Type = includeType ? type ?? _faker.PickRandom("producer", "composer", "performer") : null,
+ TypeId = includeTypeId ? typeId ?? Guid.NewGuid().ToString() : null,
+ Direction = includeDirection ? direction ?? "backward" : null,
+ TargetType = includeTargetType ? targetType ?? "artist" : null,
+ Artist = includeArtist ? artist ?? _musicBrainzArtistResponseFixture.Value.Create() : null,
+ Work = includeWork ? work ?? _musicBrainzWorkResponseFixture.Value.Create() : null,
+ Url = includeUrl ? url ?? _musicBrainzUrlResponseFixture.Create() : null,
+ Attributes = attributes ?? []
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseFixture.cs
new file mode 100644
index 00000000..490996ec
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseFixture.cs
@@ -0,0 +1,51 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzReleaseBrowseResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MusicBrainzReleaseResponseFixture _musicBrainzReleaseResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The releases returned by the browse request.
+ /// Optional. The total number of releases linked to the browsed entity.
+ /// Optional. The offset of the returned releases.
+ /// A configured instance.
+ public MusicBrainzReleaseBrowseResponse Create(
+ List? releases = null,
+ int? releaseCount = null,
+ int? releaseOffset = null)
+ {
+ List resolvedReleases = releases ?? [.. _musicBrainzReleaseResponseFixture.CreateMany(2)];
+ return new MusicBrainzReleaseBrowseResponse
+ {
+ Releases = resolvedReleases,
+ ReleaseCount = releaseCount ?? resolvedReleases.Count,
+ ReleaseOffset = releaseOffset ?? _faker.Random.Int(0, 100)
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseFixture.cs
new file mode 100644
index 00000000..3817e8b9
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseFixture.cs
@@ -0,0 +1,51 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzReleaseEventResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MusicBrainzAreaResponseFixture _musicBrainzAreaResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The date of the release event.
+ /// Whether the date should be included, or forced to .
+ /// Optional. The area of the release event.
+ /// Whether the area should be included, or forced to .
+ /// A configured instance.
+ public MusicBrainzReleaseEventResponse Create(
+ string? date = null,
+ bool includeDate = true,
+ MusicBrainzAreaResponse? area = null,
+ bool includeArea = true)
+ {
+ return new MusicBrainzReleaseEventResponse
+ {
+ Date = includeDate ? date ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null,
+ Area = includeArea ? area ?? _musicBrainzAreaResponseFixture.Create() : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseFixture.cs
new file mode 100644
index 00000000..30cf9ff3
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseFixture.cs
@@ -0,0 +1,89 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+/// The releases of the release group default to an empty list, because they are only returned by a dedicated browse request.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzReleaseGroupResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MusicBrainzArtistCreditResponseFixture _musicBrainzArtistCreditResponseFixture = new();
+ private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new();
+ private readonly MusicBrainzRatingResponseFixture _musicBrainzRatingResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The MusicBrainz identifier of the release group.
+ /// Whether the identifier should be included, or forced to .
+ /// Optional. The title of the release group.
+ /// Whether the title should be included, or forced to .
+ /// Optional. The disambiguation comment of the release group.
+ /// Whether the disambiguation should be included, or forced to .
+ /// Optional. The primary type of the release group.
+ /// Whether the primary type should be included, or forced to .
+ /// Optional. The secondary types of the release group.
+ /// Optional. The date the release group was first released.
+ /// Whether the first release date should be included, or forced to .
+ /// Optional. The artist credit of the release group.
+ /// Optional. The releases of the release group.
+ /// Optional. The tags of the release group.
+ /// Optional. The genres of the release group.
+ /// Optional. The aggregated rating of the release group.
+ /// Whether the rating should be included, or forced to .
+ /// A configured instance.
+ public MusicBrainzReleaseGroupResponse Create(
+ string? id = null,
+ bool includeId = true,
+ string? title = null,
+ bool includeTitle = true,
+ string? disambiguation = null,
+ bool includeDisambiguation = true,
+ string? primaryType = null,
+ bool includePrimaryType = true,
+ List? secondaryTypes = null,
+ string? firstReleaseDate = null,
+ bool includeFirstReleaseDate = true,
+ List? artistCredit = null,
+ List? releases = null,
+ List? tags = null,
+ List? genres = null,
+ MusicBrainzRatingResponse? rating = null,
+ bool includeRating = false)
+ {
+ return new MusicBrainzReleaseGroupResponse
+ {
+ Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
+ Title = includeTitle ? title ?? _faker.Commerce.ProductName() : null,
+ Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
+ PrimaryType = includePrimaryType ? primaryType ?? _faker.PickRandom("Album", "Single", "EP") : null,
+ SecondaryTypes = secondaryTypes ?? [],
+ FirstReleaseDate = includeFirstReleaseDate ? firstReleaseDate ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null,
+ ArtistCredit = artistCredit ?? [.. _musicBrainzArtistCreditResponseFixture.CreateMany(2)],
+ Releases = releases ?? [],
+ Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
+ Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
+ Rating = includeRating ? rating ?? _musicBrainzRatingResponseFixture.Create() : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseFixture.cs
new file mode 100644
index 00000000..cb1afb9a
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseFixture.cs
@@ -0,0 +1,51 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzReleaseGroupSearchResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MusicBrainzReleaseGroupResponseFixture _musicBrainzReleaseGroupResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The total number of matching release groups.
+ /// Optional. The offset of the returned release groups.
+ /// Optional. The matching release groups.
+ /// A configured instance.
+ public MusicBrainzReleaseGroupSearchResponse Create(
+ int? count = null,
+ int? offset = null,
+ List? releaseGroups = null)
+ {
+ List resolvedReleaseGroups = releaseGroups ?? [.. _musicBrainzReleaseGroupResponseFixture.CreateMany(2)];
+ return new MusicBrainzReleaseGroupSearchResponse
+ {
+ Count = count ?? resolvedReleaseGroups.Count,
+ Offset = offset ?? _faker.Random.Int(0, 100),
+ ReleaseGroups = resolvedReleaseGroups
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseFixture.cs
new file mode 100644
index 00000000..11da2c2f
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzReleaseResponseFixture.cs
@@ -0,0 +1,123 @@
+#region ========================================================================= USING =====================================================================================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzReleaseResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MusicBrainzArtistCreditResponseFixture _musicBrainzArtistCreditResponseFixture = new();
+ private readonly MusicBrainzReleaseGroupResponseFixture _musicBrainzReleaseGroupResponseFixture = new();
+ private readonly MusicBrainzLabelInfoResponseFixture _musicBrainzLabelInfoResponseFixture = new();
+ private readonly MusicBrainzMediumResponseFixture _musicBrainzMediumResponseFixture = new();
+ private readonly MusicBrainzReleaseEventResponseFixture _musicBrainzReleaseEventResponseFixture = new();
+ private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new();
+ private readonly MusicBrainzTextRepresentationResponseFixture _musicBrainzTextRepresentationResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The MusicBrainz identifier of the release.
+ /// Whether the identifier should be included, or forced to .
+ /// Optional. The title of the release.
+ /// Whether the title should be included, or forced to .
+ /// Optional. The disambiguation comment of the release.
+ /// Whether the disambiguation should be included, or forced to .
+ /// Optional. The status of the release.
+ /// Whether the status should be included, or forced to .
+ /// Optional. The date the release was issued.
+ /// Whether the date should be included, or forced to .
+ /// Optional. The ISO 3166-1 alpha-2 code of the country the release was issued in.
+ /// Whether the country should be included, or forced to .
+ /// Optional. The release events of the release.
+ /// Optional. The barcode of the release.
+ /// Whether the barcode should be included, or forced to .
+ /// Optional. The outermost packaging of the release.
+ /// Whether the packaging should be included, or forced to .
+ /// Optional. The language and script of the titles of the release.
+ /// Whether the text representation should be included, or forced to .
+ /// Optional. The artist credit of the release.
+ /// Optional. The release group the release belongs to.
+ /// Whether the release group should be included, or forced to .
+ /// Optional. The label information of the release.
+ /// Optional. The media of the release.
+ /// Optional. The ASIN of the release.
+ /// Whether the ASIN should be included, or forced to .
+ /// Optional. The tags of the release.
+ /// Optional. The genres of the release.
+ /// Optional. The relationships of the release to other entities.
+ /// A configured instance.
+ public MusicBrainzReleaseResponse Create(
+ string? id = null,
+ bool includeId = true,
+ string? title = null,
+ bool includeTitle = true,
+ string? disambiguation = null,
+ bool includeDisambiguation = true,
+ string? status = null,
+ bool includeStatus = true,
+ string? date = null,
+ bool includeDate = true,
+ string? country = null,
+ bool includeCountry = true,
+ List? releaseEvents = null,
+ string? barcode = null,
+ bool includeBarcode = true,
+ string? packaging = null,
+ bool includePackaging = true,
+ MusicBrainzTextRepresentationResponse? textRepresentation = null,
+ bool includeTextRepresentation = true,
+ List? artistCredit = null,
+ MusicBrainzReleaseGroupResponse? releaseGroup = null,
+ bool includeReleaseGroup = true,
+ List? labelInfo = null,
+ List? media = null,
+ string? asin = null,
+ bool includeAsin = true,
+ List? tags = null,
+ List? genres = null,
+ List? relations = null)
+ {
+ return new MusicBrainzReleaseResponse
+ {
+ Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
+ Title = includeTitle ? title ?? _faker.Commerce.ProductName() : null,
+ Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
+ Status = includeStatus ? status ?? _faker.PickRandom("Official", "Promotion", "Bootleg") : null,
+ Date = includeDate ? date ?? _faker.Date.Past(40).ToString("yyyy-MM-dd") : null,
+ Country = includeCountry ? country ?? _faker.Address.CountryCode() : null,
+ ReleaseEvents = releaseEvents ?? [.. _musicBrainzReleaseEventResponseFixture.CreateMany(1)],
+ Barcode = includeBarcode ? barcode ?? _faker.Random.AlphaNumeric(12) : null,
+ Packaging = includePackaging ? packaging ?? _faker.PickRandom("Jewel Case", "Digipak") : null,
+ TextRepresentation = includeTextRepresentation ? textRepresentation ?? _musicBrainzTextRepresentationResponseFixture.Create() : null,
+ ArtistCredit = artistCredit ?? [.. _musicBrainzArtistCreditResponseFixture.CreateMany(2)],
+ ReleaseGroup = includeReleaseGroup ? releaseGroup ?? _musicBrainzReleaseGroupResponseFixture.Create() : null,
+ LabelInfo = labelInfo ?? [.. _musicBrainzLabelInfoResponseFixture.CreateMany(1)],
+ Media = media ?? [.. _musicBrainzMediumResponseFixture.CreateMany(1)],
+ Asin = includeAsin ? asin ?? _faker.Random.AlphaNumeric(10) : null,
+ Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
+ Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
+ Relations = relations ?? []
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTagResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTagResponseFixture.cs
new file mode 100644
index 00000000..d3eb53cc
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTagResponseFixture.cs
@@ -0,0 +1,58 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzTagResponseFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The MusicBrainz identifier of a genre tag.
+ /// Whether the identifier should be included, or forced to .
+ /// Optional. The name of the tag.
+ /// Whether the name should be included, or forced to .
+ /// Optional. The disambiguation comment of a genre tag.
+ /// Whether the disambiguation should be included, or forced to .
+ /// Optional. The number of votes the tag received.
+ /// A configured instance.
+ public MusicBrainzTagResponse Create(
+ string? id = null,
+ bool includeId = true,
+ string? name = null,
+ bool includeName = true,
+ string? disambiguation = null,
+ bool includeDisambiguation = true,
+ int? count = null)
+ {
+ return new MusicBrainzTagResponse
+ {
+ Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
+ Name = includeName ? name ?? _faker.Lorem.Word() : null,
+ Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
+ Count = count ?? _faker.Random.Int(0, 100)
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseFixture.cs
new file mode 100644
index 00000000..68787c3b
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTextRepresentationResponseFixture.cs
@@ -0,0 +1,50 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzTextRepresentationResponseFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The ISO 639-3 language code of the release.
+ /// Whether the language should be included, or forced to .
+ /// Optional. The ISO 15924 script code of the release.
+ /// Whether the script should be included, or forced to .
+ /// A configured instance.
+ public MusicBrainzTextRepresentationResponse Create(
+ string? language = null,
+ bool includeLanguage = true,
+ string? script = null,
+ bool includeScript = true)
+ {
+ return new MusicBrainzTextRepresentationResponse
+ {
+ Language = includeLanguage ? language ?? _faker.PickRandom("eng", "deu", "fra") : null,
+ Script = includeScript ? script ?? _faker.PickRandom("Latn", "Cyrl", "Arab") : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTrackResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTrackResponseFixture.cs
new file mode 100644
index 00000000..745a2db1
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzTrackResponseFixture.cs
@@ -0,0 +1,71 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzTrackResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MusicBrainzRecordingResponseFixture _musicBrainzRecordingResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The MusicBrainz identifier of the track.
+ /// Whether the identifier should be included, or forced to .
+ /// Optional. The track number, as displayed on the medium.
+ /// Whether the number should be included, or forced to .
+ /// Optional. The position of the track within its medium.
+ /// Optional. The title of the track.
+ /// Whether the title should be included, or forced to .
+ /// Optional. The length of the track in milliseconds.
+ /// Whether the length should be included, or forced to .
+ /// Optional. The recording the track is a performance of.
+ /// Whether the recording should be included, or forced to .
+ /// A configured instance.
+ public MusicBrainzTrackResponse Create(
+ string? id = null,
+ bool includeId = true,
+ string? number = null,
+ bool includeNumber = true,
+ int? position = null,
+ string? title = null,
+ bool includeTitle = true,
+ long? length = null,
+ bool includeLength = true,
+ MusicBrainzRecordingResponse? recording = null,
+ bool includeRecording = true)
+ {
+ int resolvedPosition = position ?? _faker.Random.Int(1, 30);
+ string? resolvedTitle = includeTitle ? title ?? _faker.Lorem.Sentence(3) : null;
+ return new MusicBrainzTrackResponse
+ {
+ Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
+ Number = includeNumber ? number ?? resolvedPosition.ToString() : null,
+ Position = resolvedPosition,
+ Title = resolvedTitle,
+ Length = includeLength ? length ?? _faker.Random.Long(30_000, 600_000) : null,
+ Recording = includeRecording ? recording ?? _musicBrainzRecordingResponseFixture.Create(title: resolvedTitle) : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(index => Create(position: index + 1))];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzUrlResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzUrlResponseFixture.cs
new file mode 100644
index 00000000..08602a9b
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzUrlResponseFixture.cs
@@ -0,0 +1,50 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzUrlResponseFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The MusicBrainz identifier of the URL.
+ /// Whether the identifier should be included, or forced to .
+ /// Optional. The resource the URL points to.
+ /// Whether the resource should be included, or forced to .
+ /// A configured instance.
+ public MusicBrainzUrlResponse Create(
+ string? id = null,
+ bool includeId = true,
+ string? resource = null,
+ bool includeResource = true)
+ {
+ return new MusicBrainzUrlResponse
+ {
+ Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
+ Resource = includeResource ? resource ?? _faker.Internet.Url() : null
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzWorkResponseFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzWorkResponseFixture.cs
new file mode 100644
index 00000000..09311696
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/Contracts/Responses/MusicBrainzWorkResponseFixture.cs
@@ -0,0 +1,77 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.Contracts.Responses;
+
+///
+/// Fixture class for the record.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzWorkResponseFixture
+{
+ private readonly Faker _faker = new();
+ private readonly MusicBrainzRelationResponseFixture _musicBrainzRelationResponseFixture = new();
+ private readonly MusicBrainzTagResponseFixture _musicBrainzTagResponseFixture = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The MusicBrainz identifier of the work.
+ /// Whether the identifier should be included, or forced to .
+ /// Optional. The title of the work.
+ /// Whether the title should be included, or forced to .
+ /// Optional. The MusicBrainz type of the work.
+ /// Whether the type should be included, or forced to .
+ /// Optional. The disambiguation comment of the work.
+ /// Whether the disambiguation should be included, or forced to .
+ /// Optional. The languages of the work.
+ /// Optional. The ISWCs of the work.
+ /// Optional. The relationships of the work to other entities.
+ /// Optional. The tags of the work.
+ /// Optional. The genres of the work.
+ /// A configured instance.
+ public MusicBrainzWorkResponse Create(
+ string? id = null,
+ bool includeId = true,
+ string? title = null,
+ bool includeTitle = true,
+ string? type = null,
+ bool includeType = true,
+ string? disambiguation = null,
+ bool includeDisambiguation = true,
+ List? languages = null,
+ List? iswcs = null,
+ List? relations = null,
+ List? tags = null,
+ List? genres = null)
+ {
+ return new MusicBrainzWorkResponse
+ {
+ Id = includeId ? id ?? Guid.NewGuid().ToString() : null,
+ Title = includeTitle ? title ?? _faker.Lorem.Sentence(3) : null,
+ Type = includeType ? type ?? _faker.PickRandom("Song", "Aria", "Symphony") : null,
+ Disambiguation = includeDisambiguation ? disambiguation ?? _faker.Lorem.Sentence(2) : null,
+ Languages = languages ?? [_faker.PickRandom("eng", "deu", "fra")],
+ Iswcs = iswcs ?? [$"T-{_faker.Random.Int(100, 999)}.{_faker.Random.Int(100, 999)}.{_faker.Random.Int(100, 999)}-{_faker.Random.Int(1, 9)}"],
+ Relations = relations ?? [.. _musicBrainzRelationResponseFixture.CreateMany(2)],
+ Tags = tags ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)],
+ Genres = genres ?? [.. _musicBrainzTagResponseFixture.CreateMany(2)]
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/DTO/Settings/MusicBrainzSettingsDtoFixture.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/DTO/Settings/MusicBrainzSettingsDtoFixture.cs
new file mode 100644
index 00000000..c1b2abae
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Common/Models/DTO/Settings/MusicBrainzSettingsDtoFixture.cs
@@ -0,0 +1,63 @@
+#region ========================================================================= USING =====================================================================================
+using Bogus;
+using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.Fixtures.Common.Models.DTO.Settings;
+
+///
+/// Fixture class for the class.
+///
+[ExcludeFromCodeCoverage]
+internal sealed class MusicBrainzSettingsDtoFixture
+{
+ private readonly Faker _faker = new();
+
+ ///
+ /// Creates a new instance with randomized test data.
+ ///
+ /// Optional. The base URL of the MusicBrainz web service.
+ /// Optional. Whether the base URL may point at a private or local host.
+ /// Optional. The user agent sent with every request.
+ /// Optional. The contact email sent to the MusicBrainz API.
+ /// Whether the contact email should be included, or forced to .
+ /// Optional. The maximum number of results returned by a single search.
+ /// Optional. The maximum number of releases fetched for a single release group.
+ /// Optional. The minimum interval between consecutive requests.
+ /// A configured instance.
+ public MusicBrainzSettingsDto Create(
+ string? baseUrl = null,
+ bool? doesAllowPrivateBaseUrl = null,
+ string? userAgent = null,
+ string? contactEmail = null,
+ bool includeContactEmail = true,
+ int? searchResultLimit = null,
+ int? releaseLookupLimit = null,
+ TimeSpan? minimumRequestInterval = null)
+ {
+ return new MusicBrainzSettingsDto
+ {
+ BaseUrl = baseUrl ?? _faker.Internet.Url(),
+ DoesAllowPrivateBaseUrl = doesAllowPrivateBaseUrl ?? _faker.Random.Bool(),
+ UserAgent = userAgent ?? $"Lumina-MusicBrainz/{_faker.Random.Int(1, 9)}.{_faker.Random.Int(0, 9)}",
+ ContactEmail = includeContactEmail ? contactEmail ?? _faker.Internet.Email() : null,
+ SearchResultLimit = searchResultLimit ?? _faker.Random.Int(1, 100),
+ ReleaseLookupLimit = releaseLookupLimit ?? _faker.Random.Int(1, 100),
+ MinimumRequestInterval = minimumRequestInterval ?? TimeSpan.FromSeconds(_faker.Random.Double(0, 5))
+ };
+ }
+
+ ///
+ /// Creates multiple instances with randomized test data.
+ ///
+ /// Number of instances to create.
+ /// List of configured instances.
+ public List CreateMany(int count = 3)
+ {
+ return [.. Enumerable.Range(0, count).Select(_ => Create())];
+ }
+}
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Lumina.Plugins.MusicBrainz.Fixtures.csproj b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Lumina.Plugins.MusicBrainz.Fixtures.csproj
new file mode 100644
index 00000000..e07d39a7
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Lumina.Plugins.MusicBrainz.Fixtures.csproj
@@ -0,0 +1,25 @@
+
+
+
+ net10.0
+ disable
+ enable
+ $(SolutionDir)..\bin\api\
+
+ false
+ false
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Properties/AssemblyInfo.cs b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Properties/AssemblyInfo.cs
new file mode 100644
index 00000000..7f795b30
--- /dev/null
+++ b/tests/Common/Lumina.Plugins.MusicBrainz.Fixtures/Properties/AssemblyInfo.cs
@@ -0,0 +1,22 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("Lumina.Plugins.MusicBrainz.Fixtures")]
+[assembly: AssemblyProduct("Lumina.Plugins.MusicBrainz.Fixtures")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("C4D7E1A9-2F83-4B56-9E0D-6A8C1F3B5D72")]
+
+[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.UnitTests")]
+[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.IntegrationTests")]
+[assembly: InternalsVisibleTo("Lumina.Presentation.Api.SecurityTests")]
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/DependencyInjection/MusicBrainzServicesTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/DependencyInjection/MusicBrainzServicesTests.cs
new file mode 100644
index 00000000..cb5dca74
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/DependencyInjection/MusicBrainzServicesTests.cs
@@ -0,0 +1,147 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.Contracts.Core.Metadata;
+using Lumina.Plugins.MusicBrainz.Common.DependencyInjection;
+using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
+using Lumina.Plugins.MusicBrainz.Core;
+using Lumina.Plugins.MusicBrainz.Core.Api;
+using Lumina.Plugins.MusicBrainz.Core.Settings;
+using Microsoft.Extensions.DependencyInjection;
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.DependencyInjection;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzServicesTests
+{
+ [Fact]
+ public void AddMusicBrainzMetadataProviders_WhenServicesIsNull_ShouldThrowArgumentNullException()
+ {
+ // Arrange
+ IServiceCollection services = null!;
+
+ // Act
+ Action act = () => services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid());
+
+ // Assert
+ Assert.Throws(act);
+ }
+
+ [Fact]
+ public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldReturnTheSameServiceCollection()
+ {
+ // Arrange
+ ServiceCollection services = new();
+
+ // Act
+ IServiceCollection result = services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid());
+
+ // Assert
+ Assert.Same(services, result);
+ }
+
+ [Fact]
+ public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheThreeMetadataProvidersForKeyedResolution()
+ {
+ // Arrange
+ Guid pluginId = Guid.NewGuid();
+ ServiceCollection services = new();
+
+ // Act
+ services.AddMusicBrainzMetadataProviders(pluginId: pluginId);
+ ServiceProvider serviceProvider = services.BuildServiceProvider();
+
+ // Assert
+ Assert.Equal(3, serviceProvider.GetKeyedServices(pluginId).Count());
+ Assert.Empty(serviceProvider.GetKeyedServices(Guid.NewGuid()));
+ }
+
+ [Fact]
+ public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheSettingsProviderAsScoped()
+ {
+ // Arrange
+ ServiceCollection services = new();
+
+ // Act
+ services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid());
+
+ // Assert
+ ServiceDescriptor settingsProviderDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzSettingsProvider));
+ Assert.Equal(ServiceLifetime.Scoped, settingsProviderDescriptor.Lifetime);
+ }
+
+ [Fact]
+ public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheThrottleAndTheResponseCacheAsSingletons()
+ {
+ // Arrange
+ ServiceCollection services = new();
+
+ // Act
+ services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid());
+
+ // Assert
+ ServiceDescriptor throttleDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzRequestThrottle));
+ ServiceDescriptor responseCacheDescriptor = Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzResponseCache));
+ Assert.Equal(ServiceLifetime.Singleton, throttleDescriptor.Lifetime);
+ Assert.Equal(ServiceLifetime.Singleton, responseCacheDescriptor.Lifetime);
+ }
+
+ [Fact]
+ public void AddMusicBrainzMetadataProviders_WhenCalled_ShouldRegisterTheHttpClient()
+ {
+ // Arrange
+ ServiceCollection services = new();
+
+ // Act
+ services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid());
+ ServiceProvider serviceProvider = services.BuildServiceProvider();
+
+ // Assert
+ Assert.NotNull(serviceProvider.GetService());
+ }
+
+ [Fact]
+ public async Task AddMusicBrainzMetadataProviders_WhenASettingsCallbackIsProvided_ShouldApplyItToTheDefaults()
+ {
+ // Arrange
+ Guid pluginId = Guid.NewGuid();
+ ServiceCollection services = new();
+
+ // Act
+ services.AddMusicBrainzMetadataProviders(pluginId: pluginId, settings => settings.BaseUrl = "http://custom.example/ws/2/");
+ ServiceProvider serviceProvider = services.BuildServiceProvider();
+ using (IServiceScope scope = serviceProvider.CreateScope())
+ {
+ MusicBrainzSettingsProvider settingsProvider = scope.ServiceProvider.GetRequiredService();
+ MusicBrainzSettingsDto settings = await settingsProvider.GetAsync(CancellationToken.None);
+
+ // Assert
+ Assert.Equal("http://custom.example/ws/2/", settings.BaseUrl);
+ }
+ }
+
+ [Fact]
+ public void AddMusicBrainzMetadataProviders_WhenCalledTwice_ShouldNotDuplicateTheTryAddServices()
+ {
+ // Arrange
+ Guid pluginId = Guid.NewGuid();
+ ServiceCollection services = new();
+
+ // Act
+ services.AddMusicBrainzMetadataProviders(pluginId: pluginId);
+ services.AddMusicBrainzMetadataProviders(pluginId: pluginId);
+
+ // Assert
+ // The settings provider, the throttle and the response cache are registered with TryAdd, so a second call must not add them again.
+ Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzRequestThrottle));
+ Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzResponseCache));
+ Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzSettingsProvider));
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAliasResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAliasResponseTests.cs
new file mode 100644
index 00000000..6be62d2e
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAliasResponseTests.cs
@@ -0,0 +1,75 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzAliasResponseTests
+{
+ [Fact]
+ public void IsEnded_WhenTheMusicBrainzApiReturnsNull_ShouldDeserializeAsNull()
+ {
+ // Arrange
+ // the MusicBrainz search API can return a null ended flag for aliases, which used to break deserialization into a non-nullable boolean
+ const string JSON = """{"name":"Rammstein","ended":null}""";
+
+ // Act
+ MusicBrainzAliasResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Null(response.IsEnded);
+ }
+
+ [Fact]
+ public void IsEnded_WhenTheMusicBrainzApiReturnsTrue_ShouldDeserializeAsTrue()
+ {
+ // Arrange
+ const string JSON = """{"name":"Rammstein","ended":true}""";
+
+ // Act
+ MusicBrainzAliasResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.True(response.IsEnded);
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "name": "Alias Name",
+ "sort-name": "Alias Sort Name",
+ "type": "Artist name",
+ "locale": "en",
+ "primary": true,
+ "begin": "1994-01-01",
+ "end": "2020-12-31",
+ "ended": true
+ }
+ """;
+
+ // Act
+ MusicBrainzAliasResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("Alias Name", response.Name);
+ Assert.Equal("Alias Sort Name", response.SortName);
+ Assert.Equal("Artist name", response.Type);
+ Assert.Equal("en", response.Locale);
+ Assert.True(response.IsPrimary);
+ Assert.Equal("1994-01-01", response.Begin);
+ Assert.Equal("2020-12-31", response.End);
+ Assert.True(response.IsEnded);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAreaResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAreaResponseTests.cs
new file mode 100644
index 00000000..d5f084a6
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzAreaResponseTests.cs
@@ -0,0 +1,70 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzAreaResponseTests
+{
+ [Fact]
+ public void SortNameTypeAndIsoCodes_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "id": "c0e0e0e0-0000-0000-0000-000000000000",
+ "name": "United Kingdom",
+ "sort-name": "United Kingdom",
+ "type": "Country",
+ "iso-3166-1-codes": [ "GB" ],
+ "iso-3166-2-codes": [ "GB-ENG" ]
+ }
+ """;
+
+ // Act
+ MusicBrainzAreaResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("United Kingdom", response.SortName);
+ Assert.Equal("Country", response.Type);
+ Assert.Equal("GB", Assert.Single(response.Iso3166Part1Codes));
+ Assert.Equal("GB-ENG", Assert.Single(response.Iso3166Part2Codes));
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "id": "area-id",
+ "name": "United Kingdom",
+ "sort-name": "United Kingdom",
+ "disambiguation": "The United Kingdom of Great Britain",
+ "type": "Country",
+ "iso-3166-1-codes": [ "GB" ],
+ "iso-3166-2-codes": [ "GB-ENG" ]
+ }
+ """;
+
+ // Act
+ MusicBrainzAreaResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("area-id", response.Id);
+ Assert.Equal("United Kingdom", response.Name);
+ Assert.Equal("United Kingdom", response.SortName);
+ Assert.Equal("The United Kingdom of Great Britain", response.Disambiguation);
+ Assert.Equal("Country", response.Type);
+ Assert.Equal("GB", Assert.Single(response.Iso3166Part1Codes));
+ Assert.Equal("GB-ENG", Assert.Single(response.Iso3166Part2Codes));
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseTests.cs
new file mode 100644
index 00000000..72083a42
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistCreditResponseTests.cs
@@ -0,0 +1,54 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzArtistCreditResponseTests
+{
+ [Fact]
+ public void NameJoinPhraseAndArtist_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
+ {
+ // Arrange
+ const string JSON = """{"name":"Freddie Mercury","joinphrase":" & ","artist":{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","name":"Freddie Mercury"}}""";
+
+ // Act
+ MusicBrainzArtistCreditResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("Freddie Mercury", response.Name);
+ Assert.Equal(" & ", response.JoinPhrase);
+ Assert.NotNull(response.Artist);
+ Assert.Equal("Freddie Mercury", response.Artist.Name);
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "name": "Freddie Mercury",
+ "joinphrase": " & ",
+ "artist": { "id": "artist-id", "name": "Freddie Mercury" }
+ }
+ """;
+
+ // Act
+ MusicBrainzArtistCreditResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("Freddie Mercury", response.Name);
+ Assert.Equal(" & ", response.JoinPhrase);
+ Assert.NotNull(response.Artist);
+ Assert.Equal("artist-id", response.Artist.Id);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistResponseTests.cs
new file mode 100644
index 00000000..70353349
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistResponseTests.cs
@@ -0,0 +1,103 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzArtistResponseTests
+{
+ [Fact]
+ public void SortNameTypeCountryAndCodes_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35",
+ "name": "Queen",
+ "sort-name": "Queen",
+ "type": "Group",
+ "gender": null,
+ "country": "GB",
+ "life-span": { "begin": "1970", "ended": false },
+ "ipis": [ "00000000000" ],
+ "isnis": [ "0000000000000000" ]
+ }
+ """;
+
+ // Act
+ MusicBrainzArtistResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("Queen", response.SortName);
+ Assert.Equal("Group", response.Type);
+ Assert.Equal("GB", response.Country);
+ Assert.Equal("00000000000", Assert.Single(response.Ipis));
+ Assert.Equal("0000000000000000", Assert.Single(response.Isnis));
+ Assert.NotNull(response.LifeSpan);
+ Assert.Equal("1970", response.LifeSpan.Begin);
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "id": "artist-id",
+ "name": "Queen",
+ "sort-name": "Queen",
+ "disambiguation": "UK rock band",
+ "type": "Group",
+ "gender": "Male",
+ "country": "GB",
+ "area": { "id": "area-id", "name": "United Kingdom" },
+ "begin-area": { "id": "begin-area-id", "name": "London" },
+ "end-area": { "id": "end-area-id", "name": "Montreux" },
+ "life-span": { "begin": "1970", "end": "1991", "ended": true },
+ "isnis": [ "isni-1" ],
+ "ipis": [ "ipi-1" ],
+ "aliases": [ { "name": "Queen alias" } ],
+ "tags": [ { "name": "rock", "count": 5 } ],
+ "genres": [ { "id": "genre-id", "name": "Rock" } ],
+ "relations": [ { "type": "member of band", "artist": { "id": "member-id", "name": "Freddie Mercury" } } ],
+ "rating": { "value": 4.5, "votes-count": 10 }
+ }
+ """;
+
+ // Act
+ MusicBrainzArtistResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("artist-id", response.Id);
+ Assert.Equal("Queen", response.Name);
+ Assert.Equal("Queen", response.SortName);
+ Assert.Equal("UK rock band", response.Disambiguation);
+ Assert.Equal("Group", response.Type);
+ Assert.Equal("Male", response.Gender);
+ Assert.Equal("GB", response.Country);
+ Assert.NotNull(response.Area);
+ Assert.Equal("United Kingdom", response.Area.Name);
+ Assert.NotNull(response.BeginArea);
+ Assert.Equal("London", response.BeginArea.Name);
+ Assert.NotNull(response.EndArea);
+ Assert.Equal("Montreux", response.EndArea.Name);
+ Assert.NotNull(response.LifeSpan);
+ Assert.Equal("1970", response.LifeSpan.Begin);
+ Assert.Equal("isni-1", Assert.Single(response.Isnis));
+ Assert.Equal("ipi-1", Assert.Single(response.Ipis));
+ Assert.Equal("Queen alias", Assert.Single(response.Aliases).Name);
+ Assert.Equal("rock", Assert.Single(response.Tags).Name);
+ Assert.Equal("Rock", Assert.Single(response.Genres).Name);
+ Assert.Equal("member of band", Assert.Single(response.Relations).Type);
+ Assert.NotNull(response.Rating);
+ Assert.Equal(4.5m, response.Rating.Value);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseTests.cs
new file mode 100644
index 00000000..67f8f072
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzArtistSearchResponseTests.cs
@@ -0,0 +1,52 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzArtistSearchResponseTests
+{
+ [Fact]
+ public void CountOffsetAndArtists_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
+ {
+ // Arrange
+ const string JSON = """{"count":1,"offset":0,"artists":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","name":"Queen"}]}""";
+
+ // Act
+ MusicBrainzArtistSearchResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal(1, response.Count);
+ Assert.Equal(0, response.Offset);
+ Assert.Equal("Queen", Assert.Single(response.Artists).Name);
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "count": 2,
+ "offset": 1,
+ "artists": [ { "id": "artist-id", "name": "Queen" } ]
+ }
+ """;
+
+ // Act
+ MusicBrainzArtistSearchResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal(2, response.Count);
+ Assert.Equal(1, response.Offset);
+ Assert.Equal("artist-id", Assert.Single(response.Artists).Id);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseTests.cs
new file mode 100644
index 00000000..a3400d05
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelInfoResponseTests.cs
@@ -0,0 +1,51 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzLabelInfoResponseTests
+{
+ [Fact]
+ public void CatalogNumberAndLabel_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
+ {
+ // Arrange
+ const string JSON = """{"catalog-number":"EMC 4008","label":{"id":"f0e0e0e0-0000-0000-0000-000000000000","name":"EMI"}}""";
+
+ // Act
+ MusicBrainzLabelInfoResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("EMC 4008", response.CatalogNumber);
+ Assert.NotNull(response.Label);
+ Assert.Equal("EMI", response.Label.Name);
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "catalog-number": "EMC 4008",
+ "label": { "id": "label-id", "name": "EMI" }
+ }
+ """;
+
+ // Act
+ MusicBrainzLabelInfoResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("EMC 4008", response.CatalogNumber);
+ Assert.NotNull(response.Label);
+ Assert.Equal("EMI", response.Label.Name);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelResponseTests.cs
new file mode 100644
index 00000000..71b21dc3
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLabelResponseTests.cs
@@ -0,0 +1,54 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzLabelResponseTests
+{
+ [Fact]
+ public void NameDisambiguationAndLabelCode_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
+ {
+ // Arrange
+ const string JSON = """{"id":"f0e0e0e0-0000-0000-0000-000000000000","name":"EMI","disambiguation":"EMI Records Ltd.","label-code":1234}""";
+
+ // Act
+ MusicBrainzLabelResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("EMI", response.Name);
+ Assert.Equal("EMI Records Ltd.", response.Disambiguation);
+ Assert.Equal(1234, response.LabelCode);
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "id": "label-id",
+ "name": "EMI",
+ "disambiguation": "EMI Records Ltd.",
+ "label-code": 1234
+ }
+ """;
+
+ // Act
+ MusicBrainzLabelResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("label-id", response.Id);
+ Assert.Equal("EMI", response.Name);
+ Assert.Equal("EMI Records Ltd.", response.Disambiguation);
+ Assert.Equal(1234, response.LabelCode);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseTests.cs
new file mode 100644
index 00000000..38ee4e0c
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzLifeSpanResponseTests.cs
@@ -0,0 +1,65 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzLifeSpanResponseTests
+{
+ [Fact]
+ public void IsEnded_WhenTheMusicBrainzApiReturnsNull_ShouldDeserializeAsNull()
+ {
+ // Arrange
+ // the MusicBrainz search API returns a null ended flag for artists whose end status is unknown, which used to break deserialization into a non-nullable boolean
+ const string JSON = """{"begin":"1994-01","ended":null}""";
+
+ // Act
+ MusicBrainzLifeSpanResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Null(response.IsEnded);
+ }
+
+ [Fact]
+ public void IsEnded_WhenTheMusicBrainzApiReturnsTrue_ShouldDeserializeAsTrue()
+ {
+ // Arrange
+ const string JSON = """{"begin":"1970-06-27","ended":true}""";
+
+ // Act
+ MusicBrainzLifeSpanResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.True(response.IsEnded);
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "begin": "1970-06-27",
+ "end": "1991-11-24",
+ "ended": true
+ }
+ """;
+
+ // Act
+ MusicBrainzLifeSpanResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("1970-06-27", response.Begin);
+ Assert.Equal("1991-11-24", response.End);
+ Assert.True(response.IsEnded);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzMediumResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzMediumResponseTests.cs
new file mode 100644
index 00000000..1c8ebda1
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzMediumResponseTests.cs
@@ -0,0 +1,57 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzMediumResponseTests
+{
+ [Fact]
+ public void PositionFormatAndTrackCount_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
+ {
+ // Arrange
+ const string JSON = """{"position":1,"title":"Disc 1","format":"CD","track-count":12}""";
+
+ // Act
+ MusicBrainzMediumResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal(1, response.Position);
+ Assert.Equal("Disc 1", response.Title);
+ Assert.Equal("CD", response.Format);
+ Assert.Equal(12, response.TrackCount);
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "position": 2,
+ "title": "Disc 2",
+ "format": "Vinyl",
+ "track-count": 8,
+ "tracks": [ { "id": "track-id", "number": "A1", "position": 1, "title": "Death on Two Legs" } ]
+ }
+ """;
+
+ // Act
+ MusicBrainzMediumResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal(2, response.Position);
+ Assert.Equal("Disc 2", response.Title);
+ Assert.Equal("Vinyl", response.Format);
+ Assert.Equal(8, response.TrackCount);
+ Assert.Equal("track-id", Assert.Single(response.Tracks).Id);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRatingResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRatingResponseTests.cs
new file mode 100644
index 00000000..675a12a2
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRatingResponseTests.cs
@@ -0,0 +1,66 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzRatingResponseTests
+{
+ private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web)
+ {
+ NumberHandling = JsonNumberHandling.AllowReadingFromString
+ };
+
+ [Fact]
+ public void ValueAndVotesCount_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
+ {
+ // Arrange
+ const string JSON = """{"value":4.5,"votes-count":10}""";
+
+ // Act
+ MusicBrainzRatingResponse? response = JsonSerializer.Deserialize(JSON, s_serializerOptions);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal(4.5m, response.Value);
+ Assert.Equal(10, response.VotesCount);
+ }
+
+ [Fact]
+ public void ValueAndVotesCount_WhenTheMusicBrainzApiReturnsStrings_ShouldStillDeserializeThem()
+ {
+ // Arrange
+ // The MusicBrainz search API sometimes returns the rating numbers as strings.
+ const string JSON = """{"value":"4.5","votes-count":"10"}""";
+
+ // Act
+ MusicBrainzRatingResponse? response = JsonSerializer.Deserialize(JSON, s_serializerOptions);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal(4.5m, response.Value);
+ Assert.Equal(10, response.VotesCount);
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """{"value":4.5,"votes-count":10}""";
+
+ // Act
+ MusicBrainzRatingResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal(4.5m, response.Value);
+ Assert.Equal(10, response.VotesCount);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseTests.cs
new file mode 100644
index 00000000..195f7f68
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingListResponseTests.cs
@@ -0,0 +1,50 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzRecordingListResponseTests
+{
+ [Fact]
+ public void Recordings_WhenReturnedByTheMusicBrainzIsrcLookup_ShouldDeserialize()
+ {
+ // Arrange
+ const string JSON = """{"recordings":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs","isrcs":["GBUM71029604"]}]}""";
+
+ // Act
+ MusicBrainzRecordingListResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ MusicBrainzRecordingResponse recording = Assert.Single(response.Recordings);
+ Assert.Equal("Death on Two Legs", recording.Title);
+ Assert.Equal("GBUM71029604", Assert.Single(recording.Isrcs));
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "recordings": [ { "id": "recording-id", "title": "Death on Two Legs", "isrcs": [ "GBUM71029604" ] } ]
+ }
+ """;
+
+ // Act
+ MusicBrainzRecordingListResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ MusicBrainzRecordingResponse recording = Assert.Single(response.Recordings);
+ Assert.Equal("recording-id", recording.Id);
+ Assert.Equal("Death on Two Legs", recording.Title);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseTests.cs
new file mode 100644
index 00000000..857e7fe7
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingResponseTests.cs
@@ -0,0 +1,86 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzRecordingResponseTests
+{
+ [Fact]
+ public void IsVideo_WhenTheMusicBrainzApiReturnsNull_ShouldDeserializeAsNull()
+ {
+ // Arrange
+ // The MusicBrainz search API returns a null video flag for most recordings, which used to break deserialization into a non-nullable boolean.
+ const string JSON = """{"id":"8778bb30-2f72-4bc8-8b71-cdbe084036c3","title":"A Kind of Magic","video":null}""";
+
+ // Act
+ MusicBrainzRecordingResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Null(response.IsVideo);
+ }
+
+ [Fact]
+ public void IsVideo_WhenTheMusicBrainzApiReturnsFalse_ShouldDeserializeAsFalse()
+ {
+ // Arrange
+ const string JSON = """{"id":"8778bb30-2f72-4bc8-8b71-cdbe084036c3","title":"A Kind of Magic","video":false}""";
+
+ // Act
+ MusicBrainzRecordingResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.False(response.IsVideo);
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "id": "recording-id",
+ "title": "Bohemian Rhapsody",
+ "disambiguation": "album version",
+ "length": 354000,
+ "video": true,
+ "first-release-date": "1975-10-31",
+ "artist-credit": [ { "name": "Queen", "artist": { "id": "artist-id", "name": "Queen" } } ],
+ "isrcs": [ "GBUM71029604" ],
+ "releases": [ { "id": "release-id", "title": "A Night at the Opera" } ],
+ "tags": [ { "name": "rock", "count": 5 } ],
+ "genres": [ { "id": "genre-id", "name": "Rock" } ],
+ "relations": [ { "type": "performance", "work": { "id": "work-id", "title": "Bohemian Rhapsody" } } ],
+ "rating": { "value": 4.5, "votes-count": 10 }
+ }
+ """;
+
+ // Act
+ MusicBrainzRecordingResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("recording-id", response.Id);
+ Assert.Equal("Bohemian Rhapsody", response.Title);
+ Assert.Equal("album version", response.Disambiguation);
+ Assert.Equal(354000, response.Length);
+ Assert.True(response.IsVideo);
+ Assert.Equal("1975-10-31", response.FirstReleaseDate);
+ Assert.Equal("Queen", Assert.Single(response.ArtistCredit).Name);
+ Assert.Equal("GBUM71029604", Assert.Single(response.Isrcs));
+ Assert.Equal("release-id", Assert.Single(response.Releases).Id);
+ Assert.Equal("rock", Assert.Single(response.Tags).Name);
+ Assert.Equal("Rock", Assert.Single(response.Genres).Name);
+ Assert.Equal("performance", Assert.Single(response.Relations).Type);
+ Assert.NotNull(response.Rating);
+ Assert.Equal(4.5m, response.Rating.Value);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseTests.cs
new file mode 100644
index 00000000..b9ebb79d
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRecordingSearchResponseTests.cs
@@ -0,0 +1,52 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzRecordingSearchResponseTests
+{
+ [Fact]
+ public void CountOffsetAndRecordings_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
+ {
+ // Arrange
+ const string JSON = """{"count":1,"offset":0,"recordings":[{"id":"cb6c5931-436c-38c5-9d24-044f37d1fe35","title":"Death on Two Legs"}]}""";
+
+ // Act
+ MusicBrainzRecordingSearchResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal(1, response.Count);
+ Assert.Equal(0, response.Offset);
+ Assert.Equal("Death on Two Legs", Assert.Single(response.Recordings).Title);
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "count": 3,
+ "offset": 2,
+ "recordings": [ { "id": "recording-id", "title": "Death on Two Legs" } ]
+ }
+ """;
+
+ // Act
+ MusicBrainzRecordingSearchResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal(3, response.Count);
+ Assert.Equal(2, response.Offset);
+ Assert.Equal("recording-id", Assert.Single(response.Recordings).Id);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRelationResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRelationResponseTests.cs
new file mode 100644
index 00000000..08e90b41
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzRelationResponseTests.cs
@@ -0,0 +1,77 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzRelationResponseTests
+{
+ [Fact]
+ public void TypeTargetTypeArtistAndAttributes_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "type": "producer",
+ "type-id": "d0e0e0e0-0000-0000-0000-000000000000",
+ "direction": "backward",
+ "target-type": "artist",
+ "artist": { "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35", "name": "Roy Thomas Baker" },
+ "attributes": [ "producer" ]
+ }
+ """;
+
+ // Act
+ MusicBrainzRelationResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("producer", response.Type);
+ Assert.Equal("backward", response.Direction);
+ Assert.Equal("artist", response.TargetType);
+ Assert.NotNull(response.Artist);
+ Assert.Equal("Roy Thomas Baker", response.Artist.Name);
+ Assert.Equal("producer", Assert.Single(response.Attributes));
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "type": "producer",
+ "type-id": "type-id",
+ "direction": "backward",
+ "target-type": "artist",
+ "artist": { "id": "artist-id", "name": "Roy Thomas Baker" },
+ "work": { "id": "work-id", "title": "Bohemian Rhapsody" },
+ "url": { "id": "url-id", "resource": "https://example.com/" },
+ "attributes": [ "producer" ]
+ }
+ """;
+
+ // Act
+ MusicBrainzRelationResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("producer", response.Type);
+ Assert.Equal("type-id", response.TypeId);
+ Assert.Equal("backward", response.Direction);
+ Assert.Equal("artist", response.TargetType);
+ Assert.NotNull(response.Artist);
+ Assert.Equal("Roy Thomas Baker", response.Artist.Name);
+ Assert.NotNull(response.Work);
+ Assert.Equal("Bohemian Rhapsody", response.Work.Title);
+ Assert.NotNull(response.Url);
+ Assert.Equal("https://example.com/", response.Url.Resource);
+ Assert.Equal("producer", Assert.Single(response.Attributes));
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseTests.cs
new file mode 100644
index 00000000..4f4a5711
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseBrowseResponseTests.cs
@@ -0,0 +1,52 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzReleaseBrowseResponseTests
+{
+ [Fact]
+ public void ReleaseCountReleaseOffsetAndReleases_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
+ {
+ // Arrange
+ const string JSON = """{"release-count":5,"release-offset":2,"releases":[{"id":"11111111-1111-1111-1111-111111111111","title":"A Night at the Opera"}]}""";
+
+ // Act
+ MusicBrainzReleaseBrowseResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal(5, response.ReleaseCount);
+ Assert.Equal(2, response.ReleaseOffset);
+ Assert.Equal("A Night at the Opera", Assert.Single(response.Releases).Title);
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "releases": [ { "id": "release-id", "title": "A Night at the Opera" } ],
+ "release-count": 5,
+ "release-offset": 2
+ }
+ """;
+
+ // Act
+ MusicBrainzReleaseBrowseResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("release-id", Assert.Single(response.Releases).Id);
+ Assert.Equal(5, response.ReleaseCount);
+ Assert.Equal(2, response.ReleaseOffset);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseTests.cs
new file mode 100644
index 00000000..4d594ba5
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseEventResponseTests.cs
@@ -0,0 +1,52 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzReleaseEventResponseTests
+{
+ [Fact]
+ public void DateAndArea_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
+ {
+ // Arrange
+ const string JSON = """{"date":"1975-11-21","area":{"id":"c0e0e0e0-0000-0000-0000-000000000000","name":"United Kingdom","iso-3166-1-codes":["GB"]}}""";
+
+ // Act
+ MusicBrainzReleaseEventResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("1975-11-21", response.Date);
+ Assert.NotNull(response.Area);
+ Assert.Equal("United Kingdom", response.Area.Name);
+ Assert.Equal("GB", Assert.Single(response.Area.Iso3166Part1Codes));
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "date": "1975-11-21",
+ "area": { "id": "area-id", "name": "United Kingdom" }
+ }
+ """;
+
+ // Act
+ MusicBrainzReleaseEventResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("1975-11-21", response.Date);
+ Assert.NotNull(response.Area);
+ Assert.Equal("area-id", response.Area.Id);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseTests.cs
new file mode 100644
index 00000000..39a0ce75
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupResponseTests.cs
@@ -0,0 +1,79 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the class.
+///
+[ExcludeFromCodeCoverage]
+public class MusicBrainzReleaseGroupResponseTests
+{
+ [Fact]
+ public void PrimaryTypeSecondaryTypesAndFirstReleaseDate_WhenReturnedByTheMusicBrainzApi_ShouldDeserialize()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "id": "22222222-2222-2222-2222-222222222222",
+ "title": "A Night at the Opera",
+ "primary-type": "Album",
+ "secondary-types": [ "Live" ],
+ "first-release-date": "1975-11-21",
+ "artist-credit": [ { "name": "Queen", "artist": { "id": "cb6c5931-436c-38c5-9d24-044f37d1fe35" } } ]
+ }
+ """;
+
+ // Act
+ MusicBrainzReleaseGroupResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("Album", response.PrimaryType);
+ Assert.Equal("Live", Assert.Single(response.SecondaryTypes));
+ Assert.Equal("1975-11-21", response.FirstReleaseDate);
+ Assert.Equal("Queen", Assert.Single(response.ArtistCredit).Name);
+ }
+
+ [Fact]
+ public void Deserialize_WhenEveryFieldIsPresent_ShouldDeserializeEveryProperty()
+ {
+ // Arrange
+ const string JSON = """
+ {
+ "id": "release-group-id",
+ "title": "A Night at the Opera",
+ "disambiguation": "1975 album",
+ "primary-type": "Album",
+ "secondary-types": [ "Live" ],
+ "first-release-date": "1975-11-21",
+ "artist-credit": [ { "name": "Queen", "artist": { "id": "artist-id" } } ],
+ "releases": [ { "id": "release-id", "title": "A Night at the Opera" } ],
+ "tags": [ { "name": "rock", "count": 5 } ],
+ "genres": [ { "id": "genre-id", "name": "Rock" } ],
+ "rating": { "value": 4.5, "votes-count": 10 }
+ }
+ """;
+
+ // Act
+ MusicBrainzReleaseGroupResponse? response = JsonSerializer.Deserialize(JSON);
+
+ // Assert
+ Assert.NotNull(response);
+ Assert.Equal("release-group-id", response.Id);
+ Assert.Equal("A Night at the Opera", response.Title);
+ Assert.Equal("1975 album", response.Disambiguation);
+ Assert.Equal("Album", response.PrimaryType);
+ Assert.Equal("Live", Assert.Single(response.SecondaryTypes));
+ Assert.Equal("1975-11-21", response.FirstReleaseDate);
+ Assert.Equal("Queen", Assert.Single(response.ArtistCredit).Name);
+ Assert.Equal("release-id", Assert.Single(response.Releases).Id);
+ Assert.Equal("rock", Assert.Single(response.Tags).Name);
+ Assert.Equal("Rock", Assert.Single(response.Genres).Name);
+ Assert.NotNull(response.Rating);
+ Assert.Equal(4.5m, response.Rating.Value);
+ }
+}
diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseTests.cs
new file mode 100644
index 00000000..57aef8ce
--- /dev/null
+++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/Models/Contracts/Responses/MusicBrainzReleaseGroupSearchResponseTests.cs
@@ -0,0 +1,52 @@
+#region ========================================================================= USING =====================================================================================
+using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
+using System.Diagnostics.CodeAnalysis;
+using System.Text.Json;
+#endregion
+
+namespace Lumina.Plugins.MusicBrainz.UnitTests.Common.Models.Contracts.Responses;
+
+///
+/// Contains unit tests for the