ArtistProvider.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Http;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using System.Xml;
  13. using MediaBrowser.Controller.Entities.Audio;
  14. using MediaBrowser.Controller.Extensions;
  15. using MediaBrowser.Controller.Providers;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.Providers;
  18. using MediaBrowser.Providers.Plugins.MusicBrainz;
  19. namespace MediaBrowser.Providers.Music
  20. {
  21. public class MusicBrainzArtistProvider : IRemoteMetadataProvider<MusicArtist, ArtistInfo>
  22. {
  23. /// <inheritdoc />
  24. public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(ArtistInfo searchInfo, CancellationToken cancellationToken)
  25. {
  26. // TODO maybe remove when artist metadata can be disabled
  27. if (!Plugin.Instance.Configuration.Enable)
  28. {
  29. return Enumerable.Empty<RemoteSearchResult>();
  30. }
  31. var musicBrainzId = searchInfo.GetMusicBrainzArtistId();
  32. if (!string.IsNullOrWhiteSpace(musicBrainzId))
  33. {
  34. var url = "/ws/2/artist/?query=arid:{0}" + musicBrainzId.ToString(CultureInfo.InvariantCulture);
  35. using var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  36. await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  37. return GetResultsFromResponse(stream);
  38. }
  39. else
  40. {
  41. // They seem to throw bad request failures on any term with a slash
  42. var nameToSearch = searchInfo.Name.Replace('/', ' ');
  43. var url = string.Format(CultureInfo.InvariantCulture, "/ws/2/artist/?query=\"{0}\"&dismax=true", UrlEncode(nameToSearch));
  44. using (var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false))
  45. await using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
  46. {
  47. var results = GetResultsFromResponse(stream).ToList();
  48. if (results.Count > 0)
  49. {
  50. return results;
  51. }
  52. }
  53. if (HasDiacritics(searchInfo.Name))
  54. {
  55. // Try again using the search with accent characters url
  56. url = string.Format(CultureInfo.InvariantCulture, "/ws/2/artist/?query=artistaccent:\"{0}\"", UrlEncode(nameToSearch));
  57. using var response = await MusicBrainzAlbumProvider.Current.GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  58. await using var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
  59. return GetResultsFromResponse(stream);
  60. }
  61. }
  62. return Enumerable.Empty<RemoteSearchResult>();
  63. }
  64. private IEnumerable<RemoteSearchResult> GetResultsFromResponse(Stream stream)
  65. {
  66. using (var oReader = new StreamReader(stream, Encoding.UTF8))
  67. {
  68. var settings = new XmlReaderSettings()
  69. {
  70. ValidationType = ValidationType.None,
  71. CheckCharacters = false,
  72. IgnoreProcessingInstructions = true,
  73. IgnoreComments = true
  74. };
  75. using (var reader = XmlReader.Create(oReader, settings))
  76. {
  77. reader.MoveToContent();
  78. reader.Read();
  79. // Loop through each element
  80. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  81. {
  82. if (reader.NodeType == XmlNodeType.Element)
  83. {
  84. switch (reader.Name)
  85. {
  86. case "artist-list":
  87. {
  88. if (reader.IsEmptyElement)
  89. {
  90. reader.Read();
  91. continue;
  92. }
  93. using (var subReader = reader.ReadSubtree())
  94. {
  95. return ParseArtistList(subReader).ToList();
  96. }
  97. }
  98. default:
  99. {
  100. reader.Skip();
  101. break;
  102. }
  103. }
  104. }
  105. else
  106. {
  107. reader.Read();
  108. }
  109. }
  110. return Enumerable.Empty<RemoteSearchResult>();
  111. }
  112. }
  113. }
  114. private IEnumerable<RemoteSearchResult> ParseArtistList(XmlReader reader)
  115. {
  116. reader.MoveToContent();
  117. reader.Read();
  118. // Loop through each element
  119. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  120. {
  121. if (reader.NodeType == XmlNodeType.Element)
  122. {
  123. switch (reader.Name)
  124. {
  125. case "artist":
  126. {
  127. if (reader.IsEmptyElement)
  128. {
  129. reader.Read();
  130. continue;
  131. }
  132. var mbzId = reader.GetAttribute("id");
  133. using (var subReader = reader.ReadSubtree())
  134. {
  135. var artist = ParseArtist(subReader, mbzId);
  136. if (artist != null)
  137. {
  138. yield return artist;
  139. }
  140. }
  141. break;
  142. }
  143. default:
  144. {
  145. reader.Skip();
  146. break;
  147. }
  148. }
  149. }
  150. else
  151. {
  152. reader.Read();
  153. }
  154. }
  155. }
  156. private RemoteSearchResult ParseArtist(XmlReader reader, string artistId)
  157. {
  158. var result = new RemoteSearchResult();
  159. reader.MoveToContent();
  160. reader.Read();
  161. // http://stackoverflow.com/questions/2299632/why-does-xmlreader-skip-every-other-element-if-there-is-no-whitespace-separator
  162. // Loop through each element
  163. while (!reader.EOF && reader.ReadState == ReadState.Interactive)
  164. {
  165. if (reader.NodeType == XmlNodeType.Element)
  166. {
  167. switch (reader.Name)
  168. {
  169. case "name":
  170. {
  171. result.Name = reader.ReadElementContentAsString();
  172. break;
  173. }
  174. case "annotation":
  175. {
  176. result.Overview = reader.ReadElementContentAsString();
  177. break;
  178. }
  179. default:
  180. {
  181. // there is sort-name if ever needed
  182. reader.Skip();
  183. break;
  184. }
  185. }
  186. }
  187. else
  188. {
  189. reader.Read();
  190. }
  191. }
  192. result.SetProviderId(MetadataProvider.MusicBrainzArtist, artistId);
  193. if (string.IsNullOrWhiteSpace(artistId) || string.IsNullOrWhiteSpace(result.Name))
  194. {
  195. return null;
  196. }
  197. return result;
  198. }
  199. public async Task<MetadataResult<MusicArtist>> GetMetadata(ArtistInfo id, CancellationToken cancellationToken)
  200. {
  201. var result = new MetadataResult<MusicArtist>
  202. {
  203. Item = new MusicArtist()
  204. };
  205. // TODO maybe remove when artist metadata can be disabled
  206. if (!Plugin.Instance.Configuration.Enable)
  207. {
  208. return result;
  209. }
  210. var musicBrainzId = id.GetMusicBrainzArtistId();
  211. if (string.IsNullOrWhiteSpace(musicBrainzId))
  212. {
  213. var searchResults = await GetSearchResults(id, cancellationToken).ConfigureAwait(false);
  214. var singleResult = searchResults.FirstOrDefault();
  215. if (singleResult != null)
  216. {
  217. musicBrainzId = singleResult.GetProviderId(MetadataProvider.MusicBrainzArtist);
  218. result.Item.Overview = singleResult.Overview;
  219. if (Plugin.Instance.Configuration.ReplaceArtistName)
  220. {
  221. result.Item.Name = singleResult.Name;
  222. }
  223. }
  224. }
  225. if (!string.IsNullOrWhiteSpace(musicBrainzId))
  226. {
  227. result.HasMetadata = true;
  228. result.Item.SetProviderId(MetadataProvider.MusicBrainzArtist, musicBrainzId);
  229. }
  230. return result;
  231. }
  232. /// <summary>
  233. /// Determines whether the specified text has diacritics.
  234. /// </summary>
  235. /// <param name="text">The text.</param>
  236. /// <returns><c>true</c> if the specified text has diacritics; otherwise, <c>false</c>.</returns>
  237. private bool HasDiacritics(string text)
  238. {
  239. return !string.Equals(text, text.RemoveDiacritics(), StringComparison.Ordinal);
  240. }
  241. /// <summary>
  242. /// Encodes an URL.
  243. /// </summary>
  244. /// <param name="name">The name.</param>
  245. /// <returns>System.String.</returns>
  246. private static string UrlEncode(string name)
  247. {
  248. return WebUtility.UrlEncode(name);
  249. }
  250. public string Name => "MusicBrainz";
  251. public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
  252. {
  253. throw new NotImplementedException();
  254. }
  255. }
  256. }