LastfmArtistProvider.cs 11 KB

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