Migrate MusicBrainz plugin to MetaBrainz.MusicBrainz

Co-authored-by: crobibero <cody@robibe.ro>
Co-authored-by: Shadowghost <Shadowghost@users.noreply.github.com>
This commit is contained in:
MrTimscampi 2022-04-07 12:15:25 +02:00 committed by Shadowghost
parent 7eae6891c8
commit 7ad0c9ba24
14 changed files with 590 additions and 1201 deletions

View File

@ -17,6 +17,7 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="LrcParser" Version="2022.529.1" /> <PackageReference Include="LrcParser" Version="2022.529.1" />
<PackageReference Include="MetaBrainz.MusicBrainz" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />

View File

@ -1,37 +1,58 @@
#pragma warning disable CS1591
using MediaBrowser.Model.Plugins; using MediaBrowser.Model.Plugins;
using MetaBrainz.MusicBrainz;
namespace MediaBrowser.Providers.Plugins.MusicBrainz namespace MediaBrowser.Providers.Plugins.MusicBrainz.Configuration;
/// <summary>
/// MusicBrainz plugin configuration.
/// </summary>
public class PluginConfiguration : BasePluginConfiguration
{ {
public class PluginConfiguration : BasePluginConfiguration private const string DefaultServer = "musicbrainz.org";
{
private string _server = Plugin.DefaultServer;
private long _rateLimit = Plugin.DefaultRateLimit; private const double DefaultRateLimit = 1.0;
private string _server = DefaultServer;
private double _rateLimit = DefaultRateLimit;
/// <summary>
/// Gets or sets the server url.
/// </summary>
public string Server public string Server
{ {
get => _server; get => _server;
set => _server = value.TrimEnd('/');
set
{
_server = value.TrimEnd('/');
Query.DefaultServer = _server;
}
} }
public long RateLimit /// <summary>
/// Gets or sets the rate limit.
/// </summary>
public double RateLimit
{ {
get => _rateLimit; get => _rateLimit;
set set
{ {
if (value < Plugin.DefaultRateLimit && _server == Plugin.DefaultServer) if (value < DefaultRateLimit && _server == DefaultServer)
{ {
_rateLimit = Plugin.DefaultRateLimit; _rateLimit = DefaultRateLimit;
} }
else else
{ {
_rateLimit = value; _rateLimit = value;
} }
Query.DelayBetweenRequests = _rateLimit;
} }
} }
/// <summary>
/// Gets or sets a value indicating whether to replace the artist name.
/// </summary>
public bool ReplaceArtistName { get; set; } public bool ReplaceArtistName { get; set; }
}
} }

View File

@ -1,15 +1,15 @@
#pragma warning disable CS1591
using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities; using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers; using MediaBrowser.Model.Providers;
using MediaBrowser.Providers.Plugins.MusicBrainz;
namespace MediaBrowser.Providers.Music namespace MediaBrowser.Providers.Plugins.MusicBrainz;
/// <summary>
/// MusicBrainz album artist external id.
/// </summary>
public class MusicBrainzAlbumArtistExternalId : IExternalId
{ {
public class MusicBrainzAlbumArtistExternalId : IExternalId
{
/// <inheritdoc /> /// <inheritdoc />
public string ProviderName => "MusicBrainz"; public string ProviderName => "MusicBrainz";
@ -20,9 +20,8 @@ namespace MediaBrowser.Providers.Music
public ExternalIdMediaType? Type => ExternalIdMediaType.AlbumArtist; public ExternalIdMediaType? Type => ExternalIdMediaType.AlbumArtist;
/// <inheritdoc /> /// <inheritdoc />
public string? UrlFormatString => Plugin.Instance.Configuration.Server + "/artist/{0}"; public string? UrlFormatString => Plugin.Instance!.Configuration.Server + "/artist/{0}";
/// <inheritdoc /> /// <inheritdoc />
public bool Supports(IHasProviderIds item) => item is Audio; public bool Supports(IHasProviderIds item) => item is Audio;
}
} }

View File

@ -1,15 +1,15 @@
#pragma warning disable CS1591
using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities; using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers; using MediaBrowser.Model.Providers;
using MediaBrowser.Providers.Plugins.MusicBrainz;
namespace MediaBrowser.Providers.Music namespace MediaBrowser.Providers.Plugins.MusicBrainz;
/// <summary>
/// MusicBrainz album external id.
/// </summary>
public class MusicBrainzAlbumExternalId : IExternalId
{ {
public class MusicBrainzAlbumExternalId : IExternalId
{
/// <inheritdoc /> /// <inheritdoc />
public string ProviderName => "MusicBrainz"; public string ProviderName => "MusicBrainz";
@ -20,9 +20,8 @@ namespace MediaBrowser.Providers.Music
public ExternalIdMediaType? Type => ExternalIdMediaType.Album; public ExternalIdMediaType? Type => ExternalIdMediaType.Album;
/// <inheritdoc /> /// <inheritdoc />
public string? UrlFormatString => Plugin.Instance.Configuration.Server + "/release/{0}"; public string? UrlFormatString => Plugin.Instance!.Configuration.Server + "/release/{0}";
/// <inheritdoc /> /// <inheritdoc />
public bool Supports(IHasProviderIds item) => item is Audio || item is MusicAlbum; public bool Supports(IHasProviderIds item) => item is Audio || item is MusicAlbum;
}
} }

View File

