LastfmArtistProvider.cs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Entities.Audio;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Providers;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Logging;
  9. using MediaBrowser.Model.Net;
  10. using MediaBrowser.Model.Serialization;
  11. using System;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Net;
  16. using System.Text;
  17. using System.Threading;
  18. using System.Threading.Tasks;
  19. using System.Xml;
  20. namespace MediaBrowser.Providers.Music
  21. {
  22. /// <summary>
  23. /// Class LastfmArtistProvider
  24. /// </summary>
  25. public class LastfmArtistProvider : LastfmBaseProvider
  26. {
  27. /// <summary>
  28. /// The _library manager
  29. /// </summary>
  30. protected readonly ILibraryManager LibraryManager;
  31. /// <summary>
  32. /// Initializes a new instance of the <see cref="LastfmArtistProvider" /> class.
  33. /// </summary>
  34. /// <param name="jsonSerializer">The json serializer.</param>
  35. /// <param name="httpClient">The HTTP client.</param>
  36. /// <param name="logManager">The log manager.</param>
  37. /// <param name="configurationManager">The configuration manager.</param>
  38. /// <param name="libraryManager">The library manager.</param>
  39. public LastfmArtistProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, ILogManager logManager, IServerConfigurationManager configurationManager, ILibraryManager libraryManager)
  40. : base(jsonSerializer, httpClient, logManager, configurationManager)
  41. {
  42. LibraryManager = libraryManager;
  43. }
  44. protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  45. {
  46. if (HasAltMeta(item))
  47. {
  48. return false;
  49. }
  50. return base.NeedsRefreshInternal(item, providerInfo);
  51. }
  52. protected override string ProviderVersion
  53. {
  54. get
  55. {
  56. return "8";
  57. }
  58. }
  59. /// <summary>
  60. /// Gets the priority.
  61. /// </summary>
  62. /// <value>The priority.</value>
  63. public override MetadataProviderPriority Priority
  64. {
  65. get { return MetadataProviderPriority.Third; }
  66. }
  67. private bool HasAltMeta(BaseItem item)
  68. {
  69. return item.LocationType == LocationType.FileSystem && item.ResolveArgs.ContainsMetaFileByName("artist.xml");
  70. }
  71. /// <summary>
  72. /// Finds the id.
  73. /// </summary>
  74. /// <param name="item">The item.</param>
  75. /// <param name="cancellationToken">The cancellation token.</param>
  76. /// <returns>Task{System.String}.</returns>
  77. protected override async Task<string> FindId(BaseItem item, CancellationToken cancellationToken)
  78. {
  79. if (item is Artist)
  80. {
  81. // Since MusicArtists are refreshed first, try to find it from one of them
  82. var id = FindIdFromMusicArtistEntity(item);
  83. if (!string.IsNullOrEmpty(id))
  84. {
  85. return id;
  86. }
  87. }
  88. try
  89. {
  90. // If we don't get anything, go directly to music brainz
  91. return await FindIdFromMusicBrainz(item, cancellationToken).ConfigureAwait(false);
  92. }
  93. catch (HttpException e)
  94. {
  95. if (e.StatusCode.HasValue && e.StatusCode.Value == HttpStatusCode.BadRequest)
  96. {
  97. // They didn't like a character in the name. Handle the exception so that the provider doesn't keep retrying over and over
  98. return null;
  99. }
  100. throw;
  101. }
  102. }
  103. /// <summary>
  104. /// Finds the id from music artist entity.
  105. /// </summary>
  106. /// <param name="item">The item.</param>
  107. /// <returns>System.String.</returns>
  108. private string FindIdFromMusicArtistEntity(BaseItem item)
  109. {
  110. var artist = LibraryManager.RootFolder.RecursiveChildren.OfType<MusicArtist>()
  111. .FirstOrDefault(i => string.Compare(i.Name, item.Name, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols) == 0);
  112. return artist != null ? artist.GetProviderId(MetadataProviders.Musicbrainz) : null;
  113. }
  114. /// <summary>
  115. /// Finds the id from music brainz.
  116. /// </summary>
  117. /// <param name="item">The item.</param>
  118. /// <param name="cancellationToken">The cancellation token.</param>
  119. /// <returns>Task{System.String}.</returns>
  120. private async Task<string> FindIdFromMusicBrainz(BaseItem item, CancellationToken cancellationToken)
  121. {
  122. // They seem to throw bad request failures on any term with a slash
  123. var nameToSearch = item.Name.Replace('/', ' ');
  124. var url = string.Format("http://www.musicbrainz.org/ws/2/artist/?query=artist:{0}", UrlEncode(nameToSearch));
  125. var doc = await FanArtAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  126. var ns = new XmlNamespaceManager(doc.NameTable);
  127. ns.AddNamespace("mb", "http://musicbrainz.org/ns/mmd-2.0#");
  128. var node = doc.SelectSingleNode("//mb:artist-list/mb:artist/@id", ns);
  129. if (node != null && node.Value != null)
  130. {
  131. return node.Value;
  132. }
  133. if (HasDiacritics(item.Name))
  134. {
  135. // Try again using the search with accent characters url
  136. url = string.Format("http://www.musicbrainz.org/ws/2/artist/?query=artistaccent:{0}", UrlEncode(nameToSearch));
  137. doc = await FanArtAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  138. ns = new XmlNamespaceManager(doc.NameTable);
  139. ns.AddNamespace("mb", "http://musicbrainz.org/ns/mmd-2.0#");
  140. node = doc.SelectSingleNode("//mb:artist-list/mb:artist/@id", ns);
  141. if (node != null && node.Value != null)
  142. {
  143. return node.Value;
  144. }
  145. }
  146. return null;
  147. }
  148. /// <summary>
  149. /// Determines whether the specified text has diacritics.
  150. /// </summary>
  151. /// <param name="text">The text.</param>
  152. /// <returns><c>true</c> if the specified text has diacritics; otherwise, <c>false</c>.</returns>
  153. private bool HasDiacritics(string text)
  154. {
  155. return !string.Equals(text, RemoveDiacritics(text), StringComparison.Ordinal);
  156. }
  157. /// <summary>
  158. /// Removes the diacritics.
  159. /// </summary>
  160. /// <param name="text">The text.</param>
  161. /// <returns>System.String.</returns>
  162. private string RemoveDiacritics(string text)
  163. {
  164. return string.Concat(
  165. text.Normalize(NormalizationForm.FormD)
  166. .Where(ch => CharUnicodeInfo.GetUnicodeCategory(ch) !=
  167. UnicodeCategory.NonSpacingMark)
  168. ).Normalize(NormalizationForm.FormC);
  169. }
  170. /// <summary>
  171. /// Fetches the lastfm data.
  172. /// </summary>
  173. /// <param name="item">The item.</param>
  174. /// <param name="musicBrainzId">The music brainz id.</param>
  175. /// <param name="cancellationToken">The cancellation token.</param>
  176. /// <returns>Task.</returns>
  177. protected override async Task FetchLastfmData(BaseItem item, string musicBrainzId, bool force, CancellationToken cancellationToken)
  178. {
  179. // Get artist info with provided id
  180. var url = RootUrl + string.Format("method=artist.getInfo&mbid={0}&api_key={1}&format=json", UrlEncode(musicBrainzId), ApiKey);
  181. LastfmGetArtistResult result;
  182. using (var json = await HttpClient.Get(new HttpRequestOptions
  183. {
  184. Url = url,
  185. ResourcePool = LastfmResourcePool,
  186. CancellationToken = cancellationToken,
  187. EnableHttpCompression = false
  188. }).ConfigureAwait(false))
  189. {
  190. using (var reader = new StreamReader(json))
  191. {
  192. var jsonText = await reader.ReadToEndAsync().ConfigureAwait(false);
  193. // Fix their bad json
  194. jsonText = jsonText.Replace("\"#text\"", "\"url\"");
  195. result = JsonSerializer.DeserializeFromString<LastfmGetArtistResult>(jsonText);
  196. }
  197. }
  198. if (result != null && result.artist != null)
  199. {
  200. LastfmHelper.ProcessArtistData(item, result.artist);
  201. }
  202. }
  203. /// <summary>
  204. /// Supportses the specified item.
  205. /// </summary>
  206. /// <param name="item">The item.</param>
  207. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  208. public override bool Supports(BaseItem item)
  209. {
  210. return item is MusicArtist;
  211. }
  212. }
  213. }