LastfmArtistProvider.cs 12 KB

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