@ -1,72 +1,36 @@
#nullable disable
#pragma warning disable CS1591, SA1401
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq; using System.Linq;
using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml; using Jellyfin.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities; using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers; using MediaBrowser.Model.Providers;
using MediaBrowser.Providers.Plugins.MusicBrainz; using MediaBrowser.Providers.Music;
using Microsoft.Extensions.Logging; using MetaBrainz.MusicBrainz;
using MetaBrainz.MusicBrainz.Interfaces.Entities;
using MetaBrainz.MusicBrainz.Interfaces.Searches;
namespace MediaBrowser.Providers.Music namespace MediaBrowser.Providers.Plugins.MusicBrainz;
/// <summary>
/// Music album metadata provider for MusicBrainz.
/// </summary>
public class MusicBrainzAlbumProvider : IRemoteMetadataProvider<MusicAlbum, AlbumInfo>, IHasOrder, IDisposable
{ {
public class MusicBrainzAlbumProvider : IRemoteMetadataProvider<MusicAlbum, AlbumInfo>, IHasOrder, IDisposable private readonly Query _musicBrainzQuery;
{
/// <summary>
/// For each single MB lookup/search, this is the maximum number of
/// attempts that shall be made whilst receiving a 503 Server
/// Unavailable (indicating throttled) response.
/// </summary>
private const uint MusicBrainzQueryAttempts = 5u;
/// <summary> /// <summary>
/// The Jellyfin user-agent is unrestricted but source IP must not exceed /// Initializes a new instance of the <see cref="MusicBrainzAlbumProvider"/> class.
/// one request per second, therefore we rate limit to avoid throttling.
/// Be prudent, use a value slightly above the minimum required.
/// https://musicbrainz.org/doc/XML_Web_Service/Rate_Limiting.
/// </summary> /// </summary>
private readonly long _musicBrainzQueryIntervalMs; public MusicBrainzAlbumProvider()
private readonly IHttpClientFactory _httpClientFactory;
private readonly ILogger<MusicBrainzAlbumProvider> _logger;
private readonly string _musicBrainzBaseUrl;
private SemaphoreSlim _apiRequestLock = new SemaphoreSlim(1, 1);
private Stopwatch _stopWatchMusicBrainz = new Stopwatch();
public MusicBrainzAlbumProvider(
IHttpClientFactory httpClientFactory,
ILogger<MusicBrainzAlbumProvider> logger)
{ {
_httpClientFactory = httpClientFactory; _musicBrainzQuery = new Query();
_logger = logger;
_musicBrainzBaseUrl = Plugin.Instance.Configuration.Server;
_musicBrainzQueryIntervalMs = Plugin.Instance.Configuration.RateLimit;
// Use a stopwatch to ensure we don't exceed the MusicBrainz rate limit
_stopWatchMusicBrainz.Start();
Current = this;
} }
internal static MusicBrainzAlbumProvider Current { get; private set; }
/// <inheritdoc /> /// <inheritdoc />
public string Name => "MusicBrainz"; public string Name => "MusicBrainz";
@ -79,101 +43,110 @@ namespace MediaBrowser.Providers.Music
var releaseId = searchInfo.GetReleaseId(); var releaseId = searchInfo.GetReleaseId();
var releaseGroupId = searchInfo.GetReleaseGroupId(); var releaseGroupId = searchInfo.GetReleaseGroupId();
string url;
if (!string.IsNullOrEmpty(releaseId)) if (!string.IsNullOrEmpty(releaseId))
{ {
url = "/ws/2/release/?query=reid:" + releaseId.ToString(CultureInfo.InvariantCulture); var releaseResult = await _musicBrainzQuery.LookupReleaseAsync(new Guid(releaseId), Include.Releases, cancellationToken).ConfigureAwait(false);
return GetResultFromResponse(releaseResult).SingleItemAsEnumerable();
} }
else if (!string.IsNullOrEmpty(releaseGroupId))
if (!string.IsNullOrEmpty(releaseGroupId))
{ {
url = "/ws/2/release?release-group=" + releaseGroupId.ToString(CultureInfo.InvariantCulture); var releaseGroupResult = await _musicBrainzQuery.LookupReleaseGroupAsync(new Guid(releaseGroupId), Include.ReleaseGroups, null, cancellationToken).ConfigureAwait(false);
return GetResultsFromResponse(releaseGroupResult.Releases);
} }
else
{
var artistMusicBrainzId = searchInfo.GetMusicBrainzArtistId(); var artistMusicBrainzId = searchInfo.GetMusicBrainzArtistId();
if (!string.IsNullOrWhiteSpace(artistMusicBrainzId)) if (!string.IsNullOrWhiteSpace(artistMusicBrainzId))
{ {
url = string.Format( var releaseSearchResults = await _musicBrainzQuery.FindReleasesAsync($"\"{searchInfo.Name}\" AND arid:{artistMusicBrainzId}", null, null, false, cancellationToken)
CultureInfo.InvariantCulture, .ConfigureAwait(false);
"/ws/2/release/?query=\"{0}\" AND arid:{1}",
WebUtility.UrlEncode(searchInfo.Name), if (releaseSearchResults.Results.Count > 0)
artistMusicBrainzId); {
return GetResultsFromResponse(releaseSearchResults.Results);
}
} }
else else
{ {
// I'm sure there is a better way but for now it resolves search for 12" Mixes // I'm sure there is a better way but for now it resolves search for 12" Mixes
var queryName = searchInfo.Name.Replace("\"", string.Empty, StringComparison.Ordinal); var queryName = searchInfo.Name.Replace("\"", string.Empty, StringComparison.Ordinal);
url = string.Format( var releaseSearchResults = await _musicBrainzQuery.FindReleasesAsync($"\"{queryName}\" AND artist:\"{searchInfo.GetAlbumArtist()}\"c", null, null, false, cancellationToken)
CultureInfo.InvariantCulture, .ConfigureAwait(false);
"/ws/2/release/?query=\"{0}\" AND artist:\"{1}\"",
WebUtility.UrlEncode(queryName),
WebUtility.UrlEncode(searchInfo.GetAlbumArtist()));
}
}
if (!string.IsNullOrWhiteSpace(url)) if (releaseSearchResults.Results.Count > 0)
{ {
using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false); return GetResultsFromResponse(releaseSearchResults.Results);
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); }
return GetResultsFromResponse(stream);
} }
return Enumerable.Empty<RemoteSearchResult>(); return Enumerable.Empty<RemoteSearchResult>();
} }
private IEnumerable<RemoteSearchResult> GetResultsFromResponse(Stream stream) private IEnumerable<RemoteSearchResult> GetResultsFromResponse(IEnumerable<ISearchResult<IRelease>>? releaseSearchResults)
{ {
using var oReader = new StreamReader(stream, Encoding.UTF8); if (releaseSearchResults is null)
var settings = new XmlReaderSettings()
{ {
ValidationType = ValidationType.None, yield break;
CheckCharacters = false, }
IgnoreProcessingInstructions = true,
IgnoreComments = true foreach (var result in releaseSearchResults)
{
yield return GetResultFromResponse(result.Item);
}
}
private IEnumerable<RemoteSearchResult> GetResultsFromResponse(IEnumerable<IRelease>? releaseSearchResults)
{
if (releaseSearchResults is null)
{
yield break;
}
foreach (var result in releaseSearchResults)
{
yield return GetResultFromResponse(result);
}
}
private RemoteSearchResult GetResultFromResponse(IRelease releaseSearchResult)
{
var searchResult = new RemoteSearchResult
{
Name = releaseSearchResult.Title,
ProductionYear = releaseSearchResult.Date?.Year,
PremiereDate = releaseSearchResult.Date?.NearestDate
}; };
using var reader = XmlReader.Create(oReader, settings); if (releaseSearchResult.ArtistCredit?.Count > 0)
var results = ReleaseResult.Parse(reader);
return results.Select(i =>
{ {
var result = new RemoteSearchResult searchResult.AlbumArtist = new RemoteSearchResult
{
Name = i.Title,
ProductionYear = i.Year
};
if (i.Artists.Count > 0)
{
result.AlbumArtist = new RemoteSearchResult
{ {
SearchProviderName = Name, SearchProviderName = Name,
Name = i.Artists[0].Item1 Name = releaseSearchResult.ArtistCredit[0].Name
}; };
result.AlbumArtist.SetProviderId(MetadataProvider.MusicBrainzArtist, i.Artists[0].Item2); if (releaseSearchResult.ArtistCredit[0].Artist?.Id is not null)
}
if (!string.IsNullOrWhiteSpace(i.ReleaseId))
{ {
result.SetProviderId(MetadataProvider.MusicBrainzAlbum, i.ReleaseId); searchResult.AlbumArtist.SetProviderId(MetadataProvider.MusicBrainzArtist, releaseSearchResult.ArtistCredit[0].Artist!.Id.ToString());
}
} }
if (!string.IsNullOrWhiteSpace(i.ReleaseGroupId)) searchResult.SetProviderId(MetadataProvider.MusicBrainzAlbum, releaseSearchResult.Id.ToString());
if (releaseSearchResult.ReleaseGroup?.Id is not null)
{ {
result.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, i.ReleaseGroupId); searchResult.SetProviderId(MetadataProvider.MusicBrainzReleaseGroup, releaseSearchResult.ReleaseGroup.Id.ToString());
} }
return result; return searchResult;
});
} }
/// <inheritdoc /> /// <inheritdoc />
public async Task<MetadataResult<MusicAlbum>> GetMetadata(AlbumInfo info, CancellationToken cancellationToken) public async Task<MetadataResult<MusicAlbum>> GetMetadata(AlbumInfo info, CancellationToken cancellationToken)
{ {
// TODO: This sets essentially nothing. As-is, it's mostly useless. Make it actually pull metadata and use it.
var releaseId = info.GetReleaseId(); var releaseId = info.GetReleaseId();
var releaseGroupId = info.GetReleaseGroupId(); var releaseGroupId = info.GetReleaseGroupId();
@ -182,45 +155,59 @@ namespace MediaBrowser.Providers.Music
Item = new MusicAlbum() Item = new MusicAlbum()
}; };
// If we have a release group Id but not a release Id... // If there is a release group, but no release ID, try to match the release
if (string.IsNullOrWhiteSpace(releaseId) && !string.IsNullOrWhiteSpace(releaseGroupId)) if (string.IsNullOrWhiteSpace(releaseId) && !string.IsNullOrWhiteSpace(releaseGroupId))
{ {
releaseId = await GetReleaseIdFromReleaseGroupId(releaseGroupId, cancellationToken).ConfigureAwait(false); // TODO: Actually try to match the release. Simply taking the first result is stupid.
var releaseGroup = await _musicBrainzQuery.LookupReleaseGroupAsync(new Guid(releaseGroupId), Include.ReleaseGroups, null, cancellationToken).ConfigureAwait(false);
var release = releaseGroup.Releases?.Count > 0 ? releaseGroup.Releases[0] : null;
releaseId = release?.Id.ToString();
result.HasMetadata = true; result.HasMetadata = true;
} }
// If there is no release ID, lookup a release with the info we have
if (string.IsNullOrWhiteSpace(releaseId)) if (string.IsNullOrWhiteSpace(releaseId))
{ {
var artistMusicBrainzId = info.GetMusicBrainzArtistId(); var artistMusicBrainzId = info.GetMusicBrainzArtistId();
IRelease? releaseResult = null;
var releaseResult = await GetReleaseResult(artistMusicBrainzId, info.GetAlbumArtist(), info.Name, cancellationToken).ConfigureAwait(false); if (!string.IsNullOrEmpty(artistMusicBrainzId))
{
var releaseSearchResults = await _musicBrainzQuery.FindReleasesAsync($"\"{info.Name}\" AND arid:{artistMusicBrainzId}", null, null, false, cancellationToken)
.ConfigureAwait(false);
releaseResult = releaseSearchResults.Results.Count > 0 ? releaseSearchResults.Results[0].Item : null;
}
else if (!string.IsNullOrEmpty(info.GetAlbumArtist()))
{
var releaseSearchResults = await _musicBrainzQuery.FindReleasesAsync($"\"{info.Name}\" AND artist:{info.GetAlbumArtist()}", null, null, false, cancellationToken)
.ConfigureAwait(false);
releaseResult = releaseSearchResults.Results.Count > 0 ? releaseSearchResults.Results[0].Item : null;
}
if (releaseResult != null) if (releaseResult != null)
{ {
if (!string.IsNullOrWhiteSpace(releaseResult.ReleaseId)) releaseId = releaseResult.Id.ToString();
if (releaseResult.ReleaseGroup?.Id is not null)
{ {
releaseId = releaseResult.ReleaseId; releaseGroupId = releaseResult.ReleaseGroup.Id.ToString();
}
result.HasMetadata = true; result.HasMetadata = true;
} result.Item.ProductionYear = releaseResult.Date?.Year;
result.Item.Overview = releaseResult.Annotation;
if (!string.IsNullOrWhiteSpace(releaseResult.ReleaseGroupId))
{
releaseGroupId = releaseResult.ReleaseGroupId;
result.HasMetadata = true;
}
result.Item.ProductionYear = releaseResult.Year;
result.Item.Overview = releaseResult.Overview;
} }
} }
// If we have a release Id but not a release group Id... // If we have a release ID but not a release group ID, lookup the release group
if (!string.IsNullOrWhiteSpace(releaseId) && string.IsNullOrWhiteSpace(releaseGroupId)) if (!string.IsNullOrWhiteSpace(releaseId) && string.IsNullOrWhiteSpace(releaseGroupId))
{ {
releaseGroupId = await GetReleaseGroupFromReleaseId(releaseId, cancellationToken).ConfigureAwait(false); var release = await _musicBrainzQuery.LookupReleaseAsync(new Guid(releaseId), Include.Releases, cancellationToken).ConfigureAwait(false);
releaseGroupId = release.ReleaseGroup?.Id.ToString();
result.HasMetadata = true; result.HasMetadata = true;
} }
// If we have a release ID and a release group ID
if (!string.IsNullOrWhiteSpace(releaseId) || !string.IsNullOrWhiteSpace(releaseGroupId)) if (!string.IsNullOrWhiteSpace(releaseId) || !string.IsNullOrWhiteSpace(releaseGroupId))
{ {
result.HasMetadata = true; result.HasMetadata = true;
@ -242,378 +229,12 @@ namespace MediaBrowser.Providers.Music
return result; return result;
} }
private Task<ReleaseResult> GetReleaseResult(string artistMusicBrainId, string artistName, string albumName, CancellationToken cancellationToken)
{
if (!string.IsNullOrEmpty(artistMusicBrainId))
{
return GetReleaseResult(albumName, artistMusicBrainId, cancellationToken);
}
if (string.IsNullOrWhiteSpace(artistName))
{
return Task.FromResult(new ReleaseResult());
}
return GetReleaseResultByArtistName(albumName, artistName, cancellationToken);
}
private async Task<ReleaseResult> GetReleaseResult(string albumName, string artistId, CancellationToken cancellationToken)
{
var url = string.Format(
CultureInfo.InvariantCulture,
"/ws/2/release/?query=\"{0}\" AND arid:{1}",
WebUtility.UrlEncode(albumName),
artistId);
using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using var oReader = new StreamReader(stream, Encoding.UTF8);
var settings = new XmlReaderSettings
{
ValidationType = ValidationType.None,
CheckCharacters = false,
IgnoreProcessingInstructions = true,
IgnoreComments = true
};
using var reader = XmlReader.Create(oReader, settings);
return ReleaseResult.Parse(reader).FirstOrDefault();
}
private async Task<ReleaseResult> GetReleaseResultByArtistName(string albumName, string artistName, CancellationToken cancellationToken)
{
var url = string.Format(
CultureInfo.InvariantCulture,
"/ws/2/release/?query=\"{0}\" AND artist:\"{1}\"",
WebUtility.UrlEncode(albumName),
WebUtility.UrlEncode(artistName));
using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using var oReader = new StreamReader(stream, Encoding.UTF8);
var settings = new XmlReaderSettings()
{
ValidationType = ValidationType.None,
CheckCharacters = false,
IgnoreProcessingInstructions = true,
IgnoreComments = true
};
using var reader = XmlReader.Create(oReader, settings);
return ReleaseResult.Parse(reader).FirstOrDefault();
}
private static (string Name, string ArtistId) ParseArtistCredit(XmlReader reader)
{
reader.MoveToContent();
reader.Read();
// http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
// Loop through each element
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "name-credit":
{
if (reader.IsEmptyElement)
{
reader.Read();
break;
}
using var subReader = reader.ReadSubtree();
return ParseArtistNameCredit(subReader);
}
default:
{
reader.Skip();
break;
}
}
}
else
{
reader.Read();
}
}
return default;
}
private static (string Name, string ArtistId) ParseArtistNameCredit(XmlReader reader)
{
reader.MoveToContent();
reader.Read();
// http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
// Loop through each element
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "artist":
{
if (reader.IsEmptyElement)
{
reader.Read();
break;
}
var id = reader.GetAttribute("id");
using var subReader = reader.ReadSubtree();
return ParseArtistArtistCredit(subReader, id);
}
default:
{
reader.Skip();
break;
}
}
}
else
{
reader.Read();
}
}
return (null, null);
}
private static (string Name, string ArtistId) ParseArtistArtistCredit(XmlReader reader, string artistId)
{
reader.MoveToContent();
reader.Read();
string name = null;
// http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
// Loop through each element
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "name":
{
name = reader.ReadElementContentAsString();
break;
}
default:
{
reader.Skip();
break;
}
}
}
else
{
reader.Read();
}
}
return (name, artistId);
}
private async Task<string> GetReleaseIdFromReleaseGroupId(string releaseGroupId, CancellationToken cancellationToken)
{
var url = "/ws/2/release?release-group=" + releaseGroupId.ToString(CultureInfo.InvariantCulture);
using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using var oReader = new StreamReader(stream, Encoding.UTF8);
var settings = new XmlReaderSettings
{
ValidationType = ValidationType.None,
CheckCharacters = false,
IgnoreProcessingInstructions = true,
IgnoreComments = true
};
using var reader = XmlReader.Create(oReader, settings);
var result = ReleaseResult.Parse(reader).FirstOrDefault();
return result?.ReleaseId;
}
/// <summary>
/// Gets the release group id internal.
/// </summary>
/// <param name="releaseEntryId">The release entry id.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task{System.String}.</returns>
private async Task<string> GetReleaseGroupFromReleaseId(string releaseEntryId, CancellationToken cancellationToken)
{
var url = "/ws/2/release-group/?query=reid:" + releaseEntryId.ToString(CultureInfo.InvariantCulture);
using var response = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
using var oReader = new StreamReader(stream, Encoding.UTF8);
var settings = new XmlReaderSettings
{
ValidationType = ValidationType.None,
CheckCharacters = false,
IgnoreProcessingInstructions = true,
IgnoreComments = true,
Async = true
};
using var reader = XmlReader.Create(oReader, settings);
await reader.MoveToContentAsync().ConfigureAwait(false);
await reader.ReadAsync().ConfigureAwait(false);
// Loop through each element
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "release-group-list":
{
if (reader.IsEmptyElement)
{
await reader.ReadAsync().ConfigureAwait(false);
continue;
}
using var subReader = reader.ReadSubtree();
return GetFirstReleaseGroupId(subReader);
}
default:
{
await reader.SkipAsync().ConfigureAwait(false);
break;
}
}
}
else
{
await reader.ReadAsync().ConfigureAwait(false);
}
}
return null;
}
private string GetFirstReleaseGroupId(XmlReader reader)
{
reader.MoveToContent();
reader.Read();
// Loop through each element
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "release-group":
{
return reader.GetAttribute("id");
}
default:
{
reader.Skip();
break;
}
}
}
else
{
reader.Read();
}
}
return null;
}
/// <summary>
/// Makes request to MusicBrainz server and awaits a response.
/// A 503 Service Unavailable response indicates throttling to maintain a rate limit.
/// A number of retries shall be made in order to try and satisfy the request before
/// giving up and returning null.
/// </summary>
/// <param name="url">Address of MusicBrainz server.</param>
/// <param name="cancellationToken">CancellationToken to use for method.</param>
/// <returns>Returns response from MusicBrainz service.</returns>
internal async Task<HttpResponseMessage> GetMusicBrainzResponse(string url, CancellationToken cancellationToken)
{
await _apiRequestLock.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
HttpResponseMessage response;
var attempts = 0u;
var requestUrl = _musicBrainzBaseUrl.TrimEnd('/') + url;
do
{
attempts++;
if (_stopWatchMusicBrainz.ElapsedMilliseconds < _musicBrainzQueryIntervalMs)
{
// MusicBrainz is extremely adamant about limiting to one request per second.
var delayMs = _musicBrainzQueryIntervalMs - _stopWatchMusicBrainz.ElapsedMilliseconds;
await Task.Delay((int)delayMs, cancellationToken).ConfigureAwait(false);
}
// Write time since last request to debug log as evidence we're meeting rate limit
// requirement, before resetting stopwatch back to zero.
_logger.LogDebug("GetMusicBrainzResponse: Time since previous request: {0} ms", _stopWatchMusicBrainz.ElapsedMilliseconds);
_stopWatchMusicBrainz.Restart();
using var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
response = await _httpClientFactory
.CreateClient(NamedClient.MusicBrainz)
.SendAsync(request, cancellationToken)
.ConfigureAwait(false);
// We retry a finite number of times, and only whilst MB is indicating 503 (throttling).
}
while (attempts < MusicBrainzQueryAttempts && response.StatusCode == HttpStatusCode.ServiceUnavailable);
// Log error if unable to query MB database due to throttling.
if (attempts == MusicBrainzQueryAttempts && response.StatusCode == HttpStatusCode.ServiceUnavailable)
{
_logger.LogError("GetMusicBrainzResponse: 503 Service Unavailable (throttled) response received {0} times whilst requesting {1}", attempts, requestUrl);
}
return response;
}
finally
{
_apiRequestLock.Release();
}
}
/// <inheritdoc /> /// <inheritdoc />
public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken) public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_apiRequestLock?.Dispose();
}
}
/// <inheritdoc /> /// <inheritdoc />
public void Dispose() public void Dispose()
{ {
@ -621,185 +242,15 @@ namespace MediaBrowser.Providers.Music
GC.SuppressFinalize(this); GC.SuppressFinalize(this);
} }
private class ReleaseResult /// <summary>
/// Dispose all resources.
/// </summary>
/// <param name="disposing">Whether to dispose.</param>
protected virtual void Dispose(bool disposing)
{ {
public string ReleaseId; if (disposing)
public string ReleaseGroupId;
public string Title;
public string Overview;
public int? Year;
public List<(string, string)> Artists = new();
public static IEnumerable<ReleaseResult> Parse(XmlReader reader)
{ {
reader.MoveToContent(); _musicBrainzQuery.Dispose();
reader.Read();
// Loop through each element
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "release-list":
{
if (reader.IsEmptyElement)
{
reader.Read();
continue;
}
using var subReader = reader.ReadSubtree();
return ParseReleaseList(subReader).ToList();
}
default:
{
reader.Skip();
break;
}
}
}
else
{
reader.Read();
}
}
return Enumerable.Empty<ReleaseResult>();
}
private static IEnumerable<ReleaseResult> ParseReleaseList(XmlReader reader)
{
reader.MoveToContent();
reader.Read();
// Loop through each element
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "release":
{
if (reader.IsEmptyElement)
{
reader.Read();
continue;
}
var releaseId = reader.GetAttribute("id");
using var subReader = reader.ReadSubtree();
var release = ParseRelease(subReader, releaseId);
if (release != null)
{
yield return release;
}
break;
}
default:
{
reader.Skip();
break;
}
}
}
else
{
reader.Read();
}
}
}
private static ReleaseResult ParseRelease(XmlReader reader, string releaseId)
{
var result = new ReleaseResult
{
ReleaseId = releaseId
};
reader.MoveToContent();
reader.Read();
// http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
// Loop through each element
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "title":
{
result.Title = reader.ReadElementContentAsString();
break;
}
case "date":
{
var val = reader.ReadElementContentAsString();
if (DateTime.TryParse(val, out var date))
{
result.Year = date.Year;
}
break;
}
case "annotation":
{
result.Overview = reader.ReadElementContentAsString();
break;
}
case "release-group":
{
result.ReleaseGroupId = reader.GetAttribute("id");
reader.Skip();
break;
}
case "artist-credit":
{
if (reader.IsEmptyElement)
{
reader.Read();
break;
}
using var subReader = reader.ReadSubtree();
var artist = ParseArtistCredit(subReader);
if (!string.IsNullOrEmpty(artist.Name))
{
result.Artists.Add(artist);
}
break;
}
default:
{
reader.Skip();
break;
}
}
}
else
{
reader.Read();
}
}
return result;
}
} }
} }
} }

