FanArtAlbumProvider.cs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. EnableResponseCache = true
  127. }).ConfigureAwait(false))
  128. {
  129. doc.Load(xml);
  130. }
  131. cancellationToken.ThrowIfCancellationRequested();
  132. if (doc.HasChildNodes)
  133. {
  134. if (ConfigurationManager.Configuration.DownloadMusicAlbumImages.Disc && !item.ResolveArgs.ContainsMetaFileByName(DiscFile))
  135. {
  136. var node = doc.SelectSingleNode("//fanart/music/albums/album/cdart/@url");
  137. var path = node != null ? node.Value : null;
  138. if (!string.IsNullOrEmpty(path))
  139. {
  140. Logger.Debug("FanArtProvider getting Disc for " + item.Name);
  141. item.SetImage(ImageType.Disc, await _providerManager.DownloadAndSaveImage(item, path, DiscFile, ConfigurationManager.Configuration.SaveLocalMeta, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  142. }
  143. }
  144. if (ConfigurationManager.Configuration.DownloadMusicAlbumImages.Primary && !item.ResolveArgs.ContainsMetaFileByName(PrimaryFile))
  145. {
  146. var node = doc.SelectSingleNode("//fanart/music/albums/album/albumcover/@url");
  147. var path = node != null ? node.Value : null;
  148. if (!string.IsNullOrEmpty(path))
  149. {
  150. Logger.Debug("FanArtProvider getting albumcover for " + item.Name);
  151. item.SetImage(ImageType.Primary, await _providerManager.DownloadAndSaveImage(item, path, PrimaryFile, ConfigurationManager.Configuration.SaveLocalMeta, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  152. }
  153. }
  154. }
  155. SetLastRefreshed(item, DateTime.UtcNow);
  156. return true;
  157. }
  158. /// <summary>
  159. /// The _last music brainz request
  160. /// </summary>
  161. private DateTime _lastRequestDate = DateTime.MinValue;
  162. /// <summary>
  163. /// Gets the music brainz response.
  164. /// </summary>
  165. /// <param name="url">The URL.</param>
  166. /// <param name="cancellationToken">The cancellation token.</param>
  167. /// <returns>Task{XmlDocument}.</returns>
  168. internal async Task<XmlDocument> GetMusicBrainzResponse(string url, CancellationToken cancellationToken)
  169. {
  170. await _musicBrainzResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  171. try
  172. {
  173. var diff = 1500 - (DateTime.Now - _lastRequestDate).TotalMilliseconds;
  174. // MusicBrainz is extremely adamant about limiting to one request per second
  175. if (diff > 0)
  176. {
  177. await Task.Delay(Convert.ToInt32(diff), cancellationToken).ConfigureAwait(false);
  178. }
  179. _lastRequestDate = DateTime.Now;
  180. var doc = new XmlDocument();
  181. using (var xml = await HttpClient.Get(new HttpRequestOptions
  182. {
  183. Url = url,
  184. CancellationToken = cancellationToken,
  185. UserAgent = Environment.MachineName + "-" + Environment.UserName,
  186. EnableResponseCache = true
  187. }).ConfigureAwait(false))
  188. {
  189. using (var oReader = new StreamReader(xml, Encoding.UTF8))
  190. {
  191. doc.Load(oReader);
  192. }
  193. }
  194. return doc;
  195. }
  196. finally
  197. {
  198. _lastRequestDate = DateTime.Now;
  199. _musicBrainzResourcePool.Release();
  200. }
  201. }
  202. /// <summary>
  203. /// Gets the release group id internal.
  204. /// </summary>
  205. /// <param name="releaseEntryId">The release entry id.</param>
  206. /// <param name="cancellationToken">The cancellation token.</param>
  207. /// <returns>Task{System.String}.</returns>
  208. private async Task<string> GetReleaseGroupId(string releaseEntryId, CancellationToken cancellationToken)
  209. {
  210. var url = string.Format("http://www.musicbrainz.org/ws/2/release-group/?query=reid:{0}", releaseEntryId);
  211. var doc = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  212. var ns = new XmlNamespaceManager(doc.NameTable);
  213. ns.AddNamespace("mb", "http://musicbrainz.org/ns/mmd-2.0#");
  214. var node = doc.SelectSingleNode("//mb:release-group-list/mb:release-group/@id", ns);
  215. return node != null ? node.Value : null;
  216. }
  217. }
  218. }