LastfmArtistProvider.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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 "9";
  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. private 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. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  105. /// </summary>
  106. /// <param name="item">The item.</param>
  107. /// <param name="force">if set to <c>true</c> [force].</param>
  108. /// <param name="cancellationToken">The cancellation token</param>
  109. /// <returns>Task{System.Boolean}.</returns>
  110. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  111. {
  112. cancellationToken.ThrowIfCancellationRequested();
  113. var id = item.GetProviderId(MetadataProviders.Musicbrainz) ?? await FindId(item, cancellationToken).ConfigureAwait(false);
  114. if (!string.IsNullOrWhiteSpace(id))
  115. {
  116. cancellationToken.ThrowIfCancellationRequested();
  117. item.SetProviderId(MetadataProviders.Musicbrainz, id);
  118. await FetchLastfmData(item, id, force, cancellationToken).ConfigureAwait(false);
  119. }
  120. SetLastRefreshed(item, DateTime.UtcNow);
  121. return true;
  122. }
  123. /// <summary>
  124. /// Finds the id from music artist entity.
  125. /// </summary>
  126. /// <param name="item">The item.</param>
  127. /// <returns>System.String.</returns>
  128. private string FindIdFromMusicArtistEntity(BaseItem item)
  129. {
  130. var artist = LibraryManager.RootFolder.RecursiveChildren.OfType<MusicArtist>()
  131. .FirstOrDefault(i => string.Compare(i.Name, item.Name, CultureInfo.CurrentCulture, CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase | CompareOptions.IgnoreSymbols) == 0);
  132. return artist != null ? artist.GetProviderId(MetadataProviders.Musicbrainz) : null;
  133. }
  134. /// <summary>
  135. /// Finds the id from music brainz.
  136. /// </summary>
  137. /// <param name="item">The item.</param>
  138. /// <param name="cancellationToken">The cancellation token.</param>
  139. /// <returns>Task{System.String}.</returns>
  140. private async Task<string> FindIdFromMusicBrainz(BaseItem item, CancellationToken cancellationToken)
  141. {
  142. // They seem to throw bad request failures on any term with a slash
  143. var nameToSearch = item.Name.Replace('/', ' ');
  144. var url = string.Format("http://www.musicbrainz.org/ws/2/artist/?query=artist:\"{0}\"", UrlEncode(nameToSearch));
  145. var doc = await LastfmAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  146. var ns = new XmlNamespaceManager(doc.NameTable);
  147. ns.AddNamespace("mb", "http://musicbrainz.org/ns/mmd-2.0#");
  148. var node = doc.SelectSingleNode("//mb:artist-list/mb:artist/@id", ns);
  149. if (node != null && node.Value != null)
  150. {
  151. return node.Value;
  152. }
  153. if (HasDiacritics(item.Name))
  154. {
  155. // Try again using the search with accent characters url
  156. url = string.Format("http://www.musicbrainz.org/ws/2/artist/?query=artistaccent:\"{0}\"", UrlEncode(nameToSearch));
  157. doc = await LastfmAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  158. ns = new XmlNamespaceManager(doc.NameTable);
  159. ns.AddNamespace("mb", "http://musicbrainz.org/ns/mmd-2.0#");
  160. node = doc.SelectSingleNode("//mb:artist-list/mb:artist/@id", ns);
  161. if (node != null && node.Value != null)
  162. {
  163. return node.Value;
  164. }
  165. }
  166. return null;
  167. }
  168. /// <summary>
  169. /// Determines whether the specified text has diacritics.
  170. /// </summary>
  171. /// <param name="text">The text.</param>
  172. /// <returns><c>true</c> if the specified text has diacritics; otherwise, <c>false</c>.</returns>
  173. private bool HasDiacritics(string text)
  174. {
  175. return !string.Equals(text, RemoveDiacritics(text), StringComparison.Ordinal);
  176. }
  177. /// <summary>
  178. /// Removes the diacritics.
  179. /// </summary>
  180. /// <param name="text">The text.</param>
  181. /// <returns>System.String.</returns>
  182. private string RemoveDiacritics(string text)
  183. {
  184. return string.Concat(
  185. text.Normalize(NormalizationForm.FormD)
  186. .Where(ch => CharUnicodeInfo.GetUnicodeCategory(ch) !=
  187. UnicodeCategory.NonSpacingMark)
  188. ).Normalize(NormalizationForm.FormC);
  189. }
  190. /// <summary>
  191. /// Fetches the lastfm data.
  192. /// </summary>
  193. /// <param name="item">The item.</param>
  194. /// <param name="musicBrainzId">The music brainz id.</param>
  195. /// <param name="cancellationToken">The cancellation token.</param>
  196. /// <returns>Task.</returns>
  197. protected virtual async Task FetchLastfmData(BaseItem item, string musicBrainzId, bool force, CancellationToken cancellationToken)
  198. {
  199. // Get artist info with provided id
  200. var url = RootUrl + string.Format("method=artist.getInfo&mbid={0}&api_key={1}&format=json", UrlEncode(musicBrainzId), ApiKey);
  201. LastfmGetArtistResult result;
  202. using (var json = await HttpClient.Get(new HttpRequestOptions
  203. {
  204. Url = url,
  205. ResourcePool = LastfmResourcePool,
  206. CancellationToken = cancellationToken,
  207. EnableHttpCompression = false
  208. }).ConfigureAwait(false))
  209. {
  210. using (var reader = new StreamReader(json))
  211. {
  212. var jsonText = await reader.ReadToEndAsync().ConfigureAwait(false);
  213. // Fix their bad json
  214. jsonText = jsonText.Replace("\"#text\"", "\"url\"");
  215. result = JsonSerializer.DeserializeFromString<LastfmGetArtistResult>(jsonText);
  216. }
  217. }
  218. if (result != null && result.artist != null)
  219. {
  220. LastfmHelper.ProcessArtistData(item, result.artist);
  221. }
  222. }
  223. /// <summary>
  224. /// Supportses the specified item.
  225. /// </summary>
  226. /// <param name="item">The item.</param>
  227. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  228. public override bool Supports(BaseItem item)
  229. {
  230. return item is MusicArtist;
  231. }
  232. }
  233. }