View File

@ -1,15 +1,15 @@
#pragma warning disable CS1591
using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities; using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers; using MediaBrowser.Model.Providers;
using MediaBrowser.Providers.Plugins.MusicBrainz;
namespace MediaBrowser.Providers.Music namespace MediaBrowser.Providers.Plugins.MusicBrainz;
/// <summary>
/// MusicBrains Artist ExternalId.
/// </summary>
public class MusicBrainzArtistExternalId : IExternalId
{ {
public class MusicBrainzArtistExternalId : IExternalId
{
/// <inheritdoc /> /// <inheritdoc />
public string ProviderName => "MusicBrainz"; public string ProviderName => "MusicBrainz";
@ -20,9 +20,8 @@ namespace MediaBrowser.Providers.Music
public ExternalIdMediaType? Type => ExternalIdMediaType.Artist; public ExternalIdMediaType? Type => ExternalIdMediaType.Artist;
/// <inheritdoc /> /// <inheritdoc />
public string? UrlFormatString => Plugin.Instance.Configuration.Server + "/artist/{0}"; public string? UrlFormatString => Plugin.Instance!.Configuration.Server + "/artist/{0}";
/// <inheritdoc /> /// <inheritdoc />
public bool Supports(IHasProviderIds item) => item is MusicArtist; public bool Supports(IHasProviderIds item) => item is MusicArtist;
}
} }

