FanArtAlbumProvider.cs 11 KB

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