123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286 |
- using MediaBrowser.Common.Net;
- using MediaBrowser.Controller.Configuration;
- using MediaBrowser.Controller.Entities;
- using MediaBrowser.Controller.Entities.Audio;
- using MediaBrowser.Controller.Library;
- using MediaBrowser.Controller.Providers;
- using MediaBrowser.Model.Entities;
- using MediaBrowser.Model.Logging;
- using MediaBrowser.Model.Net;
- using MediaBrowser.Model.Serialization;
- using System;
- using System.Globalization;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Xml;
- namespace MediaBrowser.Providers.Music
- {
- /// <summary>
- /// Class LastfmArtistProvider
- /// </summary>
- public class LastfmArtistProvider : LastfmBaseProvider
- {
- /// <summary>
- /// The _library manager
- /// </summary>
- protected readonly ILibraryManager LibraryManager;
- /// <summary>
- /// Initializes a new instance of the <see cref="LastfmArtistProvider" /> class.
- /// </summary>
- /// <param name="jsonSerializer">The json serializer.</param>
- /// <param name="httpClient">The HTTP client.</param>
- /// <param name="logManager">The log manager.</param>
- /// <param name="configurationManager">The configuration manager.</param>
- /// <param name="libraryManager">The library manager.</param>
- public LastfmArtistProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, ILogManager logManager, IServerConfigurationManager configurationManager, ILibraryManager libraryManager)
- : base(jsonSerializer, httpClient, logManager, configurationManager)
- {
- LibraryManager = libraryManager;
- }
- protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
- {
- if (HasAltMeta(item))
- {
- return false;
- }
- return base.NeedsRefreshInternal(item, providerInfo);
- }
- /// <summary>
- /// Gets the priority.
- /// </summary>
- /// <value>The priority.</value>
- public override MetadataProviderPriority Priority
- {
- get { return MetadataProviderPriority.Third; }
- }
- private bool HasAltMeta(BaseItem item)
- {
- return item.LocationType == LocationType.FileSystem && item.ResolveArgs.ContainsMetaFileByName("artist.xml");
- }
-
- /// <summary>
- /// Finds the id.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{System.String}.</returns>
- protected override async Task<string> FindId(BaseItem item, CancellationToken cancellationToken)
- {
- if (item is Artist)
- {
- // Since MusicArtists are refreshed first, try to find it from one of them
- var id = FindIdFromMusicArtistEntity(item);
- if (!string.IsNullOrEmpty(id))
- {
- return id;
- }
- }
- //// Try to find the id using last fm
- //var result = await FindIdFromLastFm(item, cancellationToken).ConfigureAwait(false);
- //if (result != null)
- //{
- // if (!string.IsNullOrEmpty(result))
- // {
- // return result;
- // }
- //}
- try
- {
- // If we don't get anything, go directly to music brainz
- return await FindIdFromMusicBrainz(item, cancellationToken).ConfigureAwait(false);
- }
- catch (HttpException e)
- {
- if (e.StatusCode.HasValue && e.StatusCode.Value == HttpStatusCode.BadRequest)
- {
- // They didn't like a character in the name. Handle the exception so that the provider doesn't keep retrying over and over
- return null;
- }
- throw;
- }
- }
- /// <summary>
- /// Finds the id from music artist entity.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <returns>System.String.</returns>
- private string FindIdFromMusicArtistEntity(BaseItem item)
- {
- var artist = LibraryManager.RootFolder.RecursiveChildren.OfType<MusicArtist>()
- .FirstOrDefault(i => string.Compare(i.Name, item.Name, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols) == 0);
- return artist != null ? artist.GetProviderId(MetadataProviders.Musicbrainz) : null;
- }
- /// <summary>
- /// Finds the id from last fm.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{System.String}.</returns>
- private async Task<string> FindIdFromLastFm(BaseItem item, CancellationToken cancellationToken)
- {
- //Execute the Artist search against our name and assume first one is the one we want
- var url = RootUrl + string.Format("method=artist.search&artist={0}&api_key={1}&format=json", UrlEncode(item.Name), ApiKey);
- using (var json = await HttpClient.Get(new HttpRequestOptions
- {
- Url = url,
- ResourcePool = LastfmResourcePool,
- CancellationToken = cancellationToken,
- EnableHttpCompression = false
- }).ConfigureAwait(false))
- {
- using (var reader = new StreamReader(json, true))
- {
- var jsonString = await reader.ReadToEndAsync().ConfigureAwait(false);
- // Sometimes they send back an empty response or just the text "null"
- if (!jsonString.StartsWith("{", StringComparison.OrdinalIgnoreCase))
- {
- return null;
- }
- var searchResult = JsonSerializer.DeserializeFromString<LastfmArtistSearchResults>(jsonString);
- if (searchResult != null && searchResult.results != null && searchResult.results.artistmatches != null && searchResult.results.artistmatches.artist.Count > 0)
- {
- var artist = searchResult.results.artistmatches.artist
- .FirstOrDefault(i => i.name != null && string.Compare(i.name, item.Name, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols) == 0);
- return artist == null ? null : artist.mbid;
- }
- }
- }
- return null;
- }
- /// <summary>
- /// Finds the id from music brainz.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task{System.String}.</returns>
- private async Task<string> FindIdFromMusicBrainz(BaseItem item, CancellationToken cancellationToken)
- {
- // They seem to throw bad request failures on any term with a slash
- var nameToSearch = item.Name.Replace('/', ' ');
- var url = string.Format("http://www.musicbrainz.org/ws/2/artist/?query=artist:{0}", UrlEncode(nameToSearch));
- var doc = await FanArtAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
- var ns = new XmlNamespaceManager(doc.NameTable);
- ns.AddNamespace("mb", "http://musicbrainz.org/ns/mmd-2.0#");
- var node = doc.SelectSingleNode("//mb:artist-list/mb:artist[@type='Group']/@id", ns);
- if (node != null && node.Value != null)
- {
- return node.Value;
- }
- if (HasDiacritics(item.Name))
- {
- // Try again using the search with accent characters url
- url = string.Format("http://www.musicbrainz.org/ws/2/artist/?query=artistaccent:{0}", UrlEncode(nameToSearch));
- doc = await FanArtAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
- ns = new XmlNamespaceManager(doc.NameTable);
- ns.AddNamespace("mb", "http://musicbrainz.org/ns/mmd-2.0#");
- node = doc.SelectSingleNode("//mb:artist-list/mb:artist[@type='Group']/@id", ns);
- if (node != null && node.Value != null)
- {
- return node.Value;
- }
- }
- return null;
- }
- /// <summary>
- /// Determines whether the specified text has diacritics.
- /// </summary>
- /// <param name="text">The text.</param>
- /// <returns><c>true</c> if the specified text has diacritics; otherwise, <c>false</c>.</returns>
- private bool HasDiacritics(string text)
- {
- return !string.Equals(text, RemoveDiacritics(text), StringComparison.Ordinal);
- }
- /// <summary>
- /// Removes the diacritics.
- /// </summary>
- /// <param name="text">The text.</param>
- /// <returns>System.String.</returns>
- private string RemoveDiacritics(string text)
- {
- return string.Concat(
- text.Normalize(NormalizationForm.FormD)
- .Where(ch => CharUnicodeInfo.GetUnicodeCategory(ch) !=
- UnicodeCategory.NonSpacingMark)
- ).Normalize(NormalizationForm.FormC);
- }
- /// <summary>
- /// Fetches the lastfm data.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <param name="musicBrainzId">The music brainz id.</param>
- /// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>Task.</returns>
- protected override async Task FetchLastfmData(BaseItem item, string musicBrainzId, CancellationToken cancellationToken)
- {
- // Get artist info with provided id
- var url = RootUrl + string.Format("method=artist.getInfo&mbid={0}&api_key={1}&format=json", UrlEncode(musicBrainzId), ApiKey);
- LastfmGetArtistResult result;
- using (var json = await HttpClient.Get(new HttpRequestOptions
- {
- Url = url,
- ResourcePool = LastfmResourcePool,
- CancellationToken = cancellationToken,
- EnableHttpCompression = false
- }).ConfigureAwait(false))
- {
- result = JsonSerializer.DeserializeFromStream<LastfmGetArtistResult>(json);
- }
- if (result != null && result.artist != null)
- {
- LastfmHelper.ProcessArtistData(item, result.artist);
- }
- }
- /// <summary>
- /// Supportses the specified item.
- /// </summary>
- /// <param name="item">The item.</param>
- /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
- public override bool Supports(BaseItem item)
- {
- return item is MusicArtist;
- }
- }
- }
|