View File

@ -1,15 +1,7 @@
#nullable disable
#pragma warning disable CS1591
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq; using System.Linq;
using System.Net;
using System.Net.Http; using System.Net.Http;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Xml; using System.Xml;
@ -18,214 +10,107 @@ using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities; using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers; using MediaBrowser.Model.Providers;
using MediaBrowser.Providers.Plugins.MusicBrainz; using MediaBrowser.Providers.Music;
using MetaBrainz.MusicBrainz;
using MetaBrainz.MusicBrainz.Interfaces.Entities;
using MetaBrainz.MusicBrainz.Interfaces.Searches;
namespace MediaBrowser.Providers.Music namespace MediaBrowser.Providers.Plugins.MusicBrainz;
/// <summary>
/// MusicBrainz artist provider.
/// </summary>
public class MusicBrainzArtistProvider : IRemoteMetadataProvider<MusicArtist, ArtistInfo>, IDisposable
{ {
public class MusicBrainzArtistProvider : IRemoteMetadataProvider<MusicArtist, ArtistInfo> private readonly Query _musicBrainzQuery;
/// <summary>
/// Initializes a new instance of the <see cref="MusicBrainzArtistProvider"/> class.
/// </summary>
public MusicBrainzArtistProvider()
{ {
_musicBrainzQuery = new Query();
}
/// <inheritdoc />
public string Name => "MusicBrainz"; public string Name => "MusicBrainz";
/// <inheritdoc /> /// <inheritdoc />
public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(ArtistInfo searchInfo, CancellationToken cancellationToken) public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(ArtistInfo searchInfo, CancellationToken cancellationToken)
{ {
var musicBrainzId = searchInfo.GetMusicBrainzArtistId(); var artistId = searchInfo.GetMusicBrainzArtistId();
if (!string.IsNullOrWhiteSpace(musicBrainzId)) if (!string.IsNullOrWhiteSpace(artistId))
{ {
var url = "/ws/2/artist/?query=arid:{0}" + musicBrainzId.ToString(CultureInfo.InvariantCulture); var artistResult = await _musicBrainzQuery.LookupArtistAsync(new Guid(artistId), Include.Artists, null, null, cancellationToken).ConfigureAwait(false);
return GetResultFromResponse(artistResult).SingleItemAsEnumerable();
using var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);
return GetResultsFromResponse(stream);
} }
else
{
// They seem to throw bad request failures on any term with a slash
var nameToSearch = searchInfo.Name.Replace('/', ' ');
var url = string.Format(CultureInfo.InvariantCulture, "/ws/2/artist/?query=\"{0}\"&dismax=true", UrlEncode(nameToSearch)); var artistSearchResults = await _musicBrainzQuery.FindArtistsAsync($"\"{searchInfo.Name}\"", null, null, false, cancellationToken)
.ConfigureAwait(false);
using (var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false)) if (artistSearchResults.Results.Count > 0)
await using (var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false))
{ {
var results = GetResultsFromResponse(stream).ToList(); return GetResultsFromResponse(artistSearchResults.Results);
if (results.Count > 0)
{
return results;
}
} }
if (searchInfo.Name.HasDiacritics()) if (searchInfo.Name.HasDiacritics())
{ {
// Try again using the search with accent characters url // Try again using the search with an accented characters query
url = string.Format(CultureInfo.InvariantCulture, "/ws/2/artist/?query=artistaccent:\"{0}\"", UrlEncode(nameToSearch)); var artistAccentsSearchResults = await _musicBrainzQuery.FindArtistsAsync($"artistaccent:\"{searchInfo.Name}\"", null, null, false, cancellationToken)
.ConfigureAwait(false);
using var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false); if (artistAccentsSearchResults.Results.Count > 0)
await using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false); {
return GetResultsFromResponse(stream); return GetResultsFromResponse(artistAccentsSearchResults.Results);
} }
} }
return Enumerable.Empty<RemoteSearchResult>(); return Enumerable.Empty<RemoteSearchResult>();
} }
private IEnumerable<RemoteSearchResult> GetResultsFromResponse(Stream stream) private IEnumerable<RemoteSearchResult> GetResultsFromResponse(IEnumerable<ISearchResult<IArtist>>? releaseSearchResults)
{ {
using var oReader = new StreamReader(stream, Encoding.UTF8); if (releaseSearchResults is null)
var settings = new XmlReaderSettings()
{ {
ValidationType = ValidationType.None, yield break;
CheckCharacters = false, }
IgnoreProcessingInstructions = true,
IgnoreComments = true foreach (var result in releaseSearchResults)
{
yield return GetResultFromResponse(result.Item);
}
}
private IEnumerable<RemoteSearchResult> GetResultsFromResponse(IEnumerable<IArtist>? releaseSearchResults)
{
if (releaseSearchResults is null)
{
yield break;
}
foreach (var result in releaseSearchResults)
{
yield return GetResultFromResponse(result);
}
}
private RemoteSearchResult GetResultFromResponse(IArtist artist)
{
var searchResult = new RemoteSearchResult
{
Name = artist.Name,
ProductionYear = artist.LifeSpan?.Begin?.Year,
PremiereDate = artist.LifeSpan?.Begin?.NearestDate
}; };
using var reader = XmlReader.Create(oReader, settings); searchResult.SetProviderId(MetadataProvider.MusicBrainzArtist, artist.Id.ToString());
reader.MoveToContent();
reader.Read();
// Loop through each element return searchResult;
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "artist-list":
{
if (reader.IsEmptyElement)
{
reader.Read();
continue;
}
using var subReader = reader.ReadSubtree();
return ParseArtistList(subReader).ToList();
}
default:
{
reader.Skip();
break;
}
}
}
else
{
reader.Read();
}
}
return Enumerable.Empty<RemoteSearchResult>();
}
private IEnumerable<RemoteSearchResult> ParseArtistList(XmlReader reader)
{
reader.MoveToContent();
reader.Read();
// Loop through each element
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "artist":
{
if (reader.IsEmptyElement)
{
reader.Read();
continue;
}
var mbzId = reader.GetAttribute("id");
using var subReader = reader.ReadSubtree();
var artist = ParseArtist(subReader, mbzId);
if (artist != null)
{
yield return artist;
}
break;
}
default:
{
reader.Skip();
break;
}
}
}
else
{
reader.Read();
}
}
}
private RemoteSearchResult ParseArtist(XmlReader reader, string artistId)
{
var result = new RemoteSearchResult();
reader.MoveToContent();
reader.Read();
// http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
// Loop through each element
while (!reader.EOF && reader.ReadState == ReadState.Interactive)
{
if (reader.NodeType == XmlNodeType.Element)
{
switch (reader.Name)
{
case "name":
{
result.Name = reader.ReadElementContentAsString();
break;
}
case "annotation":
{
result.Overview = reader.ReadElementContentAsString();
break;
}
default:
{
// there is sort-name if ever needed
reader.Skip();
break;
}
}
}
else
{
reader.Read();
}
}
result.SetProviderId(MetadataProvider.MusicBrainzArtist, artistId);
if (string.IsNullOrWhiteSpace(artistId) || string.IsNullOrWhiteSpace(result.Name))
{
return null;
}
return result;
} }
/// <inheritdoc /> /// <inheritdoc />
public async Task<MetadataResult<MusicArtist>> GetMetadata(ArtistInfo info, CancellationToken cancellationToken) public async Task<MetadataResult<MusicArtist>> GetMetadata(ArtistInfo info, CancellationToken cancellationToken)
{ {
var result = new MetadataResult<MusicArtist> var result = new MetadataResult<MusicArtist> { Item = new MusicArtist() };
{
Item = new MusicArtist()
};
var musicBrainzId = info.GetMusicBrainzArtistId(); var musicBrainzId = info.GetMusicBrainzArtistId();
@ -240,7 +125,7 @@ namespace MediaBrowser.Providers.Music
musicBrainzId = singleResult.GetProviderId(MetadataProvider.MusicBrainzArtist); musicBrainzId = singleResult.GetProviderId(MetadataProvider.MusicBrainzArtist);
result.Item.Overview = singleResult.Overview; result.Item.Overview = singleResult.Overview;
if (Plugin.Instance.Configuration.ReplaceArtistName) if (Plugin.Instance!.Configuration.ReplaceArtistName)
{ {
result.Item.Name = singleResult.Name; result.Item.Name = singleResult.Name;
} }
@ -256,19 +141,28 @@ namespace MediaBrowser.Providers.Music
return result; return result;
} }
/// <summary> /// <inheritdoc />
/// Encodes an URL.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>System.String.</returns>
private static string UrlEncode(string name)
{
return WebUtility.UrlEncode(name);
}
public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken) public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
{ {
throw new NotImplementedException(); throw new NotImplementedException();
} }
/// <inheritdoc />
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Dispose all resources.
/// </summary>
/// <param name="disposing">Whether to dispose.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_musicBrainzQuery.Dispose();
}
} }
} }

