FanArtAlbumProvider.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Entities.Audio;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.Logging;
  7. using System;
  8. using System.IO;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using System.Xml;
  13. namespace MediaBrowser.Controller.Providers.Music
  14. {
  15. /// <summary>
  16. /// Class FanArtAlbumProvider
  17. /// </summary>
  18. public class FanArtAlbumProvider : FanartBaseProvider
  19. {
  20. /// <summary>
  21. /// The _provider manager
  22. /// </summary>
  23. private readonly IProviderManager _providerManager;
  24. /// <summary>
  25. /// The _music brainz resource pool
  26. /// </summary>
  27. private readonly SemaphoreSlim _musicBrainzResourcePool = new SemaphoreSlim(1, 1);
  28. /// <summary>
  29. /// Gets the HTTP client.
  30. /// </summary>
  31. /// <value>The HTTP client.</value>
  32. protected IHttpClient HttpClient { get; private set; }
  33. internal static FanArtAlbumProvider Current { get; private set; }
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="FanArtAlbumProvider"/> class.
  36. /// </summary>
  37. /// <param name="httpClient">The HTTP client.</param>
  38. /// <param name="logManager">The log manager.</param>
  39. /// <param name="configurationManager">The configuration manager.</param>
  40. /// <param name="providerManager">The provider manager.</param>
  41. public FanArtAlbumProvider(IHttpClient httpClient, ILogManager logManager, IServerConfigurationManager configurationManager, IProviderManager providerManager)
  42. : base(logManager, configurationManager)
  43. {
  44. _providerManager = providerManager;
  45. HttpClient = httpClient;
  46. Current = this;
  47. }
  48. /// <summary>
  49. /// Supportses the specified item.
  50. /// </summary>
  51. /// <param name="item">The item.</param>
  52. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  53. public override bool Supports(BaseItem item)
  54. {
  55. return item is MusicAlbum;
  56. }
  57. /// <summary>
  58. /// Gets a value indicating whether [refresh on version change].
  59. /// </summary>
  60. /// <value><c>true</c> if [refresh on version change]; otherwise, <c>false</c>.</value>
  61. protected override bool RefreshOnVersionChange
  62. {
  63. get
  64. {
  65. return true;
  66. }
  67. }
  68. /// <summary>
  69. /// Gets the provider version.
  70. /// </summary>
  71. /// <value>The provider version.</value>
  72. protected override string ProviderVersion
  73. {
  74. get
  75. {
  76. return "12";
  77. }
  78. }
  79. /// <summary>
  80. /// Needses the refresh internal.
  81. /// </summary>
  82. /// <param name="item">The item.</param>
  83. /// <param name="providerInfo">The provider info.</param>
  84. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  85. protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  86. {
  87. if (string.IsNullOrEmpty(item.GetProviderId(MetadataProviders.Musicbrainz)))
  88. {
  89. return false;
  90. }
  91. if (!ConfigurationManager.Configuration.DownloadMusicAlbumImages.Disc &&
  92. !ConfigurationManager.Configuration.DownloadMusicAlbumImages.Primary)
  93. {
  94. return false;
  95. }
  96. return base.NeedsRefreshInternal(item, providerInfo);
  97. }
  98. /// <summary>
  99. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  100. /// </summary>
  101. /// <param name="item">The item.</param>
  102. /// <param name="force">if set to <c>true</c> [force].</param>
  103. /// <param name="cancellationToken">The cancellation token.</param>
  104. /// <returns>Task{System.Boolean}.</returns>
  105. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  106. {
  107. cancellationToken.ThrowIfCancellationRequested();
  108. var album = (MusicAlbum)item;
  109. if (string.IsNullOrEmpty(album.MusicBrainzReleaseGroupId))
  110. {
  111. album.MusicBrainzReleaseGroupId = await GetReleaseGroupId(item.GetProviderId(MetadataProviders.Musicbrainz), cancellationToken).ConfigureAwait(false);
  112. }
  113. // If still empty there's nothing more we can do
  114. if (string.IsNullOrEmpty(album.MusicBrainzReleaseGroupId))
  115. {
  116. SetLastRefreshed(item, DateTime.UtcNow);
  117. return true;
  118. }
  119. var url = string.Format("http://api.fanart.tv/webservice/album/{0}/{1}/xml/all/1/1", ApiKey, album.MusicBrainzReleaseGroupId);
  120. var doc = new XmlDocument();
  121. using (var xml = await HttpClient.Get(new HttpRequestOptions
  122. {
  123. Url = url,
  124. ResourcePool = FanArtResourcePool,
  125. CancellationToken = cancellationToken
  126. }).ConfigureAwait(false))
  127. {
  128. doc.Load(xml);
  129. }
  130. cancellationToken.ThrowIfCancellationRequested();
  131. if (doc.HasChildNodes)
  132. {
  133. if (ConfigurationManager.Configuration.DownloadMusicAlbumImages.Disc && !item.HasImage(ImageType.Disc))
  134. {
  135. var node = doc.SelectSingleNode("//fanart/music/albums/album/cdart/@url");
  136. var path = node != null ? node.Value : null;
  137. if (!string.IsNullOrEmpty(path))
  138. {
  139. Logger.Debug("FanArtProvider getting Disc for " + item.Name);
  140. item.SetImage(ImageType.Disc, await _providerManager.DownloadAndSaveImage(item, path, DiscFile, ConfigurationManager.Configuration.SaveLocalMeta, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  141. }
  142. }
  143. if (ConfigurationManager.Configuration.DownloadMusicAlbumImages.Primary && !item.HasImage(ImageType.Primary))
  144. {
  145. var node = doc.SelectSingleNode("//fanart/music/albums/album/albumcover/@url");
  146. var path = node != null ? node.Value : null;
  147. if (!string.IsNullOrEmpty(path))
  148. {
  149. Logger.Debug("FanArtProvider getting albumcover for " + item.Name);
  150. item.SetImage(ImageType.Primary, await _providerManager.DownloadAndSaveImage(item, path, PrimaryFile, ConfigurationManager.Configuration.SaveLocalMeta, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  151. }
  152. }
  153. }
  154. SetLastRefreshed(item, DateTime.UtcNow);
  155. return true;
  156. }
  157. /// <summary>
  158. /// The _last music brainz request
  159. /// </summary>
  160. private DateTime _lastRequestDate = DateTime.MinValue;
  161. /// <summary>
  162. /// Gets the music brainz response.
  163. /// </summary>
  164. /// <param name="url">The URL.</param>
  165. /// <param name="cancellationToken">The cancellation token.</param>
  166. /// <returns>Task{XmlDocument}.</returns>
  167. internal async Task<XmlDocument> GetMusicBrainzResponse(string url, CancellationToken cancellationToken)
  168. {
  169. await _musicBrainzResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  170. try
  171. {
  172. var diff = 1500 - (DateTime.Now - _lastRequestDate).TotalMilliseconds;
  173. // MusicBrainz is extremely adamant about limiting to one request per second
  174. if (diff > 0)
  175. {
  176. await Task.Delay(Convert.ToInt32(diff), cancellationToken).ConfigureAwait(false);
  177. }
  178. _lastRequestDate = DateTime.Now;
  179. var doc = new XmlDocument();
  180. using (var xml = await HttpClient.Get(new HttpRequestOptions
  181. {
  182. Url = url,
  183. CancellationToken = cancellationToken,
  184. UserAgent = Environment.MachineName
  185. }).ConfigureAwait(false))
  186. {
  187. using (var oReader = new StreamReader(xml, Encoding.UTF8))
  188. {
  189. doc.Load(oReader);
  190. }
  191. }
  192. return doc;
  193. }
  194. finally
  195. {
  196. _lastRequestDate = DateTime.Now;
  197. _musicBrainzResourcePool.Release();
  198. }
  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, 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. }
  216. }