FanArtAlbumProvider.cs 12 KB

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