View File

@ -1,15 +1,15 @@
#pragma warning disable CS1591
using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities; using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers; using MediaBrowser.Model.Providers;
using MediaBrowser.Providers.Plugins.MusicBrainz;
namespace MediaBrowser.Providers.Music namespace MediaBrowser.Providers.Plugins.MusicBrainz;
/// <summary>
/// MusicBrainz other artist external id.
/// </summary>
public class MusicBrainzOtherArtistExternalId : IExternalId
{ {
public class MusicBrainzOtherArtistExternalId : IExternalId
{
/// <inheritdoc /> /// <inheritdoc />
public string ProviderName => "MusicBrainz"; public string ProviderName => "MusicBrainz";
@ -20,9 +20,8 @@ namespace MediaBrowser.Providers.Music
public ExternalIdMediaType? Type => ExternalIdMediaType.OtherArtist; public ExternalIdMediaType? Type => ExternalIdMediaType.OtherArtist;
/// <inheritdoc /> /// <inheritdoc />
public string? UrlFormatString => Plugin.Instance.Configuration.Server + "/artist/{0}"; public string? UrlFormatString => Plugin.Instance!.Configuration.Server + "/artist/{0}";
/// <inheritdoc /> /// <inheritdoc />
public bool Supports(IHasProviderIds item) => item is Audio || item is MusicAlbum; public bool Supports(IHasProviderIds item) => item is Audio or MusicAlbum;
}
} }

