LastfmArtistProvider.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. using System;
  2. using System.Globalization;
  3. using System.Net;
  4. using System.Text;
  5. using MediaBrowser.Common.Net;
  6. using MediaBrowser.Controller.Configuration;
  7. using MediaBrowser.Controller.Entities;
  8. using MediaBrowser.Controller.Entities.Audio;
  9. using MediaBrowser.Controller.Library;
  10. using MediaBrowser.Model.Entities;
  11. using MediaBrowser.Model.Logging;
  12. using MediaBrowser.Model.Net;
  13. using MediaBrowser.Model.Serialization;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using System.Xml;
  19. using Mediabrowser.Model.Entities;
  20. namespace MediaBrowser.Controller.Providers.Music
  21. {
  22. public class LastfmArtistProvider : LastfmBaseProvider
  23. {
  24. private readonly IProviderManager _providerManager;
  25. private readonly ILibraryManager _libraryManager;
  26. public LastfmArtistProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, ILogManager logManager, IServerConfigurationManager configurationManager, IProviderManager providerManager)
  27. : base(jsonSerializer, httpClient, logManager, configurationManager)
  28. {
  29. _providerManager = providerManager;
  30. LocalMetaFileName = LastfmHelper.LocalArtistMetaFileName;
  31. }
  32. /// <summary>
  33. /// Finds the id.
  34. /// </summary>
  35. /// <param name="item">The item.</param>
  36. /// <param name="cancellationToken">The cancellation token.</param>
  37. /// <returns>Task{System.String}.</returns>
  38. protected override async Task<string> FindId(BaseItem item, CancellationToken cancellationToken)
  39. {
  40. if (item is Artist)
  41. {
  42. // Since MusicArtists are refreshed first, try to find it from one of them
  43. var id = FindIdFromMusicArtistEntity(item);
  44. if (!string.IsNullOrEmpty(id))
  45. {
  46. return id;
  47. }
  48. }
  49. // Try to find the id using last fm
  50. var result = await FindIdFromLastFm(item, cancellationToken).ConfigureAwait(false);
  51. if (!string.IsNullOrEmpty(result.Item1))
  52. {
  53. return result.Item1;
  54. }
  55. // If there were no artists returned at all, then don't bother with musicbrainz
  56. if (!result.Item2)
  57. {
  58. return null;
  59. }
  60. try
  61. {
  62. // If we don't get anything, go directly to music brainz
  63. return await FindIdFromMusicBrainz(item, cancellationToken).ConfigureAwait(false);
  64. }
  65. catch (HttpException e)
  66. {
  67. if (e.StatusCode.HasValue && e.StatusCode.Value == HttpStatusCode.BadRequest)
  68. {
  69. // They didn't like a character in the name. Handle the exception so that the provider doesn't keep retrying over and over
  70. return null;
  71. }
  72. throw;
  73. }
  74. }
  75. private string FindIdFromMusicArtistEntity(BaseItem item)
  76. {
  77. var artist = _libraryManager.RootFolder.RecursiveChildren.OfType<MusicArtist>()
  78. .FirstOrDefault(i => string.Equals(i.Name, item.Name, StringComparison.OrdinalIgnoreCase));
  79. return artist != null ? artist.GetProviderId(MetadataProviders.Musicbrainz) : null;
  80. }
  81. private async Task<Tuple<string,bool>> FindIdFromLastFm(BaseItem item, CancellationToken cancellationToken)
  82. {
  83. //Execute the Artist search against our name and assume first one is the one we want
  84. var url = RootUrl + string.Format("method=artist.search&artist={0}&api_key={1}&format=json", UrlEncode(item.Name), ApiKey);
  85. LastfmArtistSearchResults searchResult;
  86. try
  87. {
  88. using (var json = await HttpClient.Get(url, LastfmResourcePool, cancellationToken).ConfigureAwait(false))
  89. {
  90. searchResult = JsonSerializer.DeserializeFromStream<LastfmArtistSearchResults>(json);
  91. }
  92. }
  93. catch (HttpException e)
  94. {
  95. return null;
  96. }
  97. if (searchResult != null && searchResult.results != null && searchResult.results.artistmatches != null && searchResult.results.artistmatches.artist.Count > 0)
  98. {
  99. var artist = searchResult.results.artistmatches.artist.FirstOrDefault(i => i.name != null && string.Compare(i.name, item.Name, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace) == 0) ??
  100. searchResult.results.artistmatches.artist.First();
  101. return new Tuple<string, bool>(artist.mbid, true);
  102. }
  103. return new Tuple<string,bool>(null, false);
  104. }
  105. private async Task<string> FindIdFromMusicBrainz(BaseItem item, CancellationToken cancellationToken)
  106. {
  107. // They seem to throw bad request failures on any term with a slash
  108. var nameToSearch = item.Name.Replace('/', ' ');
  109. var url = string.Format("http://www.musicbrainz.org/ws/2/artist/?query=artist:{0}", UrlEncode(nameToSearch));
  110. var doc = await FanArtAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  111. var ns = new XmlNamespaceManager(doc.NameTable);
  112. ns.AddNamespace("mb", "http://musicbrainz.org/ns/mmd-2.0#");
  113. var node = doc.SelectSingleNode("//mb:artist-list/mb:artist[@type='Group']/@id", ns);
  114. if (node != null && node.Value != null)
  115. {
  116. return node.Value;
  117. }
  118. if (HasDiacritics(item.Name))
  119. {
  120. // Try again using the search with accent characters url
  121. url = string.Format("http://www.musicbrainz.org/ws/2/artist/?query=artistaccent:{0}", UrlEncode(nameToSearch));
  122. doc = await FanArtAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  123. ns = new XmlNamespaceManager(doc.NameTable);
  124. ns.AddNamespace("mb", "http://musicbrainz.org/ns/mmd-2.0#");
  125. node = doc.SelectSingleNode("//mb:artist-list/mb:artist[@type='Group']/@id", ns);
  126. if (node != null && node.Value != null)
  127. {
  128. return node.Value;
  129. }
  130. }
  131. return null;
  132. }
  133. private bool HasDiacritics(string text)
  134. {
  135. return !string.Equals(text, RemoveDiacritics(text), StringComparison.Ordinal);
  136. }
  137. private string RemoveDiacritics(string text)
  138. {
  139. return string.Concat(
  140. text.Normalize(NormalizationForm.FormD)
  141. .Where(ch => CharUnicodeInfo.GetUnicodeCategory(ch) !=
  142. UnicodeCategory.NonSpacingMark)
  143. ).Normalize(NormalizationForm.FormC);
  144. }
  145. protected override async Task FetchLastfmData(BaseItem item, string id, CancellationToken cancellationToken)
  146. {
  147. // Get artist info with provided id
  148. var url = RootUrl + string.Format("method=artist.getInfo&mbid={0}&api_key={1}&format=json", UrlEncode(id), ApiKey);
  149. LastfmGetArtistResult result;
  150. using (var json = await HttpClient.Get(url, LastfmResourcePool, cancellationToken).ConfigureAwait(false))
  151. {
  152. result = JsonSerializer.DeserializeFromStream<LastfmGetArtistResult>(json);
  153. }
  154. if (result != null && result.artist != null)
  155. {
  156. LastfmHelper.ProcessArtistData(item, result.artist);
  157. //And save locally if indicated
  158. if (SaveLocalMeta)
  159. {
  160. var ms = new MemoryStream();
  161. JsonSerializer.SerializeToStream(result.artist, ms);
  162. if (cancellationToken.IsCancellationRequested)
  163. {
  164. ms.Dispose();
  165. cancellationToken.ThrowIfCancellationRequested();
  166. }
  167. await _providerManager.SaveToLibraryFilesystem(item, Path.Combine(item.MetaLocation, LocalMetaFileName), ms, cancellationToken).ConfigureAwait(false);
  168. }
  169. }
  170. }
  171. public override bool Supports(BaseItem item)
  172. {
  173. return item is MusicArtist;
  174. }
  175. }
  176. }