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

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

No files matched your search

@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using Lumina.Plugins.MusicBrainz.Core;
using Lumina.Plugins.MusicBrainz.Core.Api;
using Lumina.Plugins.MusicBrainz.Core.Settings;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Net.Http;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.DependencyInjection;
/// <summary>
/// Utility class for registering the services of the MusicBrainz metadata provider into the Dependency Injection container.
/// </summary>
internal static class MusicBrainzServices
{
/// <summary>
/// Registers the services of the MusicBrainz metadata providers into the Dependency Injection container.
/// </summary>
/// <param name="services">The service collection to add the services to.</param>
/// <param name="pluginId">The unique identifier of the plugin that provides the metadata.</param>
/// <param name="settingsCallback">Action used to configure the <see cref="MusicBrainzSettingsDto"/>.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
internal static IServiceCollection AddMusicBrainzMetadataProviders(this IServiceCollection services, Guid pluginId, Action<MusicBrainzSettingsDto>? settingsCallback = null)
{
ArgumentNullException.ThrowIfNull(services);
// Build the runtime settings provider per scope, overlaying the settings persisted by the host over the defaults and the optional callback.
services.TryAddScoped(serviceProvider =>
{
MusicBrainzSettingsDto defaults = new();
settingsCallback?.Invoke(defaults);
IPluginSettingsStore? settingsStore = serviceProvider.GetService<IPluginSettingsStore>();
return new MusicBrainzSettingsProvider(settingsStore, pluginId, defaults);
});
// The throttle must be process-wide, because the MusicBrainz web service enforces its request policy across all callers, not per scope.
services.TryAddSingleton<MusicBrainzRequestThrottle>();
// The response cache is process-wide, so that an entity shared by many items, like a release shared by all its tracks, is fetched only once.
services.TryAddSingleton<MusicBrainzResponseCache>();
// Redirects are not followed, so the configurable base URL cannot be used to reach an internal address through a redirect from a mirror.
services.AddHttpClient<MusicBrainzHttpClient>()
.ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false });
// Register the metadata providers as keyed by pluginId transient services, so they can be resolved specifically among other IMetadataProvider implementations.
// A single plugin exposes one provider per entity type, because the metadata contract is typed to a single lookup and metadata pair.
services.AddKeyedTransient<IMetadataProvider, MusicBrainzArtistMetadataProvider>(pluginId);
services.AddKeyedTransient<IMetadataProvider, MusicBrainzAlbumMetadataProvider>(pluginId);
services.AddKeyedTransient<IMetadataProvider, MusicBrainzTrackMetadataProvider>(pluginId);
return services;
}
}
@@ -0,0 +1,59 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for an alias of a MusicBrainz entity.
/// </summary>
internal sealed record MusicBrainzAliasResponse
{
/// <summary>
/// Gets the name of the alias.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the sort name of the alias.
/// </summary>
[JsonPropertyName("sort-name")]
public string? SortName { get; init; }
/// <summary>
/// Gets the type of the alias.
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; init; }
/// <summary>
/// Gets the locale the alias is used in.
/// </summary>
[JsonPropertyName("locale")]
public string? Locale { get; init; }
/// <summary>
/// Gets a value indicating whether this is the primary alias.
/// </summary>
[JsonPropertyName("primary")]
public bool? IsPrimary { get; init; }
/// <summary>
/// Gets the begin date of the alias.
/// </summary>
[JsonPropertyName("begin")]
public string? Begin { get; init; }
/// <summary>
/// Gets the end date of the alias.
/// </summary>
[JsonPropertyName("end")]
public string? End { get; init; }
/// <summary>
/// Gets a value indicating whether the alias has ended.
/// </summary>
[JsonPropertyName("ended")]
public bool? IsEnded { get; init; }
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for an area from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzAreaResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the area.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the name of the area.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the sort name of the area.
/// </summary>
[JsonPropertyName("sort-name")]
public string? SortName { get; init; }
/// <summary>
/// Gets the disambiguation comment of the area.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the MusicBrainz type of the area.
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; init; }
/// <summary>
/// Gets the ISO 3166-1 codes of the area.
/// </summary>
[JsonPropertyName("iso-3166-1-codes")]
public List<string> Iso3166Part1Codes { get; init; } = [];
/// <summary>
/// Gets the ISO 3166-2 codes of the area.
/// </summary>
[JsonPropertyName("iso-3166-2-codes")]
public List<string> Iso3166Part2Codes { get; init; } = [];
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a single credit in the artist credit of a MusicBrainz entity.
/// </summary>
internal sealed record MusicBrainzArtistCreditResponse
{
/// <summary>
/// Gets the credited name of the artist.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the join phrase that follows the credit.
/// </summary>
[JsonPropertyName("joinphrase")]
public string? JoinPhrase { get; init; }
/// <summary>
/// Gets the artist the credit refers to.
/// </summary>
[JsonPropertyName("artist")]
public MusicBrainzArtistResponse? Artist { get; init; }
}
@@ -0,0 +1,120 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for an artist from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzArtistResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the artist.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the name of the artist.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the sort name of the artist.
/// </summary>
[JsonPropertyName("sort-name")]
public string? SortName { get; init; }
/// <summary>
/// Gets the disambiguation comment of the artist.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the MusicBrainz type of the artist.
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; init; }
/// <summary>
/// Gets the gender of the artist.
/// </summary>
[JsonPropertyName("gender")]
public string? Gender { get; init; }
/// <summary>
/// Gets the ISO 3166-1 alpha-2 code of the country of the artist.
/// </summary>
[JsonPropertyName("country")]
public string? Country { get; init; }
/// <summary>
/// Gets the area the artist is primarily identified with.
/// </summary>
[JsonPropertyName("area")]
public MusicBrainzAreaResponse? Area { get; init; }
/// <summary>
/// Gets the area the artist began in.
/// </summary>
[JsonPropertyName("begin-area")]
public MusicBrainzAreaResponse? BeginArea { get; init; }
/// <summary>
/// Gets the area the artist ended in.
/// </summary>
[JsonPropertyName("end-area")]
public MusicBrainzAreaResponse? EndArea { get; init; }
/// <summary>
/// Gets the life span of the artist.
/// </summary>
[JsonPropertyName("life-span")]
public MusicBrainzLifeSpanResponse? LifeSpan { get; init; }
/// <summary>
/// Gets the ISNI codes of the artist.
/// </summary>
[JsonPropertyName("isnis")]
public List<string> Isnis { get; init; } = [];
/// <summary>
/// Gets the IPI codes of the artist.
/// </summary>
[JsonPropertyName("ipis")]
public List<string> Ipis { get; init; } = [];
/// <summary>
/// Gets the alternative names of the artist.
/// </summary>
[JsonPropertyName("aliases")]
public List<MusicBrainzAliasResponse> Aliases { get; init; } = [];
/// <summary>
/// Gets the tags of the artist.
/// </summary>
[JsonPropertyName("tags")]
public List<MusicBrainzTagResponse> Tags { get; init; } = [];
/// <summary>
/// Gets the genres of the artist.
/// </summary>
[JsonPropertyName("genres")]
public List<MusicBrainzTagResponse> Genres { get; init; } = [];
/// <summary>
/// Gets the relationships of the artist to other entities.
/// </summary>
[JsonPropertyName("relations")]
public List<MusicBrainzRelationResponse> Relations { get; init; } = [];
/// <summary>
/// Gets the aggregated rating of the artist.
/// </summary>
[JsonPropertyName("rating")]
public MusicBrainzRatingResponse? Rating { get; init; }
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for an artist search from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzArtistSearchResponse
{
/// <summary>
/// Gets the total number of matching artists.
/// </summary>
[JsonPropertyName("count")]
public int Count { get; init; }
/// <summary>
/// Gets the offset of the returned artists.
/// </summary>
[JsonPropertyName("offset")]
public int Offset { get; init; }
/// <summary>
/// Gets the matching artists.
/// </summary>
[JsonPropertyName("artists")]
public List<MusicBrainzArtistResponse> Artists { get; init; } = [];
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the label information of a MusicBrainz release.
/// </summary>
internal sealed record MusicBrainzLabelInfoResponse
{
/// <summary>
/// Gets the catalog number assigned by the label.
/// </summary>
[JsonPropertyName("catalog-number")]
public string? CatalogNumber { get; init; }
/// <summary>
/// Gets the label that issued the release.
/// </summary>
[JsonPropertyName("label")]
public MusicBrainzLabelResponse? Label { get; init; }
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a label from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzLabelResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the label.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the name of the label.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the disambiguation comment of the label.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the label code of the label.
/// </summary>
[JsonPropertyName("label-code")]
public int? LabelCode { get; init; }
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the life span of a MusicBrainz artist, label, or area.
/// </summary>
internal sealed record MusicBrainzLifeSpanResponse
{
/// <summary>
/// Gets the begin date of the life span.
/// </summary>
[JsonPropertyName("begin")]
public string? Begin { get; init; }
/// <summary>
/// Gets the end date of the life span.
/// </summary>
[JsonPropertyName("end")]
public string? End { get; init; }
/// <summary>
/// Gets a value indicating whether the life span has ended.
/// </summary>
[JsonPropertyName("ended")]
public bool? IsEnded { get; init; }
}
@@ -0,0 +1,42 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a medium of a MusicBrainz release.
/// </summary>
internal sealed record MusicBrainzMediumResponse
{
/// <summary>
/// Gets the position of the medium within its release.
/// </summary>
[JsonPropertyName("position")]
public int Position { get; init; }
/// <summary>
/// Gets the title of the medium.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the format of the medium (e.g., CD, Vinyl, Digital Media).
/// </summary>
[JsonPropertyName("format")]
public string? Format { get; init; }
/// <summary>
/// Gets the number of tracks of the medium.
/// </summary>
[JsonPropertyName("track-count")]
public int TrackCount { get; init; }
/// <summary>
/// Gets the tracks of the medium. The tracks are only returned when the recordings are included in the request.
/// </summary>
[JsonPropertyName("tracks")]
public List<MusicBrainzTrackResponse> Tracks { get; init; } = [];
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the aggregated rating of a MusicBrainz entity.
/// </summary>
internal sealed record MusicBrainzRatingResponse
{
/// <summary>
/// Gets the average rating value.
/// </summary>
[JsonPropertyName("value")]
public decimal? Value { get; init; }
/// <summary>
/// Gets the number of votes that contributed to the rating.
/// </summary>
[JsonPropertyName("votes-count")]
public int? VotesCount { get; init; }
}
@@ -0,0 +1,18 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the recordings returned by an ISRC lookup from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzRecordingListResponse
{
/// <summary>
/// Gets the recordings that carry the looked up ISRC.
/// </summary>
[JsonPropertyName("recordings")]
public List<MusicBrainzRecordingResponse> Recordings { get; init; } = [];
}
@@ -0,0 +1,90 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a recording from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzRecordingResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the recording.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the title of the recording.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the disambiguation comment of the recording.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the length of the recording in milliseconds.
/// </summary>
[JsonPropertyName("length")]
public long? Length { get; init; }
/// <summary>
/// Gets a value indicating whether the recording is a video recording.
/// </summary>
[JsonPropertyName("video")]
public bool? IsVideo { get; init; }
/// <summary>
/// Gets the date the recording was first released.
/// </summary>
[JsonPropertyName("first-release-date")]
public string? FirstReleaseDate { get; init; }
/// <summary>
/// Gets the artist credit of the recording.
/// </summary>
[JsonPropertyName("artist-credit")]
public List<MusicBrainzArtistCreditResponse> ArtistCredit { get; init; } = [];
/// <summary>
/// Gets the ISRC (International Standard Recording Code) of the recording.
/// </summary>
[JsonPropertyName("isrcs")]
public List<string> Isrcs { get; init; } = [];
/// <summary>
/// Gets the releases the recording appears on.
/// </summary>
[JsonPropertyName("releases")]
public List<MusicBrainzReleaseResponse> Releases { get; init; } = [];
/// <summary>
/// Gets the tags of the recording.
/// </summary>
[JsonPropertyName("tags")]
public List<MusicBrainzTagResponse> Tags { get; init; } = [];
/// <summary>
/// Gets the genres of the recording.
/// </summary>
[JsonPropertyName("genres")]
public List<MusicBrainzTagResponse> Genres { get; init; } = [];
/// <summary>
/// Gets the relationships of the recording to other entities (e.g., its work, and its performers).
/// </summary>
[JsonPropertyName("relations")]
public List<MusicBrainzRelationResponse> Relations { get; init; } = [];
/// <summary>
/// Gets the aggregated rating of the recording.
/// </summary>
[JsonPropertyName("rating")]
public MusicBrainzRatingResponse? Rating { get; init; }
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a recording search from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzRecordingSearchResponse
{
/// <summary>
/// Gets the total number of matching recordings.
/// </summary>
[JsonPropertyName("count")]
public int Count { get; init; }
/// <summary>
/// Gets the offset of the returned recordings.
/// </summary>
[JsonPropertyName("offset")]
public int Offset { get; init; }
/// <summary>
/// Gets the matching recordings.
/// </summary>
[JsonPropertyName("recordings")]
public List<MusicBrainzRecordingResponse> Recordings { get; init; } = [];
}
@@ -0,0 +1,60 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a relationship between a MusicBrainz entity and another entity.
/// </summary>
internal sealed record MusicBrainzRelationResponse
{
/// <summary>
/// Gets the type of the relationship (e.g., producer, composer, member of band).
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; init; }
/// <summary>
/// Gets the MusicBrainz identifier of the type of the relationship.
/// </summary>
[JsonPropertyName("type-id")]
public string? TypeId { get; init; }
/// <summary>
/// Gets the direction of the relationship.
/// </summary>
[JsonPropertyName("direction")]
public string? Direction { get; init; }
/// <summary>
/// Gets the type of the entity the relationship targets.
/// </summary>
[JsonPropertyName("target-type")]
public string? TargetType { get; init; }
/// <summary>
/// Gets the artist the relationship targets, when the target is an artist.
/// </summary>
[JsonPropertyName("artist")]
public MusicBrainzArtistResponse? Artist { get; init; }
/// <summary>
/// Gets the work the relationship targets, when the target is a work.
/// </summary>
[JsonPropertyName("work")]
public MusicBrainzWorkResponse? Work { get; init; }
/// <summary>
/// Gets the URL the relationship targets, when the target is a URL.
/// </summary>
[JsonPropertyName("url")]
public MusicBrainzUrlResponse? Url { get; init; }
/// <summary>
/// Gets the attributes of the relationship (e.g., the instrument that was performed).
/// </summary>
[JsonPropertyName("attributes")]
public List<string> Attributes { get; init; } = [];
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the result of browsing the releases linked to another MusicBrainz entity.
/// </summary>
internal sealed record MusicBrainzReleaseBrowseResponse
{
/// <summary>
/// Gets the releases returned by the browse request.
/// </summary>
[JsonPropertyName("releases")]
public List<MusicBrainzReleaseResponse> Releases { get; init; } = [];
/// <summary>
/// Gets the total number of releases linked to the browsed entity.
/// </summary>
[JsonPropertyName("release-count")]
public int ReleaseCount { get; init; }
/// <summary>
/// Gets the offset of the returned releases.
/// </summary>
[JsonPropertyName("release-offset")]
public int ReleaseOffset { get; init; }
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a release event of a MusicBrainz release.
/// </summary>
internal sealed record MusicBrainzReleaseEventResponse
{
/// <summary>
/// Gets the date of the release event.
/// </summary>
[JsonPropertyName("date")]
public string? Date { get; init; }
/// <summary>
/// Gets the area of the release event.
/// </summary>
[JsonPropertyName("area")]
public MusicBrainzAreaResponse? Area { get; init; }
}
@@ -0,0 +1,78 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a release group from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzReleaseGroupResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the release group.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the title of the release group.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the disambiguation comment of the release group.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the primary type of the release group.
/// </summary>
[JsonPropertyName("primary-type")]
public string? PrimaryType { get; init; }
/// <summary>
/// Gets the secondary types of the release group.
/// </summary>
[JsonPropertyName("secondary-types")]
public List<string> SecondaryTypes { get; init; } = [];
/// <summary>
/// Gets the date the release group was first released.
/// </summary>
[JsonPropertyName("first-release-date")]
public string? FirstReleaseDate { get; init; }
/// <summary>
/// Gets the artist credit of the release group.
/// </summary>
[JsonPropertyName("artist-credit")]
public List<MusicBrainzArtistCreditResponse> ArtistCredit { get; init; } = [];
/// <summary>
/// Gets the releases of the release group.
/// </summary>
[JsonPropertyName("releases")]
public List<MusicBrainzReleaseResponse> Releases { get; init; } = [];
/// <summary>
/// Gets the tags of the release group.
/// </summary>
[JsonPropertyName("tags")]
public List<MusicBrainzTagResponse> Tags { get; init; } = [];
/// <summary>
/// Gets the genres of the release group.
/// </summary>
[JsonPropertyName("genres")]
public List<MusicBrainzTagResponse> Genres { get; init; } = [];
/// <summary>
/// Gets the aggregated rating of the release group.
/// </summary>
[JsonPropertyName("rating")]
public MusicBrainzRatingResponse? Rating { get; init; }
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a release group search from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzReleaseGroupSearchResponse
{
/// <summary>
/// Gets the total number of matching release groups.
/// </summary>
[JsonPropertyName("count")]
public int Count { get; init; }
/// <summary>
/// Gets the offset of the returned release groups.
/// </summary>
[JsonPropertyName("offset")]
public int Offset { get; init; }
/// <summary>
/// Gets the matching release groups.
/// </summary>
[JsonPropertyName("release-groups")]
public List<MusicBrainzReleaseGroupResponse> ReleaseGroups { get; init; } = [];
}
@@ -0,0 +1,120 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a release from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzReleaseResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the release.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the title of the release.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the disambiguation comment of the release.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the status of the release (e.g., Official, Bootleg).
/// </summary>
[JsonPropertyName("status")]
public string? Status { get; init; }
/// <summary>
/// Gets the date the release was issued.
/// </summary>
[JsonPropertyName("date")]
public string? Date { get; init; }
/// <summary>
/// Gets the ISO 3166-1 alpha-2 code of the country the release was issued in.
/// </summary>
[JsonPropertyName("country")]
public string? Country { get; init; }
/// <summary>
/// Gets the release events of the release.
/// </summary>
[JsonPropertyName("release-events")]
public List<MusicBrainzReleaseEventResponse> ReleaseEvents { get; init; } = [];
/// <summary>
/// Gets the barcode of the release.
/// </summary>
[JsonPropertyName("barcode")]
public string? Barcode { get; init; }
/// <summary>
/// Gets the outermost packaging of the release.
/// </summary>
[JsonPropertyName("packaging")]
public string? Packaging { get; init; }
/// <summary>
/// Gets the language and script of the titles of the release.
/// </summary>
[JsonPropertyName("text-representation")]
public MusicBrainzTextRepresentationResponse? TextRepresentation { get; init; }
/// <summary>
/// Gets the artist credit of the release.
/// </summary>
[JsonPropertyName("artist-credit")]
public List<MusicBrainzArtistCreditResponse> ArtistCredit { get; init; } = [];
/// <summary>
/// Gets the release group the release belongs to.
/// </summary>
[JsonPropertyName("release-group")]
public MusicBrainzReleaseGroupResponse? ReleaseGroup { get; init; }
/// <summary>
/// Gets the label information of the release.
/// </summary>
[JsonPropertyName("label-info")]
public List<MusicBrainzLabelInfoResponse> LabelInfo { get; init; } = [];
/// <summary>
/// Gets the media of the release.
/// </summary>
[JsonPropertyName("media")]
public List<MusicBrainzMediumResponse> Media { get; init; } = [];
/// <summary>
/// Gets the ASIN (Amazon Standard Identification Number) of the release.
/// </summary>
[JsonPropertyName("asin")]
public string? Asin { get; init; }
/// <summary>
/// Gets the tags of the release.
/// </summary>
[JsonPropertyName("tags")]
public List<MusicBrainzTagResponse> Tags { get; init; } = [];
/// <summary>
/// Gets the genres of the release.
/// </summary>
[JsonPropertyName("genres")]
public List<MusicBrainzTagResponse> Genres { get; init; } = [];
/// <summary>
/// Gets the relationships of the release to other entities (e.g., its producers and engineers).
/// </summary>
[JsonPropertyName("relations")]
public List<MusicBrainzRelationResponse> Relations { get; init; } = [];
}
@@ -0,0 +1,35 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a tag or a genre of a MusicBrainz entity.
/// </summary>
internal sealed record MusicBrainzTagResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the genre, when the tag is a genre.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the name of the tag.
/// </summary>
[JsonPropertyName("name")]
public string? Name { get; init; }
/// <summary>
/// Gets the disambiguation comment of the genre, when the tag is a genre.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the number of votes the tag received.
/// </summary>
[JsonPropertyName("count")]
public int Count { get; init; }
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for the language and script of the titles of a MusicBrainz release.
/// </summary>
internal sealed record MusicBrainzTextRepresentationResponse
{
/// <summary>
/// Gets the ISO 639-3 language code of the release.
/// </summary>
[JsonPropertyName("language")]
public string? Language { get; init; }
/// <summary>
/// Gets the ISO 15924 script code of the release.
/// </summary>
[JsonPropertyName("script")]
public string? Script { get; init; }
}
@@ -0,0 +1,47 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a track of a medium of a MusicBrainz release, including the recording it is a performance of.
/// </summary>
internal sealed record MusicBrainzTrackResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the track.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the track number, as displayed on the medium (for example, "1" or "A1").
/// </summary>
[JsonPropertyName("number")]
public string? Number { get; init; }
/// <summary>
/// Gets the position of the track within its medium.
/// </summary>
[JsonPropertyName("position")]
public int Position { get; init; }
/// <summary>
/// Gets the title of the track.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the length of the track in milliseconds.
/// </summary>
[JsonPropertyName("length")]
public long? Length { get; init; }
/// <summary>
/// Gets the recording the track is a performance of.
/// </summary>
[JsonPropertyName("recording")]
public MusicBrainzRecordingResponse? Recording { get; init; }
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a URL from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzUrlResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the URL.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the resource the URL points to.
/// </summary>
[JsonPropertyName("resource")]
public string? Resource { get; init; }
}
@@ -0,0 +1,66 @@
#region ========================================================================= USING =====================================================================================
using System.Collections.Generic;
using System.Text.Json.Serialization;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
/// <summary>
/// Represents a response for a work from the MusicBrainz API.
/// </summary>
internal sealed record MusicBrainzWorkResponse
{
/// <summary>
/// Gets the MusicBrainz identifier of the work.
/// </summary>
[JsonPropertyName("id")]
public string? Id { get; init; }
/// <summary>
/// Gets the title of the work.
/// </summary>
[JsonPropertyName("title")]
public string? Title { get; init; }
/// <summary>
/// Gets the MusicBrainz type of the work.
/// </summary>
[JsonPropertyName("type")]
public string? Type { get; init; }
/// <summary>
/// Gets the disambiguation comment of the work.
/// </summary>
[JsonPropertyName("disambiguation")]
public string? Disambiguation { get; init; }
/// <summary>
/// Gets the languages of the work.
/// </summary>
[JsonPropertyName("languages")]
public List<string> Languages { get; init; } = [];
/// <summary>
/// Gets the ISWC (International Standard Musical Work Code) of the work.
/// </summary>
[JsonPropertyName("iswcs")]
public List<string> Iswcs { get; init; } = [];
/// <summary>
/// Gets the relationships of the work to other entities (e.g., its composers and lyricists).
/// </summary>
[JsonPropertyName("relations")]
public List<MusicBrainzRelationResponse> Relations { get; init; } = [];
/// <summary>
/// Gets the tags of the work.
/// </summary>
[JsonPropertyName("tags")]
public List<MusicBrainzTagResponse> Tags { get; init; } = [];
/// <summary>
/// Gets the genres of the work.
/// </summary>
[JsonPropertyName("genres")]
public List<MusicBrainzTagResponse> Genres { get; init; } = [];
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using System;
#endregion
namespace Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
/// <summary>
/// Data transfer object for the settings that configure the MusicBrainz metadata plugin.
/// </summary>
internal sealed class MusicBrainzSettingsDto
{
/// <summary>
/// Gets or sets the base URL of the MusicBrainz web service the requests are sent to.
/// Defaults to the public MusicBrainz web service, and can point to a self hosted mirror instead.
/// </summary>
public string BaseUrl { get; set; } = "https://musicbrainz.org/ws/2/";
/// <summary>
/// Gets or sets a value indicating whether the base URL is allowed to point at a private or local host, for a self hosted mirror on a local
/// network. Defaults to <see langword="false"/>, so that a misconfigured base URL cannot silently reach a local service.
/// </summary>
public bool DoesAllowPrivateBaseUrl { get; set; }
/// <summary>
/// Gets or sets the user agent sent with every request to the MusicBrainz API.
/// </summary>
public string UserAgent { get; set; } = "Lumina-MusicBrainz/1.0";
/// <summary>
/// Gets or sets the contact email sent with every request to the MusicBrainz API.
/// </summary>
public string? ContactEmail { get; set; }
/// <summary>
/// Gets or sets the maximum number of results returned by a single search.
/// </summary>
public int SearchResultLimit { get; set; } = 10;
/// <summary>
/// Gets or sets the maximum number of releases fetched for a single release group.
/// </summary>
public int ReleaseLookupLimit { get; set; } = 25;
/// <summary>
/// Gets or sets the minimum interval between consecutive requests to the MusicBrainz API.
/// MusicBrainz requires client applications to make no more than one request per second.
/// </summary>
public TimeSpan MinimumRequestInterval { get; set; } = TimeSpan.FromSeconds(1.0);
}
@@ -0,0 +1,336 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using Lumina.Plugins.MusicBrainz.Core.Settings;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core.Api;
/// <summary>
/// HTTP client that calls the MusicBrainz web service and deserializes its JSON responses into typed response models.
/// </summary>
internal sealed class MusicBrainzHttpClient
{
private readonly HttpClient _httpClient;
private readonly MusicBrainzSettingsProvider _settingsProvider;
private readonly MusicBrainzRequestThrottle _requestThrottle;
private readonly MusicBrainzResponseCache _responseCache;
private static readonly JsonSerializerOptions s_serializerOptions = new(JsonSerializerDefaults.Web)
{
NumberHandling = JsonNumberHandling.AllowReadingFromString
};
// Transient failures and rate limiting are retried with an exponential backoff, so a single hiccup does not mark an item as failed to enrich.
private const int MAXIMUM_ATTEMPT_COUNT = 4;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzHttpClient"/> class.
/// </summary>
/// <param name="httpClient">The <see cref="HttpClient"/> used to send requests to the MusicBrainz web service.</param>
/// <param name="settingsProvider">The provider of the settings that configure the MusicBrainz web service requests.</param>
/// <param name="requestThrottle">The process-wide throttle that spaces out the requests sent to the MusicBrainz web service.</param>
/// <param name="responseCache">The process-wide cache that avoids fetching the same entity more than once during a run.</param>
public MusicBrainzHttpClient(HttpClient httpClient, MusicBrainzSettingsProvider settingsProvider, MusicBrainzRequestThrottle requestThrottle, MusicBrainzResponseCache responseCache)
{
_httpClient = httpClient;
_settingsProvider = settingsProvider;
_requestThrottle = requestThrottle;
_responseCache = responseCache;
}
/// <summary>
/// Looks up the artist identified by <paramref name="musicBrainzArtistId"/>.
/// </summary>
/// <param name="musicBrainzArtistId">The MusicBrainz identifier of the artist.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The artist, or <see langword="null"/> when no artist was found.</returns>
public Task<MusicBrainzArtistResponse?> GetArtistAsync(Guid musicBrainzArtistId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzArtistResponse>(
$"artist/{musicBrainzArtistId:D}?inc=aliases+tags+genres+url-rels+artist-rels+ratings&fmt=json", cancellationToken);
}
/// <summary>
/// Searches MusicBrainz for artists matching the provided query.
/// </summary>
/// <param name="query">The search query.</param>
/// <param name="limit">The maximum number of results to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of matching artists.</returns>
public async Task<IReadOnlyList<MusicBrainzArtistResponse>> SearchArtistsAsync(string query, int limit, CancellationToken cancellationToken)
{
MusicBrainzArtistSearchResponse? response = await GetJsonOrNullAsync<MusicBrainzArtistSearchResponse>(
$"artist?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
cancellationToken).ConfigureAwait(false);
return response?.Artists ?? [];
}
/// <summary>
/// Looks up the release group identified by <paramref name="musicBrainzReleaseGroupId"/>.
/// </summary>
/// <param name="musicBrainzReleaseGroupId">The MusicBrainz identifier of the release group.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The release group, or <see langword="null"/> when no release group was found.</returns>
public Task<MusicBrainzReleaseGroupResponse?> GetReleaseGroupAsync(Guid musicBrainzReleaseGroupId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzReleaseGroupResponse>(
$"release-group/{musicBrainzReleaseGroupId:D}?inc=artist-credits+tags+genres+ratings&fmt=json", cancellationToken);
}
/// <summary>
/// Searches MusicBrainz for release groups matching the provided query.
/// </summary>
/// <param name="query">The search query.</param>
/// <param name="limit">The maximum number of results to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of matching release groups.</returns>
public async Task<IReadOnlyList<MusicBrainzReleaseGroupResponse>> SearchReleaseGroupsAsync(string query, int limit, CancellationToken cancellationToken)
{
MusicBrainzReleaseGroupSearchResponse? response = await GetJsonOrNullAsync<MusicBrainzReleaseGroupSearchResponse>(
$"release-group?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
cancellationToken).ConfigureAwait(false);
return response?.ReleaseGroups ?? [];
}
/// <summary>
/// Looks up the release identified by <paramref name="musicBrainzReleaseId"/>.
/// </summary>
/// <param name="musicBrainzReleaseId">The MusicBrainz identifier of the release.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The release, or <see langword="null"/> when no release was found.</returns>
public Task<MusicBrainzReleaseResponse?> GetReleaseAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzReleaseResponse>(
$"release/{musicBrainzReleaseId:D}?inc=artist-credits+labels+release-groups+media+tags+genres+artist-rels&fmt=json", cancellationToken);
}
/// <summary>
/// Browses the releases that belong to the release group identified by <paramref name="musicBrainzReleaseGroupId"/>.
/// </summary>
/// <param name="musicBrainzReleaseGroupId">The MusicBrainz identifier of the release group.</param>
/// <param name="limit">The maximum number of releases to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of releases of the release group.</returns>
public async Task<IReadOnlyList<MusicBrainzReleaseResponse>> BrowseReleasesByReleaseGroupAsync(Guid musicBrainzReleaseGroupId, int limit, CancellationToken cancellationToken)
{
MusicBrainzReleaseBrowseResponse? response = await GetJsonOrNullAsync<MusicBrainzReleaseBrowseResponse>(
$"release?release-group={musicBrainzReleaseGroupId:D}&inc=artist-credits+labels+media&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
cancellationToken).ConfigureAwait(false);
return response?.Releases ?? [];
}
/// <summary>
/// Looks up the recording identified by <paramref name="musicBrainzRecordingId"/>.
/// </summary>
/// <param name="musicBrainzRecordingId">The MusicBrainz identifier of the recording.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The recording, or <see langword="null"/> when no recording was found.</returns>
public Task<MusicBrainzRecordingResponse?> GetRecordingAsync(Guid musicBrainzRecordingId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzRecordingResponse>(
$"recording/{musicBrainzRecordingId:D}?inc=artist-credits+isrcs+releases+tags+genres+work-rels+artist-rels+ratings&fmt=json", cancellationToken);
}
/// <summary>
/// Searches MusicBrainz for recordings matching the provided query.
/// </summary>
/// <param name="query">The search query.</param>
/// <param name="limit">The maximum number of results to return.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of matching recordings.</returns>
public async Task<IReadOnlyList<MusicBrainzRecordingResponse>> SearchRecordingsAsync(string query, int limit, CancellationToken cancellationToken)
{
MusicBrainzRecordingSearchResponse? response = await GetJsonOrNullAsync<MusicBrainzRecordingSearchResponse>(
$"recording?query={Uri.EscapeDataString(query)}&limit={Math.Clamp(limit, 1, 100).ToString(CultureInfo.InvariantCulture)}&fmt=json",
cancellationToken).ConfigureAwait(false);
return response?.Recordings ?? [];
}
/// <summary>
/// Looks up the recordings that carry the provided ISRC.
/// </summary>
/// <param name="isrc">The ISRC to look up.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The list of recordings that carry the ISRC.</returns>
public async Task<IReadOnlyList<MusicBrainzRecordingResponse>> GetRecordingsByIsrcAsync(string isrc, CancellationToken cancellationToken)
{
MusicBrainzRecordingListResponse? response = await GetJsonOrNullAsync<MusicBrainzRecordingListResponse>(
$"isrc/{Uri.EscapeDataString(isrc)}?inc=artist-credits+isrcs+work-rels+artist-rels&fmt=json", cancellationToken).ConfigureAwait(false);
return response?.Recordings ?? [];
}
/// <summary>
/// Looks up the work identified by <paramref name="musicBrainzWorkId"/>, together with its credited contributors.
/// </summary>
/// <param name="musicBrainzWorkId">The MusicBrainz identifier of the work.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The work, or <see langword="null"/> when no work was found.</returns>
public Task<MusicBrainzWorkResponse?> GetWorkAsync(Guid musicBrainzWorkId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzWorkResponse>(
$"work/{musicBrainzWorkId:D}?inc=artist-rels+tags+genres&fmt=json", cancellationToken);
}
/// <summary>
/// Looks up the release identified by <paramref name="musicBrainzReleaseId"/>, together with its media, tracks, recordings and all the data needed
/// to enrich those tracks, so that every track of the release is enriched from a single request.
/// </summary>
/// <param name="musicBrainzReleaseId">The MusicBrainz identifier of the release.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The release, with its media, tracks and recordings, or <see langword="null"/> when no release was found.</returns>
public Task<MusicBrainzReleaseResponse?> GetReleaseWithRecordingsAsync(Guid musicBrainzReleaseId, CancellationToken cancellationToken)
{
return GetJsonOrNullAsync<MusicBrainzReleaseResponse>(
$"release/{musicBrainzReleaseId:D}?inc=recordings+isrcs+artist-credits+tags+genres+ratings+work-rels+recording-level-rels+work-level-rels+artist-rels+release-groups+labels+media&fmt=json", cancellationToken);
}
/// <summary>
/// Gets the JSON resource at the given relative URL and deserializes it into <typeparamref name="TModel"/>.
/// </summary>
/// <typeparam name="TModel">The type to deserialize the JSON response into.</typeparam>
/// <param name="relativeUrl">The URL of the resource, relative to the base address.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The deserialized resource, or <see langword="null"/> when the resource was not found.</returns>
/// <remarks>Transient failures and rate limiting are handled by retrying the request up to three times.</remarks>
private async Task<TModel?> GetJsonOrNullAsync<TModel>(string relativeUrl, CancellationToken cancellationToken)
{
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
string cacheKey = string.Concat(settings.BaseUrl, relativeUrl);
if (_responseCache.TryGet(cacheKey, out string? cachedJson) && cachedJson is not null)
return JsonSerializer.Deserialize<TModel>(cachedJson, s_serializerOptions);
using HttpResponseMessage response = await SendAsync(settings, relativeUrl, cancellationToken).ConfigureAwait(false);
// A 404 means the entity does not exist in MusicBrainz, which is a normal miss rather than an error, so it is reported as no result.
if (response.StatusCode == HttpStatusCode.NotFound)
return default;
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
_responseCache.Set(cacheKey, json);
return JsonSerializer.Deserialize<TModel>(json, s_serializerOptions);
}
/// <summary>
/// Sends a GET request to the MusicBrainz web service, throttled to respect the configured minimum request interval unless the configured
/// base URL is not the real MusicBrainz service, in which case no rate limit is imposed. Transient failures, rate limiting and transport
/// exceptions are retried, preferring the delay requested by the web service when it is provided.
/// </summary>
/// <param name="settings">The settings that configure the MusicBrainz web service requests.</param>
/// <param name="relativeUrl">The URL of the resource, relative to the base address.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The HTTP response message for the request.</returns>
private async Task<HttpResponseMessage> SendAsync(MusicBrainzSettingsDto settings, string relativeUrl, CancellationToken cancellationToken)
{
EnsureRequestHeaders(settings);
// The rate limit is enforced by the MusicBrainz web service itself, so it is only observed when the requests actually reach it; a self hosted
// mirror, or any other configured base URL that is not the real service, is not limited by this process.
bool shouldThrottle = IsRealMusicBrainzService(settings.BaseUrl);
// A fresh request is created for every attempt, because an HTTP request cannot be sent more than once, and the throttle is applied to every
// attempt, so that the retries of a failed request cannot burst past the rate limit of the real MusicBrainz web service.
for (int attempt = 1; ; attempt++)
{
if (shouldThrottle)
await _requestThrottle.WaitAsync(settings.MinimumRequestInterval, cancellationToken).ConfigureAwait(false);
bool isLastAttempt = attempt >= MAXIMUM_ATTEMPT_COUNT;
HttpResponseMessage response;
try
{
HttpRequestMessage request = new(HttpMethod.Get, BuildRequestUri(settings.BaseUrl, relativeUrl));
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
}
catch (HttpRequestException) when (!isLastAttempt)
{
await Task.Delay(GetRetryDelay(attempt, null), cancellationToken).ConfigureAwait(false);
continue;
}
if (!isLastAttempt && (response.StatusCode == HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500))
{
TimeSpan retryDelay = GetRetryDelay(attempt, response);
// The response of a failed attempt is not returned, so it must be disposed here to release its connection.
response.Dispose();
await Task.Delay(retryDelay, cancellationToken).ConfigureAwait(false);
continue;
}
return response;
}
}
/// <summary>
/// Gets the delay to wait before the next attempt, preferring the delay requested by the MusicBrainz web service when it is provided.
/// </summary>
/// <param name="attempt">The one based number of the attempt that just failed.</param>
/// <param name="response">The response of the failed attempt, when the failure was a response rather than a transport exception.</param>
/// <returns>The delay to wait before the next attempt.</returns>
private static TimeSpan GetRetryDelay(int attempt, HttpResponseMessage? response)
{
if (response?.Headers.RetryAfter is { } retryAfter)
{
if (retryAfter.Delta is TimeSpan delta)
return delta;
if (retryAfter.Date is DateTimeOffset date)
{
TimeSpan wait = date - DateTimeOffset.UtcNow;
if (wait > TimeSpan.Zero)
return wait;
}
}
return TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt));
}
/// <summary>
/// Determines whether the provided base URL points to the real MusicBrainz web service, which is the only one whose rate limit is observed.
/// </summary>
/// <param name="baseUrl">The base URL of the MusicBrainz web service the requests are sent to.</param>
/// <returns><see langword="true"/> when the base URL points to the real MusicBrainz web service, otherwise <see langword="false"/>.</returns>
private static bool IsRealMusicBrainzService(string baseUrl)
{
if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out Uri? baseUri))
return false;
return baseUri.Host.Equals("musicbrainz.org", StringComparison.OrdinalIgnoreCase)
|| baseUri.Host.EndsWith(".musicbrainz.org", StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Applies the request headers configured in the <paramref name="settings"/> onto the underlying HTTP client, unless they are already set.
/// </summary>
/// <param name="settings">The settings that configure the MusicBrainz web service requests.</param>
private void EnsureRequestHeaders(MusicBrainzSettingsDto settings)
{
// The headers live on the underlying HttpClient, which is reused across the calls of this client, so they are applied only once.
if (_httpClient.DefaultRequestHeaders.UserAgent.Count == 0)
{
string userAgent = string.IsNullOrWhiteSpace(settings.ContactEmail)
? settings.UserAgent
: $"{settings.UserAgent} ( {settings.ContactEmail} )";
_httpClient.DefaultRequestHeaders.UserAgent.ParseAdd(userAgent);
}
}
/// <summary>
/// Combines the configured base URL with the given relative URL into the absolute URI of a request.
/// </summary>
/// <param name="baseUrl">The base URL of the MusicBrainz web service the requests are sent to.</param>
/// <param name="relativeUrl">The URL of the resource, relative to the base URL.</param>
/// <returns>The absolute URI of the request.</returns>
private static Uri BuildRequestUri(string baseUrl, string relativeUrl)
{
string normalizedBaseUrl = baseUrl.EndsWith('/') ? baseUrl : string.Concat(baseUrl, "/");
return new Uri(new Uri(normalizedBaseUrl, UriKind.Absolute), relativeUrl);
}
}
@@ -0,0 +1,49 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core.Api;
/// <summary>
/// Spaces out the requests sent to the MusicBrainz web service, so the configured minimum request interval is respected across every caller in the process.
/// </summary>
internal sealed class MusicBrainzRequestThrottle
{
private readonly SemaphoreSlim _gate = new(1, 1);
// The timestamp of the last reserved request slot, shared process wide, so the configured interval is enforced between requests no matter
// which caller sends them.
private DateTimeOffset _lastRequestAt = DateTimeOffset.MinValue;
/// <summary>
/// Waits until the minimum interval elapsed since the previous reserved request, then reserves the next request slot.
/// </summary>
/// <param name="minimumRequestInterval">The minimum amount of time that must elapse between two consecutive requests.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>A task that completes once the caller may send its request.</returns>
public async Task WaitAsync(TimeSpan minimumRequestInterval, CancellationToken cancellationToken)
{
// The gate is held across the delay, so concurrent callers queue up and each one is released only once the interval elapsed since the
// previous reserved slot.
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// A non positive interval means the callers are not spaced out at all, and it must not be added to the initial timestamp, which would underflow it.
if (minimumRequestInterval > TimeSpan.Zero)
{
DateTimeOffset earliestNextRequest = _lastRequestAt + minimumRequestInterval;
TimeSpan delay = earliestNextRequest - DateTimeOffset.UtcNow;
if (delay > TimeSpan.Zero)
await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
}
_lastRequestAt = DateTimeOffset.UtcNow;
}
finally
{
_gate.Release();
}
}
}
@@ -0,0 +1,140 @@
#region ========================================================================= USING =====================================================================================
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core.Api;
/// <summary>
/// In-memory cache of the responses returned by the MusicBrainz web service, keyed by the requested URL.
/// It removes the repeated lookups of the same entity during a run, and expires its entries after a bounded time.
/// </summary>
internal sealed class MusicBrainzResponseCache
{
/// <summary>
/// The maximum number of responses the cache keeps.
/// </summary>
internal const int MAXIMUM_ENTRY_COUNT = 20_000;
/// <summary>
/// The maximum total number of characters of the cached response bodies.
/// </summary>
internal const long MAXIMUM_CHARACTER_COUNT = 100_000_000;
/// <summary>
/// The percentage of a budget that the cache is trimmed down to when it exceeds that budget. Trimming to a lower water mark keeps the
/// eviction from running on every write once a budget is reached.
/// </summary>
private const int TRIM_TARGET_PERCENT = 90;
private static readonly TimeSpan s_timeToLive = TimeSpan.FromMinutes(15);
private readonly int _maximumEntryCount;
private readonly long _maximumCharacterCount;
private readonly TimeSpan _timeToLive;
private readonly ConcurrentDictionary<string, CacheEntry> _entries = new(StringComparer.Ordinal);
// The dictionary is thread safe on its own, but the character budget is a read modify write over it, so the size bookkeeping and the eviction
// are guarded by a lock, while reads stay lock free.
private readonly Lock _sizeGate = new();
private long _cachedCharacterCount;
// Monotonically increasing insertion stamp, used to evict the oldest entries first.
private long _sequence;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzResponseCache"/> class with the default budgets and time to live.
/// </summary>
public MusicBrainzResponseCache()
{
_maximumEntryCount = MAXIMUM_ENTRY_COUNT;
_maximumCharacterCount = MAXIMUM_CHARACTER_COUNT;
_timeToLive = s_timeToLive;
}
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzResponseCache"/> class with the provided budgets and time to live.
/// </summary>
/// <param name="maximumEntryCount">The maximum number of responses the cache keeps.</param>
/// <param name="maximumCharacterCount">The maximum total number of characters of the cached response bodies.</param>
/// <param name="timeToLive">The amount of time a cached response stays valid.</param>
internal MusicBrainzResponseCache(int maximumEntryCount, long maximumCharacterCount, TimeSpan timeToLive)
{
_maximumEntryCount = maximumEntryCount;
_maximumCharacterCount = maximumCharacterCount;
_timeToLive = timeToLive;
}
/// <summary>
/// Tries to get the cached response body for <paramref name="key"/>.
/// </summary>
/// <param name="key">The key of the cached response.</param>
/// <param name="json">The cached response body, when found.</param>
/// <returns><see langword="true"/> when an unexpired response was found, otherwise <see langword="false"/>.</returns>
public bool TryGet(string key, out string? json)
{
// An expired entry is treated as a miss instead of being removed here, so readers never take the lock; a later write reclaims it.
if (_entries.TryGetValue(key, out CacheEntry? entry) && entry.ExpiresOnUtc > DateTime.UtcNow)
{
json = entry.Json;
return true;
}
json = null;
return false;
}
/// <summary>
/// Adds or replaces the cached response body for <paramref name="key"/>, then trims the cache back to its budgets.
/// </summary>
/// <param name="key">The key of the cached response.</param>
/// <param name="json">The response body to cache.</param>
public void Set(string key, string json)
{
// A single response larger than the whole character budget can never be admitted, so it is rejected before it disturbs the cache.
if (json.Length > _maximumCharacterCount)
return;
lock (_sizeGate)
{
if (_entries.TryRemove(key, out CacheEntry? existing))
_cachedCharacterCount -= existing.Json.Length;
_entries[key] = new CacheEntry(json, DateTime.UtcNow.Add(_timeToLive), ++_sequence);
_cachedCharacterCount += json.Length;
if (_entries.Count > _maximumEntryCount || _cachedCharacterCount > _maximumCharacterCount)
TrimToBudget();
}
}
/// <summary>
/// Removes the expired entries, and then the oldest unexpired entries, until the cache is back within its entry count and character budgets.
/// </summary>
private void TrimToBudget()
{
DateTime utcNow = DateTime.UtcNow;
bool isOverEntryCount = _entries.Count > _maximumEntryCount;
bool isOverCharacterCount = _cachedCharacterCount > _maximumCharacterCount;
int entryTarget = Math.Max(1, _maximumEntryCount * TRIM_TARGET_PERCENT / 100);
long characterTarget = Math.Max(1, _maximumCharacterCount * TRIM_TARGET_PERCENT / 100);
// Entries are evicted in insertion order, so the most recently cached responses survive; an expired entry is always removed, even when
// a budget was not exceeded, so the cache keeps reclaiming dead entries.
foreach (KeyValuePair<string, CacheEntry> candidate in _entries.OrderBy(entry => entry.Value.Sequence))
{
bool isExpired = candidate.Value.ExpiresOnUtc <= utcNow;
bool needsEntryTrim = isOverEntryCount && _entries.Count > entryTarget;
bool needsCharacterTrim = isOverCharacterCount && _cachedCharacterCount > characterTarget;
if (!isExpired && !needsEntryTrim && !needsCharacterTrim)
break;
if (_entries.TryRemove(candidate.Key, out CacheEntry? removed))
_cachedCharacterCount -= removed.Json.Length;
}
}
private sealed record CacheEntry(string Json, DateTime ExpiresOnUtc, long Sequence);
}
@@ -0,0 +1,759 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.Common;
using Lumina.Contracts.DTO.MediaContributors;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary;
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.AudioLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.Common;
using Lumina.Domain.SharedKernel.Common.Enums.MediaContributors;
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core.Mapping;
/// <summary>
/// Maps MusicBrainz web service responses into the application's media metadata DTOs.
/// </summary>
internal static partial class MusicBrainzMapper
{
/// <summary>
/// The neutral cultures of the process, indexed by both their two letter and three letter ISO 639 codes.
/// Built once, because the available cultures do not change during the lifetime of the process.
/// </summary>
private static readonly IReadOnlyDictionary<string, CultureInfo> s_neutralCulturesByCode = BuildNeutralCultureLookup();
/// <summary>
/// Matches a four digit year.
/// </summary>
[GeneratedRegex(@"\b(?:1[0-9]{3}|20[0-9]{2}|2100)\b")]
private static partial Regex YearPattern();
/// <summary>
/// Maps a MusicBrainz artist response into artist metadata.
/// </summary>
/// <param name="artist">The artist response to map.</param>
/// <returns>The mapped artist metadata.</returns>
public static ArtistMetadataDto MapArtist(MusicBrainzArtistResponse artist)
{
(List<MediaContributorDto> contributors, string? website) = MapArtistRelations(artist.Relations);
return new ArtistMetadataDto(
Name: NullIfWhiteSpace(artist.Name),
SortName: NullIfWhiteSpace(artist.SortName),
Disambiguation: NullIfWhiteSpace(artist.Disambiguation),
Type: MapArtistType(artist.Type),
Gender: MapArtistGender(artist.Gender),
Country: NullIfWhiteSpace(artist.Country),
Area: MapArea(artist.Area),
BeginArea: MapArea(artist.BeginArea),
EndArea: MapArea(artist.EndArea),
LifeSpanBegin: ParseDate(artist.LifeSpan?.Begin).Date,
LifeSpanEnd: ParseDate(artist.LifeSpan?.End).Date,
IsEnded: artist.LifeSpan?.IsEnded ?? false,
Website: website,
MusicBrainzArtistId: ParseGuid(artist.Id),
Ipis: [.. artist.Ipis.Where(ipi => !string.IsNullOrWhiteSpace(ipi))],
Isnis: [.. artist.Isnis.Where(isni => !string.IsNullOrWhiteSpace(isni))],
Aliases: [.. artist.Aliases.Select(MapAlias)],
Genres: MapGenres(artist.Genres),
Tags: MapTags(artist.Tags),
Ratings: MapRating(artist.Rating),
Contributors: contributors);
}
/// <summary>
/// Maps a MusicBrainz release group, and optionally one of its releases, into album metadata.
/// </summary>
/// <param name="releaseGroup">The release group response to map.</param>
/// <param name="release">The selected release of the release group, or <see langword="null"/> when no release was selected.</param>
/// <returns>The mapped album metadata.</returns>
public static AlbumMetadataDto MapAlbum(MusicBrainzReleaseGroupResponse releaseGroup, MusicBrainzReleaseResponse? release)
{
(DateOnly? originalDate, int? originalYear) = ParseDate(releaseGroup.FirstReleaseDate);
(DateOnly? reReleaseDate, int? reReleaseYear) = ParseDate(release?.Date);
if (reReleaseDate is not null && originalDate is not null && reReleaseDate.Value.Year == originalDate.Value.Year)
{
reReleaseDate = null;
reReleaseYear = null;
}
string? releaseArtistId = releaseGroup.ArtistCredit.Select(credit => credit.Artist?.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id))
?? release?.ArtistCredit.Select(credit => credit.Artist?.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id));
List<MediaContributorDto> contributors = MapArtistCredit(releaseGroup.ArtistCredit);
if (contributors.Count == 0 && release is not null)
contributors = MapArtistCredit(release.ArtistCredit);
if (release is not null)
AddContributors(contributors, MapContributorsFromRelations(release.Relations));
List<MusicBrainzMediumResponse> media = release?.Media ?? [];
int totalTracks = media.Sum(medium => medium.TrackCount);
// A MusicBrainz release can carry several labels and catalog numbers: the label stores the first one, while every catalog number is kept.
string? label = release?.LabelInfo.FirstOrDefault()?.Label?.Name;
List<string> catalogNumbers = [.. (release?.LabelInfo ?? [])
.Select(labelInfo => NullIfWhiteSpace(labelInfo.CatalogNumber))
.Where(catalogNumber => catalogNumber is not null)
.Select(catalogNumber => catalogNumber!)
.Distinct(StringComparer.OrdinalIgnoreCase)];
return new AlbumMetadataDto(
Title: NullIfWhiteSpace(releaseGroup.Title) ?? NullIfWhiteSpace(release?.Title),
OriginalTitle: null,
Description: null,
Disambiguation: NullIfWhiteSpace(releaseGroup.Disambiguation),
ReleaseInfo: new ReleaseInfoDto(
OriginalReleaseDate: originalDate,
OriginalReleaseYear: originalYear,
ReReleaseDate: reReleaseDate,
ReReleaseYear: reReleaseYear,
ReleaseCountry: MapReleaseCountry(release?.Country),
ReleaseVersion: NullIfWhiteSpace(release?.Disambiguation)),
Language: MapLanguage(release?.TextRepresentation?.Language),
OriginalLanguage: null,
Tags: MapTags(releaseGroup.Tags),
Genres: MapGenres(releaseGroup.Genres),
Script: NullIfWhiteSpace(release?.TextRepresentation?.Script),
ReleaseTypes: MapReleaseTypes(releaseGroup.PrimaryType, releaseGroup.SecondaryTypes),
ReleaseStatus: MapReleaseStatus(release?.Status),
MediaFormat: MapMediaFormat(media.FirstOrDefault()?.Format),
Packaging: MapPackaging(release?.Packaging),
TotalDiscs: media.Count > 0 ? media.Count : null,
TotalTracks: totalTracks > 0 ? totalTracks : null,
Barcode: NullIfWhiteSpace(release?.Barcode),
CatalogNumbers: catalogNumbers,
Label: NullIfWhiteSpace(label),
ASIN: NullIfWhiteSpace(release?.Asin),
MusicBrainzReleaseId: ParseGuid(release?.Id),
MusicBrainzReleaseGroupId: ParseGuid(releaseGroup.Id),
MusicBrainzReleaseArtistId: ParseGuid(releaseArtistId),
Contributors: contributors,
Ratings: MapRating(releaseGroup.Rating),
ReleaseTitle: NullIfWhiteSpace(release?.Title));
}
/// <summary>
/// Maps a MusicBrainz recording, and optionally its work and release, into track metadata.
/// </summary>
/// <param name="recording">The recording response to map.</param>
/// <param name="work">The work the recording is an instance of, or <see langword="null"/> when the recording has no work.</param>
/// <param name="release">The release the recording appears on, or <see langword="null"/> when it is not known.</param>
/// <returns>The mapped track metadata.</returns>
public static AudioMetadataDto MapTrack(MusicBrainzRecordingResponse recording, MusicBrainzWorkResponse? work, MusicBrainzReleaseResponse? release)
{
(DateOnly? releaseDate, int? releaseYear) = ParseDate(recording.FirstReleaseDate);
// A recording embedded in a release lookup does not carry its own first release date, so the date of the release the track appears on is used
// instead, rather than leaving the track without any release date at all.
if (releaseYear is null)
(releaseDate, releaseYear) = ParseDate(release?.Date);
List<MediaContributorDto> contributors = MapArtistCredit(recording.ArtistCredit);
AddContributors(contributors, MapContributorsFromRelations(recording.Relations));
if (work is not null)
AddContributors(contributors, MapContributorsFromRelations(work.Relations));
return new AudioMetadataDto(
Title: NullIfWhiteSpace(recording.Title),
OriginalTitle: null,
Description: null,
Disambiguation: NullIfWhiteSpace(recording.Disambiguation),
ReleaseInfo: new ReleaseInfoDto(
OriginalReleaseDate: releaseDate,
OriginalReleaseYear: releaseYear,
ReReleaseDate: null,
ReReleaseYear: null,
ReleaseCountry: null,
ReleaseVersion: null),
Language: MapLanguage(release?.TextRepresentation?.Language),
OriginalLanguage: null,
Tags: MapTags(recording.Tags),
Genres: MapGenres(recording.Genres),
Script: NullIfWhiteSpace(release?.TextRepresentation?.Script),
Key: null,
Bpm: null,
IsVideo: recording.IsVideo ?? false,
Work: work is null ? null : MapWork(work),
Isrcs: [.. recording.Isrcs.Where(isrc => !string.IsNullOrWhiteSpace(isrc)).Select(isrc => new IsrcDto(isrc))],
Moods: null,
DurationInSeconds: recording.Length is long length && length > 0 ? (int)(length / 1000) : null,
SampleRate: null,
Channels: null,
BitDepth: null,
AudioCodec: null,
Bitrate: null,
MusicBrainzRecordingId: ParseGuid(recording.Id),
MusicBrainzTrackId: null,
Contributors: contributors,
Ratings: MapRating(recording.Rating));
}
/// <summary>
/// Maps a MusicBrainz work into a work DTO.
/// </summary>
/// <param name="work">The work response to map.</param>
/// <returns>The mapped work.</returns>
public static MusicWorkDto MapWork(MusicBrainzWorkResponse work)
{
return new MusicWorkDto(
MusicBrainzWorkId: ParseGuid(work.Id),
Title: NullIfWhiteSpace(work.Title),
Type: NullIfWhiteSpace(work.Type),
Languages: [.. work.Languages.Select(MapLanguage).Where(language => language is not null).Select(language => language!)],
Iswcs: [.. work.Iswcs.Where(iswc => !string.IsNullOrWhiteSpace(iswc))]);
}
/// <summary>
/// Maps a MusicBrainz area into an area DTO.
/// </summary>
/// <param name="area">The area response to map.</param>
/// <returns>The mapped area, or <see langword="null"/> when no area is provided.</returns>
public static MusicAreaDto? MapArea(MusicBrainzAreaResponse? area)
{
if (area is null)
return null;
string? isoCode = area.Iso3166Part1Codes.FirstOrDefault() ?? area.Iso3166Part2Codes.FirstOrDefault();
return new MusicAreaDto(
MusicBrainzAreaId: ParseGuid(area.Id),
Name: NullIfWhiteSpace(area.Name),
SortName: NullIfWhiteSpace(area.SortName),
Disambiguation: NullIfWhiteSpace(area.Disambiguation),
Type: NullIfWhiteSpace(area.Type),
Iso3166Code: NullIfWhiteSpace(isoCode));
}
/// <summary>
/// Maps a MusicBrainz alias into an alias DTO.
/// </summary>
/// <param name="alias">The alias response to map.</param>
/// <returns>The mapped alias.</returns>
private static MusicArtistAliasDto MapAlias(MusicBrainzAliasResponse alias)
{
return new MusicArtistAliasDto(
Name: NullIfWhiteSpace(alias.Name),
SortName: NullIfWhiteSpace(alias.SortName),
Type: NullIfWhiteSpace(alias.Type),
Locale: NullIfWhiteSpace(alias.Locale),
IsPrimary: alias.IsPrimary ?? false,
BeginDate: ParseDate(alias.Begin).Date,
EndDate: ParseDate(alias.End).Date,
IsEnded: alias.IsEnded ?? false);
}
/// <summary>
/// Maps the genres of a MusicBrainz entity into genre DTOs.
/// </summary>
/// <param name="genres">The genre responses to map.</param>
/// <returns>The mapped genre DTOs.</returns>
private static List<GenreDto> MapGenres(IReadOnlyCollection<MusicBrainzTagResponse> genres)
{
return [.. genres
.Where(genre => !string.IsNullOrWhiteSpace(genre.Name))
.Select(genre => new GenreDto(genre.Name))
.DistinctBy(genre => genre.Name, StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// Maps the tags of a MusicBrainz entity into tag DTOs.
/// </summary>
/// <param name="tags">The tag responses to map.</param>
/// <returns>The mapped tag DTOs.</returns>
private static List<TagDto> MapTags(IReadOnlyCollection<MusicBrainzTagResponse> tags)
{
return [.. tags
.Where(tag => !string.IsNullOrWhiteSpace(tag.Name))
.Select(tag => new TagDto(tag.Name))
.DistinctBy(tag => tag.Name, StringComparer.OrdinalIgnoreCase)];
}
/// <summary>
/// Maps the rating of a MusicBrainz entity into a rating DTO.
/// </summary>
/// <param name="rating">The rating response to map.</param>
/// <returns>The mapped rating DTO, or an empty list when no rating is provided.</returns>
private static List<AudioRatingDto> MapRating(MusicBrainzRatingResponse? rating)
{
if (rating is null || (rating.Value is null && rating.VotesCount is null))
return [];
return [new AudioRatingDto(rating.Value, 5m, AudioRatingSource.MusicBrainz, rating.VotesCount)];
}
/// <summary>
/// Maps an ISO 639-3 language code into a language DTO.
/// </summary>
/// <param name="rawCode">The code to map.</param>
/// <returns>The mapped language, or <see langword="null"/> when the code is empty.</returns>
private static LanguageInfoDto? MapLanguage(string? rawCode)
{
if (string.IsNullOrWhiteSpace(rawCode))
return null;
string code = rawCode.Trim().ToLowerInvariant();
// A language code can list several languages, such as "eng/ara"; the first one is the language of the release.
string primaryCode = code.Split('/').Select(part => part.Trim()).FirstOrDefault(part => part.Length > 0) ?? code;
// These ISO 639-3 codes describe a language absence rather than a culture, so they cannot be resolved through a culture.
switch (primaryCode)
{
case "zxx":
return new LanguageInfoDto(primaryCode, "No linguistic content", null);
case "mul":
return new LanguageInfoDto(primaryCode, "Multiple languages", null);
case "und":
return new LanguageInfoDto(primaryCode, "Undetermined", null);
default:
break;
}
// Only neutral cultures are matched, because a specific culture would resolve to an arbitrary regional name such as "German (Austria)".
return s_neutralCulturesByCode.TryGetValue(primaryCode, out CultureInfo? culture)
? new LanguageInfoDto(culture.TwoLetterISOLanguageName, culture.EnglishName, culture.NativeName)
: new LanguageInfoDto(primaryCode, primaryCode, null);
}
/// <summary>
/// Builds the lookup of the process' neutral cultures, indexed by both their two letter and three letter ISO 639 codes.
/// </summary>
/// <returns>The neutral cultures, indexed by their ISO 639 codes.</returns>
private static IReadOnlyDictionary<string, CultureInfo> BuildNeutralCultureLookup()
{
Dictionary<string, CultureInfo> culturesByCode = new(StringComparer.OrdinalIgnoreCase);
foreach (CultureInfo culture in CultureInfo.GetCultures(CultureTypes.NeutralCultures))
{
// A culture without a two letter ISO 639 code is not a language, so it is skipped; the two letter code is the one carried by the DTOs.
if (culture.TwoLetterISOLanguageName.Length != 2)
continue;
culturesByCode.TryAdd(culture.ThreeLetterISOLanguageName, culture);
culturesByCode.TryAdd(culture.TwoLetterISOLanguageName, culture);
}
return culturesByCode;
}
/// <summary>
/// Maps the artist credit of a MusicBrainz entity into attributed performing contributors.
/// </summary>
/// <param name="artistCredit">The artist credit to map.</param>
/// <returns>The mapped contributors.</returns>
private static List<MediaContributorDto> MapArtistCredit(IReadOnlyCollection<MusicBrainzArtistCreditResponse> artistCredit)
{
List<MediaContributorDto> contributors = [];
foreach (MusicBrainzArtistCreditResponse credit in artistCredit)
{
string? name = NullIfWhiteSpace(credit.Name) ?? NullIfWhiteSpace(credit.Artist?.Name);
if (name is null)
continue;
AddContributor(contributors, name, MediaContributorRole.Performer);
}
return contributors;
}
/// <summary>
/// Maps the artist relations of a MusicBrainz entity into contributors, excluding the URL relations.
/// </summary>
/// <param name="relations">The relations to map.</param>
/// <returns>The mapped contributors.</returns>
private static List<MediaContributorDto> MapContributorsFromRelations(IReadOnlyCollection<MusicBrainzRelationResponse> relations)
{
List<MediaContributorDto> contributors = [];
foreach (MusicBrainzRelationResponse relation in relations)
{
if (!string.Equals(relation.TargetType, "artist", StringComparison.OrdinalIgnoreCase))
continue;
string? name = NullIfWhiteSpace(relation.Artist?.Name);
if (name is null)
continue;
AddContributor(contributors, name, MapRole(relation.Type, relation.Attributes));
}
return contributors;
}
/// <summary>
/// Maps the relations of an artist into its contributing members, and its official homepage.
/// </summary>
/// <param name="relations">The relations of the artist.</param>
/// <returns>The mapped contributors, and the official homepage of the artist.</returns>
private static (List<MediaContributorDto> Contributors, string? Website) MapArtistRelations(IReadOnlyCollection<MusicBrainzRelationResponse> relations)
{
List<MediaContributorDto> contributors = [];
string? website = null;
foreach (MusicBrainzRelationResponse relation in relations)
{
if (string.Equals(relation.TargetType, "url", StringComparison.OrdinalIgnoreCase))
{
if (website is null && string.Equals(relation.Type, "official homepage", StringComparison.OrdinalIgnoreCase))
website = NullIfWhiteSpace(relation.Url?.Resource);
continue;
}
if (!string.Equals(relation.TargetType, "artist", StringComparison.OrdinalIgnoreCase))
continue;
string? name = NullIfWhiteSpace(relation.Artist?.Name);
if (name is null)
continue;
AddContributor(contributors, name, MapRole(relation.Type, relation.Attributes));
}
return (contributors, website);
}
/// <summary>
/// Adds a contributor to the provided list, unless an identical name and role pair is already present.
/// </summary>
/// <param name="contributors">The contributors collected so far.</param>
/// <param name="displayName">The display name of the contributor.</param>
/// <param name="role">The role the contributor played.</param>
private static void AddContributor(List<MediaContributorDto> contributors, string displayName, MediaContributorRole role)
{
if (contributors.Any(contributor =>
string.Equals(contributor.Name?.DisplayName, displayName, StringComparison.OrdinalIgnoreCase) &&
contributor.Role == role))
return;
contributors.Add(new MediaContributorDto(new MediaContributorNameDto(displayName, null), role));
}
/// <summary>
/// Adds the <paramref name="incoming"/> contributors to <paramref name="contributors"/>, skipping the duplicate name and role pairs.
/// </summary>
/// <param name="contributors">The contributors collected so far.</param>
/// <param name="incoming">The contributors to add.</param>
private static void AddContributors(List<MediaContributorDto> contributors, IReadOnlyCollection<MediaContributorDto> incoming)
{
foreach (MediaContributorDto contributor in incoming)
{
if (contributor.Name?.DisplayName is not string displayName)
continue;
AddContributor(contributors, displayName, contributor.Role ?? MediaContributorRole.Other);
}
}
/// <summary>
/// Maps a MusicBrainz relationship type, and its attributes, into a canonical media contributor role.
/// </summary>
/// <param name="relationType">The relationship type to map.</param>
/// <param name="attributes">The attributes of the relationship.</param>
/// <returns>The mapped contributor role.</returns>
private static MediaContributorRole MapRole(string? relationType, IReadOnlyCollection<string> attributes)
{
// An instrument attribute is more specific than the generic relationship type, so it is preferred.
foreach (string attribute in attributes)
{
MediaContributorRole? attributed = MapInstrument(attribute);
if (attributed is not null)
return attributed.Value;
}
if (string.IsNullOrWhiteSpace(relationType))
return MediaContributorRole.Other;
string type = relationType.Trim().ToLowerInvariant();
if (type.Contains("executive producer", StringComparison.Ordinal))
return MediaContributorRole.ExecutiveProducer;
if (type.Contains("producer", StringComparison.Ordinal))
return MediaContributorRole.Producer;
if (type.Contains("remixer", StringComparison.Ordinal))
return MediaContributorRole.Remixer;
if (type.Contains("mix", StringComparison.Ordinal))
return MediaContributorRole.Mixer;
if (type.Contains("engineer", StringComparison.Ordinal) || type.Contains("mastering", StringComparison.Ordinal))
return MediaContributorRole.Engineer;
if (type.Contains("composer", StringComparison.Ordinal))
return MediaContributorRole.Composer;
if (type.Contains("writer", StringComparison.Ordinal))
return MediaContributorRole.Author;
if (type.Contains("lyricist", StringComparison.Ordinal))
return MediaContributorRole.Lyricist;
if (type.Contains("librettist", StringComparison.Ordinal))
return MediaContributorRole.Lyricist;
if (type.Contains("arranger", StringComparison.Ordinal))
return MediaContributorRole.Arranger;
if (type.Contains("conductor", StringComparison.Ordinal))
return MediaContributorRole.Conductor;
if (type.Contains("orchestrator", StringComparison.Ordinal))
return MediaContributorRole.Orchestrator;
if (type.Contains("backing vocals", StringComparison.Ordinal))
return MediaContributorRole.BackingVocals;
if (type.Contains("vocal", StringComparison.Ordinal))
return MediaContributorRole.Vocals;
if (type.Contains("member of band", StringComparison.Ordinal) || type.Contains("performer", StringComparison.Ordinal) || type.Contains("orchestra", StringComparison.Ordinal) || type.Contains("choir", StringComparison.Ordinal))
return MediaContributorRole.Performer;
return MediaContributorRole.Other;
}
/// <summary>
/// Maps a MusicBrainz instrument attribute into a canonical media contributor role.
/// </summary>
/// <param name="attribute">The instrument attribute to map.</param>
/// <returns>The mapped contributor role, or <see langword="null"/> when the attribute is not an instrument.</returns>
private static MediaContributorRole? MapInstrument(string? attribute)
{
if (string.IsNullOrWhiteSpace(attribute))
return null;
string value = attribute.Trim().ToLowerInvariant();
if (value.Contains("backing vocal", StringComparison.Ordinal))
return MediaContributorRole.BackingVocals;
if (value.Contains("vocal", StringComparison.Ordinal))
return MediaContributorRole.Vocals;
if (value.Contains("bass guitar", StringComparison.Ordinal))
return MediaContributorRole.BassGuitar;
if (value.Contains("guitar", StringComparison.Ordinal))
return MediaContributorRole.Guitar;
if (value.Contains("drum", StringComparison.Ordinal))
return MediaContributorRole.Drums;
if (value.Contains("percussion", StringComparison.Ordinal))
return MediaContributorRole.Percussion;
if (value.Contains("keyboard", StringComparison.Ordinal))
return MediaContributorRole.Keyboards;
if (value.Contains("piano", StringComparison.Ordinal))
return MediaContributorRole.Piano;
if (value.Contains("synthesizer", StringComparison.Ordinal) || value.Contains("synth", StringComparison.Ordinal))
return MediaContributorRole.Synthesizer;
if (value.Contains("string", StringComparison.Ordinal) || value.Contains("violin", StringComparison.Ordinal) || value.Contains("cello", StringComparison.Ordinal) || value.Contains("viola", StringComparison.Ordinal))
return MediaContributorRole.Strings;
if (value.Contains("brass", StringComparison.Ordinal) || value.Contains("trumpet", StringComparison.Ordinal) || value.Contains("trombone", StringComparison.Ordinal) || value.Contains("horn", StringComparison.Ordinal))
return MediaContributorRole.Brass;
if (value.Contains("woodwind", StringComparison.Ordinal) || value.Contains("flute", StringComparison.Ordinal) || value.Contains("saxophone", StringComparison.Ordinal) || value.Contains("clarinet", StringComparison.Ordinal))
return MediaContributorRole.Woodwinds;
return null;
}
/// <summary>
/// Maps a MusicBrainz artist type into the application enum.
/// </summary>
/// <param name="type">The artist type to map.</param>
/// <returns>The mapped artist type, or <see langword="null"/> when the type is unknown.</returns>
private static MusicArtistType? MapArtistType(string? type)
{
if (string.IsNullOrWhiteSpace(type))
return null;
return type.Trim().ToLowerInvariant() switch
{
"person" => MusicArtistType.Person,
"group" => MusicArtistType.Group,
"orchestra" => MusicArtistType.Orchestra,
"choir" => MusicArtistType.Choir,
"character" => MusicArtistType.Character,
"other" => MusicArtistType.Other,
_ => null
};
}
/// <summary>
/// Maps a MusicBrainz gender into the application enum.
/// </summary>
/// <param name="gender">The gender to map.</param>
/// <returns>The mapped gender, or <see langword="null"/> when the gender is unknown.</returns>
private static MusicArtistGender? MapArtistGender(string? gender)
{
if (string.IsNullOrWhiteSpace(gender))
return null;
return gender.Trim().ToLowerInvariant() switch
{
"male" => MusicArtistGender.Male,
"female" => MusicArtistGender.Female,
"other" => MusicArtistGender.Other,
"not applicable" => MusicArtistGender.NotApplicable,
_ => null
};
}
/// <summary>
/// Maps the primary and secondary types of a release group into the application enum.
/// </summary>
/// <param name="primaryType">The primary type of the release group.</param>
/// <param name="secondaryTypes">The secondary types of the release group.</param>
/// <returns>The mapped release types.</returns>
private static List<MusicReleaseType> MapReleaseTypes(string? primaryType, IReadOnlyCollection<string> secondaryTypes)
{
List<MusicReleaseType> releaseTypes = [];
MusicReleaseType? primary = MapReleaseType(primaryType);
if (primary is not null)
releaseTypes.Add(primary.Value);
foreach (string secondaryType in secondaryTypes)
{
MusicReleaseType? mapped = MapReleaseType(secondaryType);
if (mapped is not null && !releaseTypes.Contains(mapped.Value))
releaseTypes.Add(mapped.Value);
}
return releaseTypes;
}
/// <summary>
/// Maps a single MusicBrainz release type into the application enum.
/// </summary>
/// <param name="type">The release type to map.</param>
/// <returns>The mapped release type, or <see langword="null"/> when the type is unknown.</returns>
private static MusicReleaseType? MapReleaseType(string? type)
{
if (string.IsNullOrWhiteSpace(type))
return null;
return type.Trim().ToLowerInvariant() switch
{
"album" => MusicReleaseType.Album,
"single" => MusicReleaseType.Single,
"ep" => MusicReleaseType.Ep,
"broadcast" => MusicReleaseType.Broadcast,
"other" => MusicReleaseType.Other,
"compilation" => MusicReleaseType.Compilation,
"live" => MusicReleaseType.Live,
"soundtrack" => MusicReleaseType.Soundtrack,
"spokenword" => MusicReleaseType.SpokenWord,
"audio drama" => MusicReleaseType.AudioDrama,
"audiobook" => MusicReleaseType.AudioBook,
"demo" => MusicReleaseType.Demo,
"dj-mix" => MusicReleaseType.DjMix,
"field recording" => MusicReleaseType.FieldRecording,
"interview" => MusicReleaseType.Interview,
"mixtape/street" => MusicReleaseType.Mixtape,
"remix" => MusicReleaseType.Remix,
_ => null
};
}
/// <summary>
/// Maps a MusicBrainz release status into the application enum.
/// </summary>
/// <param name="status">The release status to map.</param>
/// <returns>The mapped release status, or <see langword="null"/> when the status is unknown.</returns>
private static MusicReleaseStatus? MapReleaseStatus(string? status)
{
if (string.IsNullOrWhiteSpace(status))
return null;
return status.Trim().ToLowerInvariant() switch
{
"official" => MusicReleaseStatus.Official,
"promotion" => MusicReleaseStatus.Promotion,
"bootleg" => MusicReleaseStatus.Bootleg,
"pseudo-release" => MusicReleaseStatus.PseudoRelease,
"withdrawn" => MusicReleaseStatus.Withdrawn,
"cancelled" => MusicReleaseStatus.Cancelled,
"expunged" => MusicReleaseStatus.Expunged,
_ => null
};
}
/// <summary>
/// Maps a MusicBrainz medium format into the application enum.
/// </summary>
/// <param name="format">The format to map.</param>
/// <returns>The mapped media format, or <see langword="null"/> when the format is unknown.</returns>
private static MusicMediaFormat? MapMediaFormat(string? format)
{
if (string.IsNullOrWhiteSpace(format))
return null;
return format.Trim().ToLowerInvariant() switch
{
"cd" => MusicMediaFormat.CD,
"vinyl" => MusicMediaFormat.Vinyl,
"12\" vinyl" => MusicMediaFormat.Inch12Vinyl,
"10\" vinyl" => MusicMediaFormat.Inch10Vinyl,
"7\" vinyl" => MusicMediaFormat.Inch7Vinyl,
"digital media" => MusicMediaFormat.DigitalMedia,
"cassette" => MusicMediaFormat.Cassette,
"dvd" => MusicMediaFormat.DVD,
"dvd-video" => MusicMediaFormat.DVDVideo,
"dvd-audio" => MusicMediaFormat.DVDAudio,
"sacd" => MusicMediaFormat.SACD,
"hybrid sacd" => MusicMediaFormat.HybridSACD,
"blu-ray" => MusicMediaFormat.BluRay,
"minidisc" => MusicMediaFormat.MiniDisc,
"8cm cd" => MusicMediaFormat.Cm8CD,
"dat" => MusicMediaFormat.DAT,
"other" => MusicMediaFormat.Other,
_ => MusicMediaFormat.Other
};
}
/// <summary>
/// Maps a MusicBrainz release packaging into the application enum.
/// </summary>
/// <param name="packaging">The packaging to map.</param>
/// <returns>The mapped packaging, or <see langword="null"/> when the packaging is unknown.</returns>
private static MusicReleasePackaging? MapPackaging(string? packaging)
{
if (string.IsNullOrWhiteSpace(packaging))
return null;
return packaging.Trim().ToLowerInvariant() switch
{
"book" => MusicReleasePackaging.Book,
"box" => MusicReleasePackaging.Box,
"cardboard/paper sleeve" => MusicReleasePackaging.CardboardPaperSleeve,
"cassette case" => MusicReleasePackaging.CassetteCase,
"clamshell case" => MusicReleasePackaging.ClamshellCase,
"digibook" => MusicReleasePackaging.Digibook,
"digifile" => MusicReleasePackaging.Digifile,
"digipak" => MusicReleasePackaging.Digipak,
"discbox slider" => MusicReleasePackaging.DiscboxSlider,
"fatbox" => MusicReleasePackaging.Fatbox,
"gatefold cover" => MusicReleasePackaging.GatefoldCover,
"jewel case" => MusicReleasePackaging.JewelCase,
"keep case" => MusicReleasePackaging.KeepCase,
"longbox" => MusicReleasePackaging.Longbox,
"metal tin" => MusicReleasePackaging.MetalTin,
"plastic sleeve" => MusicReleasePackaging.PlasticSleeve,
"slidepack" => MusicReleasePackaging.Slidepack,
"slim jewel case" => MusicReleasePackaging.SlimJewelCase,
"slipcase" => MusicReleasePackaging.Slipcase,
"snap case" => MusicReleasePackaging.SnapCase,
"snappack" => MusicReleasePackaging.SnapPack,
"super jewel box" => MusicReleasePackaging.SuperJewelBox,
"none" => MusicReleasePackaging.None,
"other" => MusicReleasePackaging.Other,
_ => MusicReleasePackaging.Other
};
}
/// <summary>
/// Maps an ISO 3166-1 alpha-2 country code into the application enum.
/// </summary>
/// <param name="country">The country code to map.</param>
/// <returns>The mapped release country, or <see langword="null"/> when the code is unknown.</returns>
private static ReleaseCountry? MapReleaseCountry(string? country)
{
if (string.IsNullOrWhiteSpace(country))
return null;
return Enum.TryParse(country.Trim(), ignoreCase: true, out ReleaseCountry releaseCountry) ? releaseCountry : null;
}
/// <summary>
/// Parses a MusicBrainz identifier into a <see cref="Guid"/>.
/// </summary>
/// <param name="value">The MusicBrainz identifier to parse.</param>
/// <returns>The parsed identifier, or <see langword="null"/> when the value is not a valid identifier.</returns>
private static Guid? ParseGuid(string? value)
{
return Guid.TryParse(value, out Guid parsed) ? parsed : null;
}
/// <summary>
/// Parses a MusicBrainz date string into a date and a year.
/// </summary>
/// <param name="value">The date string to parse.</param>
/// <returns>The parsed date and year, or <see langword="null"/> values when the string could not be parsed.</returns>
private static (DateOnly? Date, int? Year) ParseDate(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return (null, null);
if (DateOnly.TryParse(value.Trim(), CultureInfo.InvariantCulture, DateTimeStyles.None, out DateOnly exact))
return (exact, exact.Year);
Match yearMatch = YearPattern().Match(value);
return yearMatch.Success && int.TryParse(yearMatch.Value, CultureInfo.InvariantCulture, out int year) ? (null, year) : (null, null);
}
/// <summary>
/// Returns the trimmed value, or <see langword="null"/> when the value is empty or white space.
/// </summary>
/// <param name="value">The value to process.</param>
/// <returns>The trimmed value, or <see langword="null"/>.</returns>
private static string? NullIfWhiteSpace(string? value)
{
return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}
}
@@ -0,0 +1,206 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using Lumina.Plugins.MusicBrainz.Core.Api;
using Lumina.Plugins.MusicBrainz.Core.Mapping;
using Lumina.Plugins.MusicBrainz.Core.Settings;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core;
/// <summary>
/// Provides album metadata from MusicBrainz by resolving lookups into album metadata DTOs.
/// A MusicBrainz release group is the logical album, while one of its releases is selected as the edition the local files match.
/// </summary>
internal sealed class MusicBrainzAlbumMetadataProvider : IMetadataProvider<AlbumMetadataLookupDto, AlbumMetadataDto>
{
private readonly MusicBrainzHttpClient _musicBrainzHttpClient;
private readonly MusicBrainzSettingsProvider _settingsProvider;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "MusicBrainz";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => true;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzAlbumMetadataProvider"/> class.
/// </summary>
/// <param name="musicBrainzHttpClient">The HTTP client used to call the MusicBrainz web service.</param>
/// <param name="settingsProvider">The provider of the settings that configure the MusicBrainz web service requests.</param>
public MusicBrainzAlbumMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider)
{
_musicBrainzHttpClient = musicBrainzHttpClient;
_settingsProvider = settingsProvider;
}
/// <summary>
/// Searches for the metadata of the album described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the album to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of album metadata candidates found.</returns>
public async Task<IReadOnlyList<AlbumMetadataDto>> GetSearchResultsAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(lookup.Title))
return [];
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
IReadOnlyList<MusicBrainzReleaseGroupResponse> releaseGroups = await _musicBrainzHttpClient
.SearchReleaseGroupsAsync(BuildReleaseGroupQuery(lookup.Title, lookup.ArtistName), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
List<AlbumMetadataDto> candidates = [];
foreach (MusicBrainzReleaseGroupResponse releaseGroup in releaseGroups)
if (!string.IsNullOrWhiteSpace(releaseGroup.Title))
candidates.Add(MusicBrainzMapper.MapAlbum(releaseGroup, null));
return candidates;
}
/// <summary>
/// Gets the metadata of the album described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the album to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the album, or <see langword="null"/> when no album was found.</returns>
public async Task<AlbumMetadataDto?> GetMetadataAsync(AlbumMetadataLookupDto lookup, CancellationToken cancellationToken)
{
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
MusicBrainzReleaseResponse? release = null;
MusicBrainzReleaseGroupResponse? releaseGroup = null;
// A release identifier pins the exact edition, so it is fetched first, and its release group is then resolved for the album level fields.
// The release is fetched together with its recordings, so that the track level enrichment of the same release is served from the response cache.
if (lookup.MusicBrainzReleaseId is not null)
release = await _musicBrainzHttpClient.GetReleaseWithRecordingsAsync(lookup.MusicBrainzReleaseId.Value, cancellationToken).ConfigureAwait(false);
Guid? releaseGroupId = lookup.MusicBrainzReleaseGroupId;
if (releaseGroupId is null && release?.ReleaseGroup?.Id is string releaseGroupIdValue && Guid.TryParse(releaseGroupIdValue, out Guid parsedReleaseGroupId))
releaseGroupId = parsedReleaseGroupId;
if (releaseGroupId is not null)
releaseGroup = await _musicBrainzHttpClient.GetReleaseGroupAsync(releaseGroupId.Value, cancellationToken).ConfigureAwait(false);
// Without any identifier, the album is searched by title and artist, and the first match is resolved in full.
if (release is null && releaseGroup is null && !string.IsNullOrWhiteSpace(lookup.Title))
{
IReadOnlyList<MusicBrainzReleaseGroupResponse> results = await _musicBrainzHttpClient
.SearchReleaseGroupsAsync(BuildReleaseGroupQuery(lookup.Title, lookup.ArtistName), 1, cancellationToken).ConfigureAwait(false);
MusicBrainzReleaseGroupResponse? searchResult = results.Count > 0 ? results[0] : null;
if (searchResult?.Id is string searchResultId && Guid.TryParse(searchResultId, out Guid parsedSearchResultId))
releaseGroup = await _musicBrainzHttpClient.GetReleaseGroupAsync(parsedSearchResultId, cancellationToken).ConfigureAwait(false);
}
if (releaseGroup is null)
return release is null ? null : MusicBrainzMapper.MapAlbum(new MusicBrainzReleaseGroupResponse { Id = release.ReleaseGroup?.Id, Title = release.Title }, release);
// When the exact release was not pinned by the lookup, the best edition of the release group is selected.
if (release is null && releaseGroup.Id is string releaseGroupIdentifier && Guid.TryParse(releaseGroupIdentifier, out Guid releaseGroupGuid))
{
IReadOnlyList<MusicBrainzReleaseResponse> releases = await _musicBrainzHttpClient
.BrowseReleasesByReleaseGroupAsync(releaseGroupGuid, settings.ReleaseLookupLimit, cancellationToken).ConfigureAwait(false);
release = SelectRelease(releases, lookup);
}
return MusicBrainzMapper.MapAlbum(releaseGroup, release);
}
/// <summary>
/// Selects the release of a release group that best matches the lookup, favoring official releases and those released in the lookup year.
/// </summary>
/// <param name="releases">The releases to select from.</param>
/// <param name="lookup">The lookup the selected release must match.</param>
/// <returns>The best matching release, or <see langword="null"/> when no release was provided.</returns>
private static MusicBrainzReleaseResponse? SelectRelease(IReadOnlyList<MusicBrainzReleaseResponse> releases, AlbumMetadataLookupDto lookup)
{
// Only a release whose tracklist matches the local album is selected, so that an edition of the release group that does not correspond to the
// local files is never attached to the album; without a known local track count, no release can be confidently matched, so none is selected.
if (lookup.TrackCount is not int trackCount)
return null;
List<MusicBrainzReleaseResponse> matchingReleases = [.. releases.Where(release => release.Media.Sum(medium => medium.TrackCount) == trackCount)];
if (matchingReleases.Count == 0)
return null;
return matchingReleases
.Select((release, index) => new
{
Release = release,
Index = index,
Score = ScoreRelease(release, lookup)
})
.OrderByDescending(item => item.Score)
.ThenBy(item => item.Index)
.Select(item => item.Release)
.First();
}
/// <summary>
/// Scores a release against the lookup to rank how well it matches.
/// </summary>
/// <param name="release">The release to score.</param>
/// <param name="lookup">The lookup the release must match.</param>
/// <returns>The match score of the release, where a higher score is a better match.</returns>
private static int ScoreRelease(MusicBrainzReleaseResponse release, AlbumMetadataLookupDto lookup)
{
int score = 0;
if (string.Equals(release.Status, "Official", StringComparison.OrdinalIgnoreCase))
score += 10_000;
if (lookup.ReleaseYear is int wantedYear && TryGetYear(release.Date) is int releaseYear && releaseYear == wantedYear)
score += 1_000;
if (!string.IsNullOrWhiteSpace(release.Barcode))
score += 100;
if (release.LabelInfo.Count > 0)
score += 50;
if (release.Media.Count > 0)
score += 10;
return score;
}
/// <summary>
/// Gets the year of a MusicBrainz date string.
/// </summary>
/// <param name="date">The date string to read.</param>
/// <returns>The year of the date, or <see langword="null"/> when it could not be read.</returns>
private static int? TryGetYear(string? date)
{
if (string.IsNullOrWhiteSpace(date))
return null;
string year = date.Length >= 4 ? date[..4] : date;
return int.TryParse(year, NumberStyles.Integer, CultureInfo.InvariantCulture, out int parsed) ? parsed : null;
}
/// <summary>
/// Builds the MusicBrainz release group search query for the provided title and artist.
/// </summary>
/// <param name="title">The title of the release group.</param>
/// <param name="artistName">The name of the artist, if applicable.</param>
/// <returns>The built search query.</returns>
private static string BuildReleaseGroupQuery(string title, string? artistName)
{
string query = $"releasegroup:\"{title.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"";
if (!string.IsNullOrWhiteSpace(artistName))
query += $" AND artist:\"{artistName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"";
return query;
}
}
@@ -0,0 +1,103 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using Lumina.Plugins.MusicBrainz.Core.Api;
using Lumina.Plugins.MusicBrainz.Core.Mapping;
using Lumina.Plugins.MusicBrainz.Core.Settings;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core;
/// <summary>
/// Provides music artist metadata from MusicBrainz by resolving lookups into artist metadata DTOs.
/// </summary>
internal sealed class MusicBrainzArtistMetadataProvider : IMetadataProvider<ArtistMetadataLookupDto, ArtistMetadataDto>
{
private readonly MusicBrainzHttpClient _musicBrainzHttpClient;
private readonly MusicBrainzSettingsProvider _settingsProvider;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "MusicBrainz";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => true;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzArtistMetadataProvider"/> class.
/// </summary>
/// <param name="musicBrainzHttpClient">The HTTP client used to call the MusicBrainz web service.</param>
/// <param name="settingsProvider">The provider of the settings that configure the MusicBrainz web service requests.</param>
public MusicBrainzArtistMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider)
{
_musicBrainzHttpClient = musicBrainzHttpClient;
_settingsProvider = settingsProvider;
}
/// <summary>
/// Searches for the metadata of the artist described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the artist to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of artist metadata candidates found.</returns>
public async Task<IReadOnlyList<ArtistMetadataDto>> GetSearchResultsAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(lookup.Name))
return [];
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
IReadOnlyList<MusicBrainzArtistResponse> artists = await _musicBrainzHttpClient
.SearchArtistsAsync(lookup.Name.Trim(), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
List<ArtistMetadataDto> candidates = [];
foreach (MusicBrainzArtistResponse artist in artists)
if (!string.IsNullOrWhiteSpace(artist.Name))
candidates.Add(MusicBrainzMapper.MapArtist(artist));
return candidates;
}
/// <summary>
/// Gets the metadata of the artist described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the artist to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the artist, or <see langword="null"/> when no artist was found.</returns>
public async Task<ArtistMetadataDto?> GetMetadataAsync(ArtistMetadataLookupDto lookup, CancellationToken cancellationToken)
{
// A MusicBrainz identifier is the most precise lookup, so it is used first, if present.
if (lookup.MusicBrainzArtistId is not null)
{
MusicBrainzArtistResponse? artist = await _musicBrainzHttpClient.GetArtistAsync(lookup.MusicBrainzArtistId.Value, cancellationToken).ConfigureAwait(false);
return artist is null ? null : MusicBrainzMapper.MapArtist(artist);
}
if (string.IsNullOrWhiteSpace(lookup.Name))
return null;
// Without an identifier, the artist is searched by name, and the first match is resolved in full.
IReadOnlyList<MusicBrainzArtistResponse> artists = await _musicBrainzHttpClient
.SearchArtistsAsync(lookup.Name.Trim(), 1, cancellationToken).ConfigureAwait(false);
MusicBrainzArtistResponse? searchResult = artists.Count > 0 ? artists[0] : null;
if (searchResult?.Id is null)
return null;
MusicBrainzArtistResponse? detailedArtist = System.Guid.TryParse(searchResult.Id, out System.Guid artistId)
? await _musicBrainzHttpClient.GetArtistAsync(artistId, cancellationToken).ConfigureAwait(false)
: null;
return detailedArtist is null ? MusicBrainzMapper.MapArtist(searchResult) : MusicBrainzMapper.MapArtist(detailedArtist);
}
}
@@ -0,0 +1,97 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Domain.SharedKernel.Common.Enums.Plugins;
using Lumina.Plugins.Contracts.Common.Models.DTO.Settings;
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.MusicBrainz.Common.DependencyInjection;
using Lumina.Plugins.MusicBrainz.Core.Settings;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core;
/// <summary>
/// Plugin that provides music metadata retrieval from MusicBrainz.
/// </summary>
public sealed class MusicBrainzPlugin : IPlugin, IPluginServiceRegistrator
{
/// <summary>
/// The unique identifier of the plugin.
/// </summary>
public static readonly Guid s_pluginId = new("f4c1a7de-3b52-4e6a-9d21-8c7e5b04a1f3");
/// <summary>
/// Gets the unique identifier of the plugin.
/// </summary>
public Guid Id => s_pluginId;
/// <summary>
/// Gets the display name of the plugin.
/// </summary>
public string Name => "MusicBrainz Metadata";
/// <summary>
/// Gets the author of the plugin.
/// </summary>
public string Author => "Lumina";
/// <summary>
/// Gets the version of the plugin.
/// </summary>
public Version Version => new(1, 0, 0);
/// <summary>
/// Gets the description of the plugin.
/// </summary>
public string Description => "Retrieves artist, album and track metadata from MusicBrainz.";
/// <summary>
/// Gets the settings schema of the plugin.
/// </summary>
/// <returns>The settings descriptors of the plugin.</returns>
public IReadOnlyList<PluginSettingDescriptorDto> GetSettingsSchema()
{
return
[
new PluginSettingDescriptorDto(
Key: MusicBrainzSettingsKeys.BASE_URL,
Label: "Base URL",
Type: PluginSettingType.Text,
DefaultValue: "https://musicbrainz.org/ws/2/"),
new PluginSettingDescriptorDto(
Key: MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL,
Label: "Allow LAN/Private Base URL",
Type: PluginSettingType.Boolean,
DefaultValue: "false"),
new PluginSettingDescriptorDto(
Key: MusicBrainzSettingsKeys.CONTACT_EMAIL,
Label: "Contact Email",
Type: PluginSettingType.Text),
new PluginSettingDescriptorDto(
Key: MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT,
Label: "Search Result Limit",
Type: PluginSettingType.Number,
DefaultValue: "10"),
new PluginSettingDescriptorDto(
Key: MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT,
Label: "Release Lookup Limit",
Type: PluginSettingType.Number,
DefaultValue: "25"),
new PluginSettingDescriptorDto(
Key: MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS,
Label: "Minimum Request Interval (seconds)",
Type: PluginSettingType.Number,
DefaultValue: "1.0")
];
}
/// <summary>
/// Registers the services required by the plugin.
/// </summary>
/// <param name="services">The service collection to register the services into.</param>
public void RegisterServices(IServiceCollection services)
{
services.AddMusicBrainzMetadataProviders(pluginId: Id);
}
}
@@ -0,0 +1,270 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Contracts.DTO.MediaLibrary.AudioLibrary.MusicLibrary;
using Lumina.Domain.SharedKernel.Common.Enums.MediaLibrary;
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using Lumina.Plugins.MusicBrainz.Core.Api;
using Lumina.Plugins.MusicBrainz.Core.Mapping;
using Lumina.Plugins.MusicBrainz.Core.Settings;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core;
/// <summary>
/// Provides track metadata from MusicBrainz by resolving lookups into audio metadata DTOs.
/// </summary>
internal sealed class MusicBrainzTrackMetadataProvider : IMetadataProvider<TrackMetadataLookupDto, AudioMetadataDto>
{
private readonly MusicBrainzHttpClient _musicBrainzHttpClient;
private readonly MusicBrainzSettingsProvider _settingsProvider;
/// <summary>
/// Gets the display name of the metadata provider.
/// </summary>
public string Name => "MusicBrainz";
/// <summary>
/// Gets the media library types this metadata provider supports.
/// </summary>
public IReadOnlyList<LibraryType> SupportedLibraryTypes => [LibraryType.Music];
/// <summary>
/// Gets a value indicating whether this metadata provider requires access to the web to retrieve metadata.
/// </summary>
public bool RequiresWebAccess => true;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzTrackMetadataProvider"/> class.
/// </summary>
/// <param name="musicBrainzHttpClient">The HTTP client used to call the MusicBrainz web service.</param>
/// <param name="settingsProvider">The provider of the settings that configure the MusicBrainz web service requests.</param>
public MusicBrainzTrackMetadataProvider(MusicBrainzHttpClient musicBrainzHttpClient, MusicBrainzSettingsProvider settingsProvider)
{
_musicBrainzHttpClient = musicBrainzHttpClient;
_settingsProvider = settingsProvider;
}
/// <summary>
/// Searches for the metadata of the track described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the track to search for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The collection of track metadata candidates found.</returns>
public async Task<IReadOnlyList<AudioMetadataDto>> GetSearchResultsAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(lookup.Title))
return [];
MusicBrainzSettingsDto settings = await _settingsProvider.GetAsync(cancellationToken).ConfigureAwait(false);
IReadOnlyList<MusicBrainzRecordingResponse> recordings = await _musicBrainzHttpClient
.SearchRecordingsAsync(BuildRecordingQuery(lookup), settings.SearchResultLimit, cancellationToken).ConfigureAwait(false);
List<AudioMetadataDto> candidates = [];
foreach (MusicBrainzRecordingResponse recording in recordings)
if (!string.IsNullOrWhiteSpace(recording.Title))
candidates.Add(MusicBrainzMapper.MapTrack(recording, null, null));
return candidates;
}
/// <summary>
/// Gets the metadata of the track described by <paramref name="lookup"/>.
/// </summary>
/// <param name="lookup">The lookup describing the track to get the metadata for.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The metadata of the track, or <see langword="null"/> when no track was found.</returns>
public async Task<AudioMetadataDto?> GetMetadataAsync(TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
{
// When the release the track belongs to is known, the release is fetched once, with all its recordings, and the track is resolved from its
// tracklist; the recording of that response already carries its work, so every track of the release is enriched from a single request.
if (lookup.MusicBrainzReleaseId is not null)
{
MusicBrainzReleaseResponse? release = await _musicBrainzHttpClient.GetReleaseWithRecordingsAsync(lookup.MusicBrainzReleaseId.Value, cancellationToken).ConfigureAwait(false);
MusicBrainzTrackResponse? releaseTrack = release is null ? null : FindTrack(release, lookup);
if (releaseTrack?.Recording is not null)
{
MusicBrainzWorkResponse? inlineWork = await ResolveFallbackWorkAsync(ResolveInlineWork(releaseTrack.Recording), lookup, cancellationToken).ConfigureAwait(false);
return MusicBrainzMapper.MapTrack(releaseTrack.Recording, inlineWork, release);
}
}
MusicBrainzRecordingResponse? recording = null;
// A recording identifier is the most precise lookup, so it is used next, if present.
if (lookup.MusicBrainzRecordingId is not null)
recording = await _musicBrainzHttpClient.GetRecordingAsync(lookup.MusicBrainzRecordingId.Value, cancellationToken).ConfigureAwait(false);
// An ISRC lookup returns the recordings that carry the code, the first of which is then resolved in full.
if (recording is null && !string.IsNullOrWhiteSpace(lookup.Isrc))
{
IReadOnlyList<MusicBrainzRecordingResponse> recordings = await _musicBrainzHttpClient
.GetRecordingsByIsrcAsync(lookup.Isrc.Trim(), cancellationToken).ConfigureAwait(false);
MusicBrainzRecordingResponse? match = recordings.FirstOrDefault();
recording = await ResolveRecordingAsync(match, cancellationToken).ConfigureAwait(false);
}
// Without an identifier or a code, the track is searched, and the first match is resolved in full.
if (recording is null && !string.IsNullOrWhiteSpace(lookup.Title))
{
IReadOnlyList<MusicBrainzRecordingResponse> recordings = await _musicBrainzHttpClient
.SearchRecordingsAsync(BuildRecordingQuery(lookup), 1, cancellationToken).ConfigureAwait(false);
recording = await ResolveRecordingAsync(recordings.FirstOrDefault(), cancellationToken).ConfigureAwait(false);
}
if (recording is null)
return null;
MusicBrainzWorkResponse? work = await ResolveWorkAsync(recording, cancellationToken).ConfigureAwait(false);
work = await ResolveFallbackWorkAsync(work, lookup, cancellationToken).ConfigureAwait(false);
MusicBrainzReleaseResponse? resolvedRelease = await ResolveReleaseAsync(recording, cancellationToken).ConfigureAwait(false);
return MusicBrainzMapper.MapTrack(recording, work, resolvedRelease);
}
/// <summary>
/// Falls back to the work identifier of the tags when MusicBrainz did not link the recording to a work.
/// </summary>
/// <param name="work">The work resolved from MusicBrainz, if any.</param>
/// <param name="lookup">The lookup describing the local track.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The provided work, the work resolved from the work identifier of the tags, or <see langword="null"/> when neither is available.</returns>
private async Task<MusicBrainzWorkResponse?> ResolveFallbackWorkAsync(MusicBrainzWorkResponse? work, TrackMetadataLookupDto lookup, CancellationToken cancellationToken)
{
// The title of the tags means the work of the tags is already complete, so it is kept as is and MusicBrainz is not queried again for it.
if (work is not null || lookup.MusicBrainzWorkId is not Guid musicBrainzWorkId || !string.IsNullOrWhiteSpace(lookup.WorkTitle))
return work;
return await _musicBrainzHttpClient.GetWorkAsync(musicBrainzWorkId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Finds the track of <paramref name="release"/> that matches the provided <paramref name="lookup"/>, matching the recording identifier first,
/// then the disc and track numbers, then the title, and finally the duration.
/// </summary>
/// <param name="release">The release whose tracklist is searched.</param>
/// <param name="lookup">The lookup describing the local track.</param>
/// <returns>The matching track, or <see langword="null"/> when no track matched.</returns>
private static MusicBrainzTrackResponse? FindTrack(MusicBrainzReleaseResponse release, TrackMetadataLookupDto lookup)
{
// The recording identifier is the most precise match, so it is used first, if present.
if (lookup.MusicBrainzRecordingId is Guid musicBrainzRecordingId)
{
foreach (MusicBrainzMediumResponse medium in release.Media)
foreach (MusicBrainzTrackResponse track in medium.Tracks)
if (track.Recording?.Id is string recordingId && Guid.TryParse(recordingId, out Guid trackRecordingId) && trackRecordingId == musicBrainzRecordingId)
return track;
}
List<MusicBrainzTrackResponse> candidates = [];
foreach (MusicBrainzMediumResponse medium in release.Media)
{
if (lookup.DiscNumber is int discNumber && medium.Position != discNumber)
continue;
foreach (MusicBrainzTrackResponse track in medium.Tracks)
{
if (lookup.TrackNumber is int trackNumber && track.Position != trackNumber)
continue;
candidates.Add(track);
}
}
if (candidates.Count <= 1)
return candidates.Count == 1 ? candidates[0] : null;
// The disc and track numbers were not enough to single the track out, so the title is used next, and the duration breaks any remaining tie.
if (!string.IsNullOrWhiteSpace(lookup.Title))
{
List<MusicBrainzTrackResponse> titledCandidates = [.. candidates.Where(candidate => string.Equals(candidate.Title, lookup.Title, StringComparison.OrdinalIgnoreCase))];
if (titledCandidates.Count == 1)
return titledCandidates[0];
if (titledCandidates.Count > 1)
candidates = titledCandidates;
}
if (candidates.Count > 1 && lookup.DurationInSeconds is int duration)
return candidates.OrderBy(candidate => Math.Abs((candidate.Length ?? 0) / 1000 - duration)).First();
return candidates[0];
}
/// <summary>
/// Gets the work the provided <paramref name="recording"/> is a performance of, from the relations already embedded in the response.
/// </summary>
/// <param name="recording">The recording whose work is resolved.</param>
/// <returns>The embedded work, or <see langword="null"/> when the recording has no work.</returns>
private static MusicBrainzWorkResponse? ResolveInlineWork(MusicBrainzRecordingResponse recording)
{
return recording.Relations
.Where(relation => string.Equals(relation.TargetType, "work", StringComparison.OrdinalIgnoreCase))
.Select(relation => relation.Work)
.FirstOrDefault(work => work is not null);
}
/// <summary>
/// Resolves the full recording of the provided search or ISRC lookup result.
/// </summary>
/// <param name="recording">The partial recording to resolve.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The full recording, or <see langword="null"/> when the recording could not be resolved.</returns>
private async Task<MusicBrainzRecordingResponse?> ResolveRecordingAsync(MusicBrainzRecordingResponse? recording, CancellationToken cancellationToken)
{
if (recording?.Id is null || !Guid.TryParse(recording.Id, out Guid recordingId))
return recording;
return await _musicBrainzHttpClient.GetRecordingAsync(recordingId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Resolves the work the provided recording is an instance of, together with its credited contributors.
/// </summary>
/// <param name="recording">The recording whose work is resolved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The work of the recording, or <see langword="null"/> when the recording has no work.</returns>
private async Task<MusicBrainzWorkResponse?> ResolveWorkAsync(MusicBrainzRecordingResponse recording, CancellationToken cancellationToken)
{
string? workId = recording.Relations
.Where(relation => string.Equals(relation.TargetType, "work", StringComparison.OrdinalIgnoreCase))
.Select(relation => relation.Work?.Id)
.FirstOrDefault(id => !string.IsNullOrWhiteSpace(id));
if (workId is null || !Guid.TryParse(workId, out Guid parsedWorkId))
return recording.Relations
.Where(relation => string.Equals(relation.TargetType, "work", StringComparison.OrdinalIgnoreCase))
.Select(relation => relation.Work)
.FirstOrDefault(work => work is not null);
return await _musicBrainzHttpClient.GetWorkAsync(parsedWorkId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Resolves the release the provided recording appears on, for the release level language and script.
/// </summary>
/// <param name="recording">The recording whose release is resolved.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The release of the recording, or <see langword="null"/> when the recording does not reference a release.</returns>
private async Task<MusicBrainzReleaseResponse?> ResolveReleaseAsync(MusicBrainzRecordingResponse recording, CancellationToken cancellationToken)
{
string? releaseId = recording.Releases.Select(release => release.Id).FirstOrDefault(id => !string.IsNullOrWhiteSpace(id));
if (releaseId is null || !Guid.TryParse(releaseId, out Guid parsedReleaseId))
return null;
return await _musicBrainzHttpClient.GetReleaseAsync(parsedReleaseId, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Builds the MusicBrainz recording search query for the provided lookup.
/// </summary>
/// <param name="lookup">The lookup describing the track.</param>
/// <returns>The built search query.</returns>
private static string BuildRecordingQuery(TrackMetadataLookupDto lookup)
{
List<string> parts = [];
if (!string.IsNullOrWhiteSpace(lookup.Title))
parts.Add($"recording:\"{lookup.Title.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"");
if (!string.IsNullOrWhiteSpace(lookup.ArtistName))
parts.Add($"artist:\"{lookup.ArtistName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"");
if (!string.IsNullOrWhiteSpace(lookup.ReleaseName))
parts.Add($"release:\"{lookup.ReleaseName.Trim().Replace("\"", string.Empty, StringComparison.Ordinal)}\"");
return string.Join(" AND ", parts);
}
}
@@ -0,0 +1,37 @@
namespace Lumina.Plugins.MusicBrainz.Core.Settings;
/// <summary>
/// Keys of the settings of the MusicBrainz metadata plugin, shared by the settings schema and the settings loader.
/// </summary>
internal static class MusicBrainzSettingsKeys
{
/// <summary>
/// The key of the setting defining the base URL of the MusicBrainz web service.
/// </summary>
internal const string BASE_URL = "BaseUrl";
/// <summary>
/// The key of the setting that allows the base URL to point at a private or local host, for a self hosted mirror on a local network.
/// </summary>
internal const string DOES_ALLOW_PRIVATE_BASE_URL = "DoesAllowPrivateBaseUrl";
/// <summary>
/// The key of the setting defining the contact email sent to the MusicBrainz API.
/// </summary>
internal const string CONTACT_EMAIL = "ContactEmail";
/// <summary>
/// The key of the setting defining the maximum number of results returned by a single search.
/// </summary>
internal const string SEARCH_RESULT_LIMIT = "SearchResultLimit";
/// <summary>
/// The key of the setting defining the maximum number of releases fetched for a single release group.
/// </summary>
internal const string RELEASE_LOOKUP_LIMIT = "ReleaseLookupLimit";
/// <summary>
/// The key of the setting defining the minimum interval between consecutive requests to the MusicBrainz API, in seconds.
/// </summary>
internal const string MINIMUM_REQUEST_INTERVAL_SECONDS = "MinimumRequestIntervalSeconds";
}
@@ -0,0 +1,210 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Core.Plugins;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Plugins.MusicBrainz.Core.Settings;
/// <summary>
/// Provides the runtime settings of the MusicBrainz metadata plugin, overlaying the settings persisted by the host over the configured defaults.
/// </summary>
internal sealed class MusicBrainzSettingsProvider
{
private readonly IPluginSettingsStore? _settingsStore;
private readonly Guid _pluginId;
private readonly MusicBrainzSettingsDto _defaults;
// The resolved settings are read on every request, so the resolved instance is published through Volatile to keep the common, already
// resolved path lock free; the gate is only needed by the first callers that race to resolve it.
private readonly SemaphoreSlim _gate = new(1, 1);
private MusicBrainzSettingsDto? _runtimeSettings;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzSettingsProvider"/> class.
/// </summary>
/// <param name="settingsStore">The store of the settings persisted by the host, or <see langword="null"/> when no store is available.</param>
/// <param name="pluginId">The unique identifier of the plugin whose settings are read.</param>
/// <param name="defaults">The runtime settings with the default values and the optional configuration callback already applied.</param>
public MusicBrainzSettingsProvider(IPluginSettingsStore? settingsStore, Guid pluginId, MusicBrainzSettingsDto defaults)
{
_settingsStore = settingsStore;
_pluginId = pluginId;
_defaults = defaults;
}
/// <summary>
/// Gets the runtime settings of the plugin, reading and applying the settings persisted by the host on the first call.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The runtime settings of the plugin.</returns>
public async Task<MusicBrainzSettingsDto> GetAsync(CancellationToken cancellationToken)
{
// Lock free first check: reading through Volatile guarantees that a fully resolved instance published by another thread is observed intact.
MusicBrainzSettingsDto? runtimeSettings = Volatile.Read(ref _runtimeSettings);
if (runtimeSettings is not null)
return runtimeSettings;
// Only the first callers reach this point, and the gate serializes them, so the settings store is queried exactly once.
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
// Second check inside the gate: another caller may have resolved the settings while this one was waiting for it.
runtimeSettings = Volatile.Read(ref _runtimeSettings);
if (runtimeSettings is null)
{
// The defaults are cloned so that applying the persisted settings never mutates the instance shared with the other scopes.
runtimeSettings = Clone(_defaults);
if (_settingsStore is not null)
{
IReadOnlyDictionary<string, string>? storedSettings = await _settingsStore.GetSettingsAsync(_pluginId, cancellationToken).ConfigureAwait(false);
if (storedSettings is not null)
Apply(runtimeSettings, storedSettings);
}
// Publishing through Volatile makes the fully built instance visible to the lock free readers above.
Volatile.Write(ref _runtimeSettings, runtimeSettings);
}
return runtimeSettings;
}
finally
{
_gate.Release();
}
}
/// <summary>
/// Overlays the persisted settings onto the provided runtime settings, keeping the default values of the settings that were not persisted.
/// </summary>
/// <param name="settings">The runtime settings onto which the persisted settings are applied.</param>
/// <param name="storedSettings">The settings persisted by the host, keyed by setting key.</param>
private static void Apply(MusicBrainzSettingsDto settings, IReadOnlyDictionary<string, string> storedSettings)
{
// The private host opt-in must be resolved first, because it governs whether a private base URL is accepted below.
if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.DOES_ALLOW_PRIVATE_BASE_URL, out string? doesAllowPrivateBaseUrl) &&
bool.TryParse(doesAllowPrivateBaseUrl, out bool doesAllowPrivateBaseUrlValue))
settings.DoesAllowPrivateBaseUrl = doesAllowPrivateBaseUrlValue;
if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.BASE_URL, out string? baseUrl) &&
Uri.TryCreate(baseUrl?.Trim(), UriKind.Absolute, out Uri? parsedBaseUrl) &&
(parsedBaseUrl.Scheme == Uri.UriSchemeHttp || parsedBaseUrl.Scheme == Uri.UriSchemeHttps) &&
(settings.DoesAllowPrivateBaseUrl || IsPublicHost(parsedBaseUrl.Host)))
settings.BaseUrl = parsedBaseUrl.AbsoluteUri;
if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.CONTACT_EMAIL, out string? contactEmail))
{
string? trimmedContactEmail = string.IsNullOrWhiteSpace(contactEmail) ? null : contactEmail.Trim();
settings.ContactEmail = trimmedContactEmail is not null && IsSafeContactEmail(trimmedContactEmail) ? trimmedContactEmail : null;
}
if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.SEARCH_RESULT_LIMIT, out string? searchResultLimit) &&
int.TryParse(searchResultLimit, NumberStyles.Integer, CultureInfo.InvariantCulture, out int searchResultLimitValue))
settings.SearchResultLimit = Math.Max(1, searchResultLimitValue);
if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.RELEASE_LOOKUP_LIMIT, out string? releaseLookupLimit) &&
int.TryParse(releaseLookupLimit, NumberStyles.Integer, CultureInfo.InvariantCulture, out int releaseLookupLimitValue))
settings.ReleaseLookupLimit = Math.Max(1, releaseLookupLimitValue);
if (storedSettings.TryGetValue(MusicBrainzSettingsKeys.MINIMUM_REQUEST_INTERVAL_SECONDS, out string? minimumRequestInterval) &&
double.TryParse(minimumRequestInterval, NumberStyles.Float, CultureInfo.InvariantCulture, out double minimumRequestIntervalValue))
settings.MinimumRequestInterval = TimeSpan.FromSeconds(Math.Max(0, minimumRequestIntervalValue));
}
/// <summary>
/// Determines whether the host of the persisted base URL is a public host, so the setting cannot be used to reach a local or private service.
/// </summary>
/// <param name="host">The host of the persisted base URL.</param>
/// <returns><see langword="true"/> when the host is public, otherwise <see langword="false"/>.</returns>
/// <remarks>
/// A host name is accepted as is, because it cannot be classified without resolving it, which is deliberately not done here.
/// A private or local host is accepted when <see cref="MusicBrainzSettingsDto.DoesAllowPrivateBaseUrl"/> is enabled, which supports self hosted
/// mirrors on a local network.
/// </remarks>
private static bool IsPublicHost(string host)
{
if (string.IsNullOrWhiteSpace(host))
return false;
// Uri.Host surrounds an IPv6 literal with brackets, which IPAddress.TryParse does not accept.
string normalizedHost = host.Trim('[', ']');
if (string.Equals(normalizedHost, "localhost", StringComparison.OrdinalIgnoreCase))
return false;
if (!IPAddress.TryParse(normalizedHost, out IPAddress? address))
return true;
if (address.IsIPv4MappedToIPv6)
address = address.MapToIPv4();
if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))
return false;
if (address.AddressFamily == AddressFamily.InterNetwork)
{
byte[] octets = address.GetAddressBytes();
// The unspecified, private, loopback, link local and carrier grade NAT ranges are rejected, as they are the common targets of an SSRF.
return octets[0] switch
{
0 => false,
10 => false,
100 when octets[1] is >= 64 and <= 127 => false,
127 => false,
169 when octets[1] == 254 => false,
172 when octets[1] is >= 16 and <= 31 => false,
192 when octets[1] == 168 => false,
_ => true
};
}
if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal)
return false;
byte[] addressBytes = address.GetAddressBytes();
// The fc00::/7 unique local range is rejected, matching the private IPv4 ranges.
if ((addressBytes[0] & 0xFE) == 0xFC)
return false;
return true;
}
/// <summary>
/// Determines whether the persisted contact email only contains characters that are safe inside the request user agent header.
/// </summary>
/// <param name="contactEmail">The persisted contact email.</param>
/// <returns><see langword="true"/> when the email is safe, otherwise <see langword="false"/>.</returns>
private static bool IsSafeContactEmail(string contactEmail)
{
// The email is embedded in the User-Agent header, and an invalid character there throws when the header is parsed, which would break every request of the plugin,
// so anything outside a conservative email charset is rejected.
foreach (char character in contactEmail)
if (!char.IsAsciiLetterOrDigit(character) && character is not ('@' or '.' or '_' or '-' or '+'))
return false;
return true;
}
/// <summary>
/// Creates a copy of the given runtime settings.
/// </summary>
/// <param name="source">The runtime settings to copy.</param>
/// <returns>A copy of the given runtime settings.</returns>
private static MusicBrainzSettingsDto Clone(MusicBrainzSettingsDto source)
{
return new MusicBrainzSettingsDto
{
BaseUrl = source.BaseUrl,
DoesAllowPrivateBaseUrl = source.DoesAllowPrivateBaseUrl,
UserAgent = source.UserAgent,
ContactEmail = source.ContactEmail,
SearchResultLimit = source.SearchResultLimit,
ReleaseLookupLimit = source.ReleaseLookupLimit,
MinimumRequestInterval = source.MinimumRequestInterval
};
}
}
@@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
<BaseOutputPath>$(SolutionDir)..\bin\plugins\</BaseOutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
<CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\..\src\AssemblyInfo_Shared.cs" Link="Properties\AssemblyInfo_Shared.cs" />
</ItemGroup>
<Target Name="CopyToPluginsFolder" AfterTargets="Build">
<MakeDir Directories="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="$(TargetPath)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
<Copy SourceFiles="@(ReferenceCopyLocalPaths)" DestinationFolder="$(SolutionDir)..\bin\api\$(Configuration)\$(TargetFramework)\plugins\" />
</Target>
<ItemGroup>
<ProjectReference Include="..\..\src\Lumina.Plugins.Contracts\Lumina.Plugins.Contracts.csproj">
<Private>false</Private><!--Do not copy this assembly in the output directory, it's loaded from somewhere else-->
<ExcludeAssets>runtime</ExcludeAssets>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
</Project>
@@ -0,0 +1,6 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.UnitTests")]
[assembly: InternalsVisibleTo("Lumina.Plugins.MusicBrainz.Fixtures")]
[assembly: InternalsVisibleTo("Lumina.Presentation.Api.SecurityTests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]