FanArtArtistProvider.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  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. var files = new DirectoryInfo(path)
  148. .EnumerateFiles("*.xml", SearchOption.TopDirectoryOnly)
  149. .Select(i => i.LastWriteTimeUtc)
  150. .ToArray();
  151. if (files.Length > 0)
  152. {
  153. return files.Max();
  154. }
  155. }
  156. return base.CompareDate(item);
  157. }
  158. /// <summary>
  159. /// The us culture
  160. /// </summary>
  161. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  162. /// <summary>
  163. /// Gets the series data path.
  164. /// </summary>
  165. /// <param name="appPaths">The app paths.</param>
  166. /// <param name="musicBrainzArtistId">The music brainz artist id.</param>
  167. /// <returns>System.String.</returns>
  168. internal static string GetArtistDataPath(IApplicationPaths appPaths, string musicBrainzArtistId)
  169. {
  170. var seriesDataPath = Path.Combine(GetArtistDataPath(appPaths), musicBrainzArtistId);
  171. if (!Directory.Exists(seriesDataPath))
  172. {
  173. Directory.CreateDirectory(seriesDataPath);
  174. }
  175. return seriesDataPath;
  176. }
  177. /// <summary>
  178. /// Gets the series data path.
  179. /// </summary>
  180. /// <param name="appPaths">The app paths.</param>
  181. /// <returns>System.String.</returns>
  182. internal static string GetArtistDataPath(IApplicationPaths appPaths)
  183. {
  184. var dataPath = Path.Combine(appPaths.DataPath, "fanart-music");
  185. if (!Directory.Exists(dataPath))
  186. {
  187. Directory.CreateDirectory(dataPath);
  188. }
  189. return dataPath;
  190. }
  191. /// <summary>
  192. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  193. /// </summary>
  194. /// <param name="item">The item.</param>
  195. /// <param name="force">if set to <c>true</c> [force].</param>
  196. /// <param name="cancellationToken">The cancellation token.</param>
  197. /// <returns>Task{System.Boolean}.</returns>
  198. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  199. {
  200. cancellationToken.ThrowIfCancellationRequested();
  201. var musicBrainzId = item.GetProviderId(MetadataProviders.Musicbrainz);
  202. var artistDataPath = GetArtistDataPath(ConfigurationManager.ApplicationPaths, musicBrainzId);
  203. var xmlPath = Path.Combine(artistDataPath, "fanart.xml");
  204. // Only download the xml if it doesn't already exist. The prescan task will take care of getting updates
  205. if (!File.Exists(xmlPath))
  206. {
  207. await DownloadArtistXml(artistDataPath, musicBrainzId, cancellationToken).ConfigureAwait(false);
  208. }
  209. if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Art ||
  210. ConfigurationManager.Configuration.DownloadMusicArtistImages.Backdrops ||
  211. ConfigurationManager.Configuration.DownloadMusicArtistImages.Banner ||
  212. ConfigurationManager.Configuration.DownloadMusicArtistImages.Logo ||
  213. ConfigurationManager.Configuration.DownloadMusicArtistImages.Primary)
  214. {
  215. if (File.Exists(xmlPath))
  216. {
  217. await FetchFromXml(item, xmlPath, cancellationToken).ConfigureAwait(false);
  218. }
  219. }
  220. BaseProviderInfo data;
  221. if (!item.ProviderData.TryGetValue(Id, out data))
  222. {
  223. data = new BaseProviderInfo();
  224. item.ProviderData[Id] = data;
  225. }
  226. SetLastRefreshed(item, DateTime.UtcNow);
  227. return true;
  228. }
  229. /// <summary>
  230. /// Downloads the artist XML.
  231. /// </summary>
  232. /// <param name="artistPath">The artist path.</param>
  233. /// <param name="musicBrainzId">The music brainz id.</param>
  234. /// <param name="cancellationToken">The cancellation token.</param>
  235. /// <returns>Task{System.Boolean}.</returns>
  236. internal async Task DownloadArtistXml(string artistPath, string musicBrainzId, CancellationToken cancellationToken)
  237. {
  238. cancellationToken.ThrowIfCancellationRequested();
  239. var url = string.Format(FanArtBaseUrl, ApiKey, musicBrainzId);
  240. var xmlPath = Path.Combine(artistPath, "fanart.xml");
  241. using (var response = await HttpClient.Get(new HttpRequestOptions
  242. {
  243. Url = url,
  244. ResourcePool = FanArtResourcePool,
  245. CancellationToken = cancellationToken
  246. }).ConfigureAwait(false))
  247. {
  248. using (var xmlFileStream = new FileStream(xmlPath, FileMode.Create, FileAccess.Write, FileShare.Read, StreamDefaults.DefaultFileStreamBufferSize, FileOptions.Asynchronous))
  249. {
  250. await response.CopyToAsync(xmlFileStream).ConfigureAwait(false);
  251. }
  252. }
  253. }
  254. /// <summary>
  255. /// Fetches from XML.
  256. /// </summary>
  257. /// <param name="item">The item.</param>
  258. /// <param name="xmlFilePath">The XML file path.</param>
  259. /// <param name="cancellationToken">The cancellation token.</param>
  260. /// <returns>Task.</returns>
  261. private async Task FetchFromXml(BaseItem item, string xmlFilePath, CancellationToken cancellationToken)
  262. {
  263. var doc = new XmlDocument();
  264. doc.Load(xmlFilePath);
  265. cancellationToken.ThrowIfCancellationRequested();
  266. string path;
  267. var hd = ConfigurationManager.Configuration.DownloadHDFanArt ? "hd" : "";
  268. if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Logo && !item.HasImage(ImageType.Logo))
  269. {
  270. var node =
  271. doc.SelectSingleNode("//fanart/music/musiclogos/" + hd + "musiclogo/@url") ??
  272. doc.SelectSingleNode("//fanart/music/musiclogos/musiclogo/@url");
  273. path = node != null ? node.Value : null;
  274. if (!string.IsNullOrEmpty(path))
  275. {
  276. try
  277. {
  278. await _providerManager.SaveImage(item, path, FanArtResourcePool, ImageType.Logo, null, cancellationToken)
  279. .ConfigureAwait(false);
  280. }
  281. catch (HttpException ex)
  282. {
  283. // Sometimes fanart has bad url's in their xml. Nothing we can do here but catch it
  284. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
  285. {
  286. throw;
  287. }
  288. }
  289. }
  290. }
  291. cancellationToken.ThrowIfCancellationRequested();
  292. if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Backdrops && item.BackdropImagePaths.Count == 0)
  293. {
  294. var nodes = doc.SelectNodes("//fanart/music/artistbackgrounds//@url");
  295. if (nodes != null)
  296. {
  297. var numBackdrops = 0;
  298. item.BackdropImagePaths = new List<string>();
  299. foreach (XmlNode node in nodes)
  300. {
  301. path = node.Value;
  302. if (!string.IsNullOrEmpty(path))
  303. {
  304. try
  305. {
  306. await _providerManager.SaveImage(item, path, FanArtResourcePool, ImageType.Backdrop, numBackdrops, cancellationToken)
  307. .ConfigureAwait(false);
  308. numBackdrops++;
  309. if (numBackdrops >= ConfigurationManager.Configuration.MaxBackdrops) break;
  310. }
  311. catch (HttpException ex)
  312. {
  313. // Sometimes fanart has bad url's in their xml. Nothing we can do here but catch it
  314. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
  315. {
  316. throw;
  317. }
  318. }
  319. }
  320. }
  321. }
  322. }
  323. cancellationToken.ThrowIfCancellationRequested();
  324. if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Art && !item.HasImage(ImageType.Art))
  325. {
  326. var node =
  327. doc.SelectSingleNode("//fanart/music/musicarts/" + hd + "musicart/@url") ??
  328. doc.SelectSingleNode("//fanart/music/musicarts/musicart/@url");
  329. path = node != null ? node.Value : null;
  330. if (!string.IsNullOrEmpty(path))
  331. {
  332. try
  333. {
  334. await _providerManager.SaveImage(item, path, FanArtResourcePool, ImageType.Art, null, cancellationToken)
  335. .ConfigureAwait(false);
  336. }
  337. catch (HttpException ex)
  338. {
  339. // Sometimes fanart has bad url's in their xml. Nothing we can do here but catch it
  340. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
  341. {
  342. throw;
  343. }
  344. }
  345. }
  346. }
  347. cancellationToken.ThrowIfCancellationRequested();
  348. if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Banner && !item.HasImage(ImageType.Banner))
  349. {
  350. var node = doc.SelectSingleNode("//fanart/music/musicbanners/" + hd + "musicbanner/@url") ??
  351. doc.SelectSingleNode("//fanart/music/musicbanners/musicbanner/@url");
  352. path = node != null ? node.Value : null;
  353. if (!string.IsNullOrEmpty(path))
  354. {
  355. try
  356. {
  357. await _providerManager.SaveImage(item, path, FanArtResourcePool, ImageType.Banner, null, cancellationToken)
  358. .ConfigureAwait(false);
  359. }
  360. catch (HttpException ex)
  361. {
  362. // Sometimes fanart has bad url's in their xml. Nothing we can do here but catch it
  363. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
  364. {
  365. throw;
  366. }
  367. }
  368. }
  369. }
  370. cancellationToken.ThrowIfCancellationRequested();
  371. // Artist thumbs are actually primary images (they are square/portrait)
  372. if (ConfigurationManager.Configuration.DownloadMusicArtistImages.Primary && !item.HasImage(ImageType.Primary))
  373. {
  374. var node = doc.SelectSingleNode("//fanart/music/artistthumbs/artistthumb/@url");
  375. path = node != null ? node.Value : null;
  376. if (!string.IsNullOrEmpty(path))
  377. {
  378. try
  379. {
  380. await _providerManager.SaveImage(item, path, FanArtResourcePool, ImageType.Primary, null, cancellationToken)
  381. .ConfigureAwait(false);
  382. }
  383. catch (HttpException ex)
  384. {
  385. // Sometimes fanart has bad url's in their xml. Nothing we can do here but catch it
  386. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
  387. {
  388. throw;
  389. }
  390. }
  391. }
  392. }
  393. }
  394. }
  395. }