FanArtAlbumProvider.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Entities.Audio;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Logging;
  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 "16";
  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. // Refresh anytime the parent mbz id changes
  98. if (providerInfo.Data != GetComparisonData(item.Parent.GetProviderId(MetadataProviders.Musicbrainz)))
  99. {
  100. return true;
  101. }
  102. return base.NeedsRefreshInternal(item, providerInfo);
  103. }
  104. /// <summary>
  105. /// Gets the comparison data.
  106. /// </summary>
  107. /// <returns>Guid.</returns>
  108. private Guid GetComparisonData(string id)
  109. {
  110. return string.IsNullOrEmpty(id) ? Guid.Empty : id.GetMD5();
  111. }
  112. /// <summary>
  113. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  114. /// </summary>
  115. /// <param name="item">The item.</param>
  116. /// <param name="force">if set to <c>true</c> [force].</param>
  117. /// <param name="cancellationToken">The cancellation token.</param>
  118. /// <returns>Task{System.Boolean}.</returns>
  119. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  120. {
  121. cancellationToken.ThrowIfCancellationRequested();
  122. var artistMusicBrainzId = item.Parent.GetProviderId(MetadataProviders.Musicbrainz);
  123. BaseProviderInfo data;
  124. if (!item.ProviderData.TryGetValue(Id, out data))
  125. {
  126. data = new BaseProviderInfo();
  127. item.ProviderData[Id] = data;
  128. }
  129. if (!string.IsNullOrEmpty(artistMusicBrainzId))
  130. {
  131. var album = (MusicAlbum)item;
  132. if (string.IsNullOrEmpty(album.MusicBrainzReleaseGroupId))
  133. {
  134. album.MusicBrainzReleaseGroupId = await GetReleaseGroupId(item.GetProviderId(MetadataProviders.Musicbrainz), cancellationToken).ConfigureAwait(false);
  135. }
  136. // If still empty there's nothing more we can do
  137. if (!string.IsNullOrEmpty(album.MusicBrainzReleaseGroupId))
  138. {
  139. var artistXmlPath = FanArtArtistProvider.GetArtistDataPath(ConfigurationManager.CommonApplicationPaths, artistMusicBrainzId);
  140. artistXmlPath = Path.Combine(artistXmlPath, "fanart.xml");
  141. var artistXmlFileInfo = new FileInfo(artistXmlPath);
  142. if (artistXmlFileInfo.Exists)
  143. {
  144. var doc = new XmlDocument();
  145. doc.Load(artistXmlPath);
  146. cancellationToken.ThrowIfCancellationRequested();
  147. if (ConfigurationManager.Configuration.DownloadMusicAlbumImages.Disc && !item.HasImage(ImageType.Disc))
  148. {
  149. var node = doc.SelectSingleNode("//fanart/music/albums/album[@id=\"" + album.MusicBrainzReleaseGroupId + "\"]/cdart/@url");
  150. var path = node != null ? node.Value : null;
  151. if (!string.IsNullOrEmpty(path))
  152. {
  153. item.SetImage(ImageType.Disc, await _providerManager.DownloadAndSaveImage(item, path, DiscFile, ConfigurationManager.Configuration.SaveLocalMeta, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  154. }
  155. }
  156. if (ConfigurationManager.Configuration.DownloadMusicAlbumImages.Primary && !item.HasImage(ImageType.Primary))
  157. {
  158. var node = doc.SelectSingleNode("//fanart/music/albums/album[@id=\"" + album.MusicBrainzReleaseGroupId + "\"]/albumcover/@url");
  159. var path = node != null ? node.Value : null;
  160. if (!string.IsNullOrEmpty(path))
  161. {
  162. item.SetImage(ImageType.Primary, await _providerManager.DownloadAndSaveImage(item, path, PrimaryFile, ConfigurationManager.Configuration.SaveLocalMeta, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  163. }
  164. }
  165. }
  166. }
  167. }
  168. data.Data = GetComparisonData(artistMusicBrainzId);
  169. SetLastRefreshed(item, DateTime.UtcNow);
  170. return true;
  171. }
  172. /// <summary>
  173. /// The _last music brainz request
  174. /// </summary>
  175. private DateTime _lastRequestDate = DateTime.MinValue;
  176. /// <summary>
  177. /// Gets the music brainz response.
  178. /// </summary>
  179. /// <param name="url">The URL.</param>
  180. /// <param name="cancellationToken">The cancellation token.</param>
  181. /// <returns>Task{XmlDocument}.</returns>
  182. internal async Task<XmlDocument> GetMusicBrainzResponse(string url, CancellationToken cancellationToken)
  183. {
  184. await _musicBrainzResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  185. try
  186. {
  187. var diff = 1500 - (DateTime.Now - _lastRequestDate).TotalMilliseconds;
  188. // MusicBrainz is extremely adamant about limiting to one request per second
  189. if (diff > 0)
  190. {
  191. await Task.Delay(Convert.ToInt32(diff), cancellationToken).ConfigureAwait(false);
  192. }
  193. _lastRequestDate = DateTime.Now;
  194. var doc = new XmlDocument();
  195. using (var xml = await HttpClient.Get(new HttpRequestOptions
  196. {
  197. Url = url,
  198. CancellationToken = cancellationToken,
  199. UserAgent = Environment.MachineName
  200. }).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. _lastRequestDate = DateTime.Now;
  212. _musicBrainzResourcePool.Release();
  213. }
  214. }
  215. /// <summary>
  216. /// Gets the release group id internal.
  217. /// </summary>
  218. /// <param name="releaseEntryId">The release entry id.</param>
  219. /// <param name="cancellationToken">The cancellation token.</param>
  220. /// <returns>Task{System.String}.</returns>
  221. private async Task<string> GetReleaseGroupId(string releaseEntryId, CancellationToken cancellationToken)
  222. {
  223. var url = string.Format("http://www.musicbrainz.org/ws/2/release-group/?query=reid:{0}", releaseEntryId);
  224. var doc = await GetMusicBrainzResponse(url, cancellationToken).ConfigureAwait(false);
  225. var ns = new XmlNamespaceManager(doc.NameTable);
  226. ns.AddNamespace("mb", "http://musicbrainz.org/ns/mmd-2.0#");
  227. var node = doc.SelectSingleNode("//mb:release-group-list/mb:release-group/@id", ns);
  228. return node != null ? node.Value : null;
  229. }
  230. }
  231. }