View File

@ -1,15 +1,15 @@
#pragma warning disable CS1591
using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities; using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers; using MediaBrowser.Model.Providers;
using MediaBrowser.Providers.Plugins.MusicBrainz;
namespace MediaBrowser.Providers.Music namespace MediaBrowser.Providers.Plugins.MusicBrainz;
/// <summary>
/// MusicBrainz release group external id.
/// </summary>
public class MusicBrainzReleaseGroupExternalId : IExternalId
{ {
public class MusicBrainzReleaseGroupExternalId : IExternalId
{
/// <inheritdoc /> /// <inheritdoc />
public string ProviderName => "MusicBrainz"; public string ProviderName => "MusicBrainz";
@ -20,9 +20,8 @@ namespace MediaBrowser.Providers.Music
public ExternalIdMediaType? Type => ExternalIdMediaType.ReleaseGroup; public ExternalIdMediaType? Type => ExternalIdMediaType.ReleaseGroup;
/// <inheritdoc /> /// <inheritdoc />
public string? UrlFormatString => Plugin.Instance.Configuration.Server + "/release-group/{0}"; public string? UrlFormatString => Plugin.Instance!.Configuration.Server + "/release-group/{0}";
/// <inheritdoc /> /// <inheritdoc />
public bool Supports(IHasProviderIds item) => item is Audio || item is MusicAlbum; public bool Supports(IHasProviderIds item) => item is Audio or MusicAlbum;
}
} }

