FanArtAlbumProvider.cs 10.0 KB

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