FanArtArtistProvider.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.IO;
  4. using MediaBrowser.Common.Net;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Entities;
  7. using MediaBrowser.Controller.Entities.Audio;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using System.Xml;
  18. namespace MediaBrowser.Controller.Providers.Music
  19. {
  20. /// <summary>
  21. /// Class FanArtArtistProvider
  22. /// </summary>
  23. public class FanArtArtistProvider : FanartBaseProvider
  24. {
  25. /// <summary>
  26. /// Gets the HTTP client.
  27. /// </summary>
  28. /// <value>The HTTP client.</value>
  29. protected IHttpClient HttpClient { get; private set; }
  30. /// <summary>
  31. /// The _provider manager
  32. /// </summary>
  33. private readonly IProviderManager _providerManager;
  34. internal static FanArtArtistProvider Current;
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="FanArtArtistProvider"/> 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. /// <exception cref="System.ArgumentNullException">httpClient</exception>
  43. public FanArtArtistProvider(IHttpClient httpClient, ILogManager logManager, IServerConfigurationManager configurationManager, IProviderManager providerManager)
  44. : base(logManager, configurationManager)
  45. {
  46. if (httpClient == null)
  47. {
  48. throw new ArgumentNullException("httpClient");
  49. }
  50. HttpClient = httpClient;
  51. _providerManager = providerManager;
  52. Current = this;
  53. }
  54. /// <summary>
  55. /// The fan art base URL
  56. /// </summary>
  57. protected string FanArtBaseUrl = "http://api.fanart.tv/webservice/artist/{0}/{1}/xml/all/1/1";
  58. /// <summary>
  59. /// Supportses the specified item.
  60. /// </summary>
  61. /// <param name="item">The item.</param>
  62. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  63. public override bool Supports(BaseItem item)
  64. {
  65. return item is MusicArtist;
  66. }
  67. /// <summary>
  68. /// Gets a value indicating whether [save local meta].
  69. /// </summary>
  70. /// <value><c>true</c> if [save local meta]; otherwise, <c>false</c>.</value>
  71. protected virtual bool SaveLocalMeta
  72. {
  73. get { return ConfigurationManager.Configuration.SaveLocalMeta; }
  74. }
  75. /// <summary>
  76. /// Gets a value indicating whether [refresh on version change].
  77. /// </summary>
  78. /// <value><c>true</c> if [refresh on version change]; otherwise, <c>false</c>.</value>
  79. protected override bool RefreshOnVersionChange
  80. {
  81. get
  82. {
  83. return true;
  84. }
  85. }
  86. /// <summary>
  87. /// Gets the provider version.
  88. /// </summary>
  89. /// <value>The provider version.</value>
  90. protected override string ProviderVersion
  91. {
  92. get
  93. {
  94. return "7";
  95. }
  96. }
  97. /// <summary>
  98. /// Needses the refresh internal.
  99. /// </summary>
  100. /// <param name="item">The item.</param>
  101. /// <param name="providerInfo">The provider info.</param>
  102. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  103. protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  104. {
  105. if (string.IsNullOrEmpty(item.GetProviderId(MetadataProviders.Musicbrainz)))
  106. {
  107. return false;
  108. }
  109. if (!ConfigurationManager.Configuration.DownloadMusicArtistImages.Art &&
  110. !ConfigurationManager.Configuration.DownloadMusicArtistImages.Backdrops &&
  111. !ConfigurationManager.Configuration.DownloadMusicArtistImages.Banner &&
  112. !ConfigurationManager.Configuration.DownloadMusicArtistImages.Logo &&
  113. !ConfigurationManager.Configuration.DownloadMusicArtistImages.Primary &&
  114. // The fanart album provider depends on xml downloaded here, so honor it's settings too
  115. !ConfigurationManager.Configuration.DownloadMusicAlbumImages.Disc &&
  116. !ConfigurationManager.Configuration.DownloadMusicAlbumImages.Primary)
  117. {
  118. return false;
  119. }
  120. if (GetComparisonData(item) != providerInfo.Data)
  121. {
  122. return true;
  123. }
  124. return base.NeedsRefreshInternal(item, providerInfo);
  125. }
  126. /// <summary>
  127. /// Gets the comparison data.
  128. /// </summary>
  129. /// <param name="item">The item.</param>
  130. /// <returns>Guid.</returns>
  131. private Guid GetComparisonData(BaseItem item)
  132. {
  133. var musicBrainzId = item.GetProviderId(MetadataProviders.Musicbrainz);
  134. if (!string.IsNullOrEmpty(musicBrainzId))
  135. {
  136. // Process images
  137. var path = GetArtistDataPath(ConfigurationManager.ApplicationPaths, musicBrainzId);
  138. var files = new DirectoryInfo(path)
  139. .EnumerateFiles("*.xml", SearchOption.TopDirectoryOnly)
  140. .Select(i => i.FullName + i.LastWriteTimeUtc.Ticks)
  141. .ToArray();
  142. if (files.Length > 0)
  143. {
  144. return string.Join(string.Empty, files).GetMD5();
  145. }
  146. }
  147. return Guid.Empty;
  148. }
  149. /// <summary>
  150. /// The us culture
  151. /// </summary>
  152. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  153. /// <summary>
  154. /// Gets the series data path.
  155. /// </summary>
  156. /// <param name="appPaths">The app paths.</param>
  157. /// <param name="musicBrainzArtistId">The music brainz artist id.</param>
  158. /// <returns>System.String.</returns>
  159. internal static string GetArtistDataPath(IApplicationPaths appPaths, string musicBrainzArtistId)
  160. {
  161. var seriesDataPath = Path.Combine(GetArtistDataPath(appPaths), musicBrainzArtistId);
  162. if (!Directory.Exists(seriesDataPath))
  163. {
  164. Directory.CreateDirectory(seriesDataPath);
  165. }
  166. return seriesDataPath;
  167. }
  168. /// <summary>
  169. /// Gets the series data path.
  170. /// </summary>
  171. /// <param name="appPaths">The app paths.</param>
  172. /// <returns>System.String.</returns>
  173. internal static string GetArtistDataPath(IApplicationPaths appPaths)
  174. {
  175. var dataPath = Path.Combine(appPaths.DataPath, "fanart-music");
  176. if (!Directory.Exists(dataPath))
  177. {
  178. Directory.CreateDirectory(dataPath);
  179. }
  180. return dataPath;
  181. }
  182. /// <summary>
  183. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  184. /// </summary>
  185. /// <param name="item">The item.</param>
  186. /// <param name="force">if set to <c>true</c> [force].</param>
  187. /// <param name="cancellationToken">The cancellation token.</param>
  188. /// <returns>Task{System.Boolean}.</returns>
  189. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  190. {
  191. cancellationToken.ThrowIfCancellationRequested();
  192. var musicBrainzId = item.GetProviderId(MetadataProviders.Musicbrainz);
  193. var artistDataPath = GetArtistDataPath(ConfigurationManager.ApplicationPaths, musicBrainzId);
  194. var xmlPath = Path.Combine(artistDataPath, "fanart.xml");
  195. // Only download the xml if it doesn't already exist. The prescan task will take care of getting updates
  196. if (!File.Exists(xmlPath))
  197. {
  198. await DownloadArtistXml(artistDataPath, musicBrainzId, cancellationToken).ConfigureAwait(false);
  199. }
  200. if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Art ||
  201. ConfigurationManager.Configuration.DownloadMusicArtistImages.Backdrops ||
  202. ConfigurationManager.Configuration.DownloadMusicArtistImages.Banner ||
  203. ConfigurationManager.Configuration.DownloadMusicArtistImages.Logo ||
  204. ConfigurationManager.Configuration.DownloadMusicArtistImages.Primary)
  205. {
  206. if (File.Exists(xmlPath))
  207. {
  208. await FetchFromXml(item, xmlPath, cancellationToken).ConfigureAwait(false);
  209. }
  210. }
  211. BaseProviderInfo data;
  212. if (!item.ProviderData.TryGetValue(Id, out data))
  213. {
  214. data = new BaseProviderInfo();
  215. item.ProviderData[Id] = data;
  216. }
  217. data.Data = GetComparisonData(item);
  218. SetLastRefreshed(item, DateTime.UtcNow);
  219. return true;
  220. }
  221. /// <summary>
  222. /// Downloads the artist XML.
  223. /// </summary>
  224. /// <param name="artistPath">The artist path.</param>
  225. /// <param name="musicBrainzId">The music brainz id.</param>
  226. /// <param name="cancellationToken">The cancellation token.</param>
  227. /// <returns>Task{System.Boolean}.</returns>
  228. internal async Task DownloadArtistXml(string artistPath, string musicBrainzId, CancellationToken cancellationToken)
  229. {
  230. cancellationToken.ThrowIfCancellationRequested();
  231. var url = string.Format(FanArtBaseUrl, ApiKey, musicBrainzId);
  232. var xmlPath = Path.Combine(artistPath, "fanart.xml");
  233. using (var response = await HttpClient.Get(new HttpRequestOptions
  234. {
  235. Url = url,
  236. ResourcePool = FanArtResourcePool,
  237. CancellationToken = cancellationToken
  238. }).ConfigureAwait(false))
  239. {
  240. using (var xmlFileStream = new FileStream(xmlPath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  241. {
  242. await response.CopyToAsync(xmlFileStream).ConfigureAwait(false);
  243. }
  244. }
  245. }
  246. /// <summary>
  247. /// Fetches from XML.
  248. /// </summary>
  249. /// <param name="item">The item.</param>
  250. /// <param name="xmlFilePath">The XML file path.</param>
  251. /// <param name="cancellationToken">The cancellation token.</param>
  252. /// <returns>Task.</returns>
  253. private async Task FetchFromXml(BaseItem item, string xmlFilePath, CancellationToken cancellationToken)
  254. {
  255. var doc = new XmlDocument();
  256. doc.Load(xmlFilePath);
  257. cancellationToken.ThrowIfCancellationRequested();
  258. string path;
  259. var hd = ConfigurationManager.Configuration.DownloadHDFanArt ? "hd" : "";
  260. if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Logo && !item.HasImage(ImageType.Logo))
  261. {
  262. var node =
  263. doc.SelectSingleNode("//fanart/music/musiclogos/" + hd + "musiclogo/@url") ??
  264. doc.SelectSingleNode("//fanart/music/musiclogos/musiclogo/@url");
  265. path = node != null ? node.Value : null;
  266. if (!string.IsNullOrEmpty(path))
  267. {
  268. item.SetImage(ImageType.Logo, await _providerManager.DownloadAndSaveImage(item, path, LogoFile, SaveLocalMeta, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  269. }
  270. }
  271. cancellationToken.ThrowIfCancellationRequested();
  272. if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Backdrops && item.BackdropImagePaths.Count == 0)
  273. {
  274. var nodes = doc.SelectNodes("//fanart/music/artistbackgrounds//@url");
  275. if (nodes != null)
  276. {
  277. var numBackdrops = 0;
  278. item.BackdropImagePaths = new List<string>();
  279. foreach (XmlNode node in nodes)
  280. {
  281. path = node.Value;
  282. if (!string.IsNullOrEmpty(path))
  283. {
  284. item.BackdropImagePaths.Add(await _providerManager.DownloadAndSaveImage(item, path, ("Backdrop" + (numBackdrops > 0 ? numBackdrops.ToString(UsCulture) : "") + ".jpg"), SaveLocalMeta, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  285. numBackdrops++;
  286. if (numBackdrops >= ConfigurationManager.Configuration.MaxBackdrops) break;
  287. }
  288. }
  289. }
  290. }
  291. cancellationToken.ThrowIfCancellationRequested();
  292. if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Art && !item.HasImage(ImageType.Art))
  293. {
  294. var node =
  295. doc.SelectSingleNode("//fanart/music/musicarts/" + hd + "musicart/@url") ??
  296. doc.SelectSingleNode("//fanart/music/musicarts/musicart/@url");
  297. path = node != null ? node.Value : null;
  298. if (!string.IsNullOrEmpty(path))
  299. {
  300. item.SetImage(ImageType.Art, await _providerManager.DownloadAndSaveImage(item, path, ArtFile, SaveLocalMeta, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  301. }
  302. }
  303. cancellationToken.ThrowIfCancellationRequested();
  304. if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Banner && !item.HasImage(ImageType.Banner))
  305. {
  306. var node = doc.SelectSingleNode("//fanart/music/musicbanners/" + hd + "musicbanner/@url") ??
  307. doc.SelectSingleNode("//fanart/music/musicbanners/musicbanner/@url");
  308. path = node != null ? node.Value : null;
  309. if (!string.IsNullOrEmpty(path))
  310. {
  311. item.SetImage(ImageType.Banner, await _providerManager.DownloadAndSaveImage(item, path, BannerFile, SaveLocalMeta, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  312. }
  313. }
  314. cancellationToken.ThrowIfCancellationRequested();
  315. // Artist thumbs are actually primary images (they are square/portrait)
  316. if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Primary && !item.HasImage(ImageType.Primary))
  317. {
  318. var node = doc.SelectSingleNode("//fanart/music/artistthumbs/artistthumb/@url");
  319. path = node != null ? node.Value : null;
  320. if (!string.IsNullOrEmpty(path))
  321. {
  322. item.SetImage(ImageType.Primary, await _providerManager.DownloadAndSaveImage(item, path, PrimaryFile, SaveLocalMeta, FanArtResourcePool, cancellationToken).ConfigureAwait(false));
  323. }
  324. }
  325. }
  326. }
  327. }