View File

@ -1,15 +1,15 @@
#pragma warning disable CS1591
using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Entities; using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers; using MediaBrowser.Model.Providers;
using MediaBrowser.Providers.Plugins.MusicBrainz;
namespace MediaBrowser.Providers.Music namespace MediaBrowser.Providers.Plugins.MusicBrainz;
/// <summary>
/// MusicBrainz track id.
/// </summary>
public class MusicBrainzTrackId : IExternalId
{ {
public class MusicBrainzTrackId : IExternalId
{
/// <inheritdoc /> /// <inheritdoc />
public string ProviderName => "MusicBrainz"; public string ProviderName => "MusicBrainz";
@ -20,9 +20,8 @@ namespace MediaBrowser.Providers.Music
public ExternalIdMediaType? Type => ExternalIdMediaType.Track; public ExternalIdMediaType? Type => ExternalIdMediaType.Track;
/// <inheritdoc /> /// <inheritdoc />
public string? UrlFormatString => Plugin.Instance.Configuration.Server + "/track/{0}"; public string? UrlFormatString => Plugin.Instance!.Configuration.Server + "/track/{0}";
/// <inheritdoc /> /// <inheritdoc />
public bool Supports(IHasProviderIds item) => item is Audio; public bool Supports(IHasProviderIds item) => item is Audio;
}
} }

