FanArtArtistProvider.cs 17 KB

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