MusicBrainzAlbumProvider.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. using MediaBrowser.Common;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Entities.Audio;
  4. using MediaBrowser.Controller.Providers;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Providers;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.IO;
  11. using System.Linq;
  12. using System.Net;
  13. using System.Text;
  14. using System.Threading;
  15. using System.Threading.Tasks;
  16. using System.Xml;
  17. namespace MediaBrowser.Providers.Music
  18. {
  19. public class MusicBrainzAlbumProvider : IRemoteMetadataProvider<MusicAlbum, AlbumInfo>, IHasOrder
  20. {
  21. internal static MusicBrainzAlbumProvider Current;
  22. private readonly IHttpClient _httpClient;
  23. private readonly IApplicationHost _appHost;
  24. private readonly ILogger _logger;
  25. public MusicBrainzAlbumProvider(IHttpClient httpClient, IApplicationHost appHost, ILogger logger)
  26. {
  27. _httpClient = httpClient;
  28. _appHost = appHost;
  29. _logger = logger;
  30. Current = this;
  31. }
  32. public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(AlbumInfo searchInfo, CancellationToken cancellationToken)
  33. {
  34. var releaseId = searchInfo.GetReleaseId();
  35. string url = null;
  36. var isNameSearch = false;
  37. if (!string.IsNullOrEmpty(releaseId))
  38. {
  39. url = string.Format("http://www.musicbrainz.org/ws/2/release/?query=reid:{0}", releaseId);
  40. }
  41. else
  42. {
  43. var artistMusicBrainzId = searchInfo.GetMusicBrainzArtistId();
  44. if (!string.IsNullOrWhiteSpace(artistMusicBrainzId))
  45. {
  46. url = string.Format("http://www.musicbrainz.org/ws/2/release/?query=\"{0}\" AND arid:{1}",
  47. WebUtility.UrlEncode(searchInfo.Name),
  48. artistMusicBrainzId);
  49. }
  50. else
  51. {
  52. isNameSearch = true;
  53. url = string.Format("http://www.musicbrainz.org/ws/2/release/?query=\"{0}\" AND artist:\"{1}\"",
  54. WebUtility.UrlEncode(searchInfo.Name),
  55. WebUtility.UrlEncode(searchInfo.GetAlbumArtist()));
  56. }
  57. }
  58. if (!string.IsNullOrWhiteSpace(url))
  59. {
  60. var doc = await GetMusicBrainzResponse(url, isNameSearch, cancellationToken).ConfigureAwait(false);
  61. return GetResultsFromResponse(doc);
  62. }
  63. return new List<RemoteSearchResult>();
  64. }
  65. private IEnumerable<RemoteSearchResult> GetResultsFromResponse(XmlDocument doc)
  66. {
  67. var ns = new XmlNamespaceManager(doc.NameTable);
  68. ns.AddNamespace("mb", "http://musicbrainz.org/ns/mmd-2.0#");
  69. var list = new List<RemoteSearchResult>();
  70. var nodes = doc.SelectNodes("//mb:release-list/mb:release", ns);
  71. if (nodes != null)
  72. {
  73. foreach (var node in nodes.Cast<XmlNode>())
  74. {
  75. if (node.Attributes != null)
  76. {
  77. string name = null;
  78. string mbzId = node.Attributes["id"].Value;
  79. var nameNode = node.SelectSingleNode("//mb:title", ns);
  80. if (nameNode != null)
  81. {
  82. name = nameNode.InnerText;
  83. }
  84. if (!string.IsNullOrWhiteSpace(mbzId) && !string.IsNullOrWhiteSpace(name))
  85. {
  86. var result = new RemoteSearchResult
  87. {
  88. Name = name
  89. };
  90. result.SetProviderId(MetadataProviders.MusicBrainzAlbum, mbzId);
  91. list.Add(result);
  92. }
  93. }
  94. }
  95. }
  96. return list;
  97. }
  98. public async Task<MetadataResult<MusicAlbum>> GetMetadata(AlbumInfo id, CancellationToken cancellationToken)
  99. {
  100. var releaseId = id.GetReleaseId();
  101. var releaseGroupId = id.GetReleaseGroupId();
  102. var result = new MetadataResult<MusicAlbum>
  103. {
  104. Item = new MusicAlbum()
  105. };
  106. if (string.IsNullOrEmpty(releaseId))
  107. {
  108. var artistMusicBrainzId = id.GetMusicBrainzArtistId();
  109. var releaseResult = await GetReleaseResult(artistMusicBrainzId, id.GetAlbumArtist(), id.Name, cancellationToken).ConfigureAwait(false);
  110. if (!string.IsNullOrEmpty(releaseResult.ReleaseId))
  111. {
  112. releaseId = releaseResult.ReleaseId;
  113. result.HasMetadata = true;
  114. }
  115. if (!string.IsNullOrEmpty(releaseResult.ReleaseGroupId))
  116. {
  117. releaseGroupId = releaseResult.ReleaseGroupId;
  118. result.HasMetadata = true;
  119. }
  120. }
  121. // If we have a release Id but not a release group Id...
  122. if (!string.IsNullOrEmpty(releaseId) && string.IsNullOrEmpty(releaseGroupId))
  123. {
  124. releaseGroupId = await GetReleaseGroupId(releaseId, cancellationToken).ConfigureAwait(false);
  125. result.HasMetadata = true;
  126. }
  127. if (!string.IsNullOrEmpty(releaseId) || !string.IsNullOrEmpty(releaseGroupId))
  128. {
  129. result.HasMetadata = true;
  130. }
  131. if (result.HasMetadata)
  132. {
  133. if (!string.IsNullOrEmpty(releaseId))
  134. {
  135. result.Item.SetProviderId(MetadataProviders.MusicBrainzAlbum, releaseId);
  136. }
  137. if (!string.IsNullOrEmpty(releaseGroupId))
  138. {
  139. result.Item.SetProviderId(MetadataProviders.MusicBrainzReleaseGroup, releaseGroupId);
  140. }
  141. }
  142. return result;
  143. }
  144. public string Name
  145. {
  146. get { return "MusicBrainz"; }
  147. }
  148. private Task<ReleaseResult> GetReleaseResult(string artistMusicBrainId, string artistName, string albumName, CancellationToken cancellationToken)
  149. {
  150. if (!string.IsNullOrEmpty(artistMusicBrainId))
  151. {
  152. return GetReleaseResult(albumName, artistMusicBrainId, cancellationToken);
  153. }
  154. if (string.IsNullOrWhiteSpace(artistName))
  155. {
  156. return Task.FromResult(new ReleaseResult());
  157. }
  158. return GetReleaseResultByArtistName(albumName, artistName, cancellationToken);
  159. }
  160. private async Task<ReleaseResult> GetReleaseResult(string albumName, string artistId, CancellationToken cancellationToken)
  161. {
  162. var url = string.Format("http://www.musicbrainz.org/ws/2/release/?query=\"{0}\" AND arid:{1}",
  163. WebUtility.UrlEncode(albumName),
  164. artistId);
  165. var doc = await GetMusicBrainzResponse(url, true, cancellationToken).ConfigureAwait(false);
  166. return GetReleaseResult(doc);
  167. }
  168. private async Task<ReleaseResult> GetReleaseResultByArtistName(string albumName, string artistName, CancellationToken cancellationToken)
  169. {
  170. var url = string.Format("http://www.musicbrainz.org/ws/2/release/?query=\"{0}\" AND artist:\"{1}\"",
  171. WebUtility.UrlEncode(albumName),
  172. WebUtility.UrlEncode(artistName));
  173. var doc = await GetMusicBrainzResponse(url, true, cancellationToken).ConfigureAwait(false);
  174. return GetReleaseResult(doc);
  175. }
  176. private ReleaseResult GetReleaseResult(XmlDocument doc)
  177. {
  178. var ns = new XmlNamespaceManager(doc.NameTable);
  179. ns.AddNamespace("mb", "http://musicbrainz.org/ns/mmd-2.0#");
  180. var result = new ReleaseResult
  181. {
  182. };
  183. var releaseIdNode = doc.SelectSingleNode("//mb:release-list/mb:release/@id", ns);
  184. if (releaseIdNode != null)
  185. {
  186. result.ReleaseId = releaseIdNode.Value;
  187. }
  188. var releaseGroupIdNode = doc.SelectSingleNode("//mb:release-list/mb:release/mb:release-group/@id", ns);
  189. if (releaseGroupIdNode != null)
  190. {
  191. result.ReleaseGroupId = releaseGroupIdNode.Value;
  192. }
  193. return result;
  194. }
  195. private class ReleaseResult
  196. {
  197. public string ReleaseId;
  198. public string ReleaseGroupId;
  199. }
  200. /// <summary>
  201. /// Gets the release group id internal.
  202. /// </summary>
  203. /// <param name="releaseEntryId">The release entry id.</param>
  204. /// <param name="cancellationToken">The cancellation token.</param>
  205. /// <returns>Task{System.String}.</returns>
  206. private async Task<string> GetReleaseGroupId(string releaseEntryId, CancellationToken cancellationToken)
  207. {
  208. var url = string.Format("http://www.musicbrainz.org/ws/2/release-group/?query=reid:{0}", releaseEntryId);
  209. var doc = await GetMusicBrainzResponse(url, false, cancellationToken).ConfigureAwait(false);
  210. var ns = new XmlNamespaceManager(doc.NameTable);
  211. ns.AddNamespace("mb", "http://musicbrainz.org/ns/mmd-2.0#");
  212. var node = doc.SelectSingleNode("//mb:release-group-list/mb:release-group/@id", ns);
  213. return node != null ? node.Value : null;
  214. }
  215. /// <summary>
  216. /// The _music brainz resource pool
  217. /// </summary>
  218. private readonly SemaphoreSlim _musicBrainzResourcePool = new SemaphoreSlim(1, 1);
  219. /// <summary>
  220. /// Gets the music brainz response.
  221. /// </summary>
  222. /// <param name="url">The URL.</param>
  223. /// <param name="isSearch">if set to <c>true</c> [is search].</param>
  224. /// <param name="cancellationToken">The cancellation token.</param>
  225. /// <returns>Task{XmlDocument}.</returns>
  226. internal async Task<XmlDocument> GetMusicBrainzResponse(string url, bool isSearch, CancellationToken cancellationToken)
  227. {
  228. // MusicBrainz is extremely adamant about limiting to one request per second
  229. await Task.Delay(1000, cancellationToken).ConfigureAwait(false);
  230. var doc = new XmlDocument();
  231. var options = new HttpRequestOptions
  232. {
  233. Url = url,
  234. CancellationToken = cancellationToken,
  235. UserAgent = _appHost.Name + "/" + _appHost.ApplicationVersion,
  236. ResourcePool = _musicBrainzResourcePool
  237. };
  238. if (!isSearch)
  239. {
  240. options.CacheMode = CacheMode.Unconditional;
  241. options.CacheLength = TimeSpan.FromDays(7);
  242. }
  243. using (var xml = await _httpClient.Get(options).ConfigureAwait(false))
  244. {
  245. using (var oReader = new StreamReader(xml, Encoding.UTF8))
  246. {
  247. doc.Load(oReader);
  248. }
  249. }
  250. return doc;
  251. }
  252. public int Order
  253. {
  254. get { return 0; }
  255. }
  256. public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
  257. {
  258. throw new NotImplementedException();
  259. }
  260. }
  261. }