View File

@ -1,38 +1,57 @@
#nullable disable
#pragma warning disable CS1591
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net.Http.Headers;
using System.Reflection;
using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.Plugins; using MediaBrowser.Common.Plugins;
using MediaBrowser.Model.Plugins; using MediaBrowser.Model.Plugins;
using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Serialization;
using MediaBrowser.Providers.Plugins.MusicBrainz.Configuration;
using MetaBrainz.MusicBrainz;
namespace MediaBrowser.Providers.Plugins.MusicBrainz namespace MediaBrowser.Providers.Plugins.MusicBrainz;
/// <summary>
/// Plugin instance.
/// </summary>
public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages
{ {
public class Plugin : BasePlugin<PluginConfiguration>, IHasWebPages /// <summary>
{ /// Initializes a new instance of the <see cref="Plugin"/> class.
public const string DefaultServer = "https://musicbrainz.org"; /// </summary>
/// <param name="applicationPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param>
public const long DefaultRateLimit = 2000u; /// <param name="xmlSerializer">Instance of the <see cref="IXmlSerializer"/> interface.</param>
public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer) public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer)
: base(applicationPaths, xmlSerializer) : base(applicationPaths, xmlSerializer)
{ {
Instance = this; Instance = this;
// TODO: Change this to "JellyfinMusicBrainzPlugin" once we take it out of the server repo.
Query.DefaultUserAgent.Add(new ProductInfoHeaderValue("Jellyfin", Assembly.GetExecutingAssembly().GetName().Version?.ToString(3)));
Query.DefaultUserAgent.Add(new ProductInfoHeaderValue("(apps@jellyfin.org)"));
Query.DelayBetweenRequests = Instance.Configuration.RateLimit;
Query.DefaultServer = Instance.Configuration.Server;
} }
public static Plugin Instance { get; private set; } /// <summary>
/// Gets the current plugin instance.
/// </summary>
public static Plugin? Instance { get; private set; }
/// <inheritdoc />
public override Guid Id => new Guid("8c95c4d2-e50c-4fb0-a4f3-6c06ff0f9a1a"); public override Guid Id => new Guid("8c95c4d2-e50c-4fb0-a4f3-6c06ff0f9a1a");
/// <inheritdoc />
public override string Name => "MusicBrainz"; public override string Name => "MusicBrainz";
/// <inheritdoc />
public override string Description => "Get artist and album metadata from any MusicBrainz server."; public override string Description => "Get artist and album metadata from any MusicBrainz server.";
/// <inheritdoc />
// TODO remove when plugin removed from server. // TODO remove when plugin removed from server.
public override string ConfigurationFileName => "Jellyfin.Plugin.MusicBrainz.xml"; public override string ConfigurationFileName => "Jellyfin.Plugin.MusicBrainz.xml";
/// <inheritdoc />
public IEnumerable<PluginPageInfo> GetPages() public IEnumerable<PluginPageInfo> GetPages()
{ {
yield return new PluginPageInfo yield return new PluginPageInfo
@ -41,5 +60,4 @@ namespace MediaBrowser.Providers.Plugins.MusicBrainz
EmbeddedResourcePath = GetType().Namespace + ".Configuration.config.html" EmbeddedResourcePath = GetType().Namespace + ".Configuration.config.html"
}; };
} }
}
} }

View File

@ -1,13 +1,13 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
namespace Jellyfin.Extensions namespace Jellyfin.Extensions;
/// <summary>
/// Static extensions for the <see cref="IEnumerable{T}"/> interface.
/// </summary>
public static class EnumerableExtensions
{ {
/// <summary>
/// Static extensions for the <see cref="IEnumerable{T}"/> interface.
/// </summary>
public static class EnumerableExtensions
{
/// <summary> /// <summary>
/// Determines whether the value is contained in the source collection. /// Determines whether the value is contained in the source collection.
/// </summary> /// </summary>
@ -44,5 +44,15 @@ namespace Jellyfin.Extensions
return false; return false;
} }
/// <summary>
/// Gets an IEnumerable from a single item.
/// </summary>
/// <param name="item">The item to return.</param>
/// <typeparam name="T">The type of item.</typeparam>
/// <returns>The IEnumerable{T}.</returns>
public static IEnumerable<T> SingleItemAsEnumerable<T>(this T item)
{
yield return item;
} }
} }

View File

@ -7,7 +7,7 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities; using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers; using MediaBrowser.Model.Providers;
using MediaBrowser.Providers.Music; using MediaBrowser.Providers.Plugins.MusicBrainz;
using MediaBrowser.XbmcMetadata.Parsers; using MediaBrowser.XbmcMetadata.Parsers;
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using Moq; using Moq;

View File

@ -7,7 +7,7 @@ using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities; using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Providers; using MediaBrowser.Model.Providers;
using MediaBrowser.Providers.Music; using MediaBrowser.Providers.Plugins.MusicBrainz;
using MediaBrowser.XbmcMetadata.Parsers; using MediaBrowser.XbmcMetadata.Parsers;
using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Logging.Abstractions;
using Moq; using Moq;