FanartSeriesProvider.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Entities.TV;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Model.Configuration;
  9. using MediaBrowser.Model.Dto;
  10. using MediaBrowser.Model.Entities;
  11. using MediaBrowser.Model.Net;
  12. using MediaBrowser.Model.Providers;
  13. using MediaBrowser.Model.Serialization;
  14. using MediaBrowser.Providers.Music;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Globalization;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Net;
  21. using System.Threading;
  22. using System.Threading.Tasks;
  23. using CommonIO;
  24. namespace MediaBrowser.Providers.TV
  25. {
  26. public class FanartSeriesProvider : IRemoteImageProvider, IHasOrder, IHasChangeMonitor
  27. {
  28. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  29. private readonly IServerConfigurationManager _config;
  30. private readonly IHttpClient _httpClient;
  31. private readonly IFileSystem _fileSystem;
  32. private readonly IJsonSerializer _json;
  33. private const string FanArtBaseUrl = "http://webservice.fanart.tv/v3/tv/{1}?api_key={0}";
  34. // &client_key=52c813aa7b8c8b3bb87f4797532a2f8c
  35. internal static FanartSeriesProvider Current { get; private set; }
  36. public FanartSeriesProvider(IServerConfigurationManager config, IHttpClient httpClient, IFileSystem fileSystem, IJsonSerializer json)
  37. {
  38. _config = config;
  39. _httpClient = httpClient;
  40. _fileSystem = fileSystem;
  41. _json = json;
  42. Current = this;
  43. }
  44. public string Name
  45. {
  46. get { return ProviderName; }
  47. }
  48. public static string ProviderName
  49. {
  50. get { return "FanArt"; }
  51. }
  52. public bool Supports(IHasImages item)
  53. {
  54. return item is Series;
  55. }
  56. public IEnumerable<ImageType> GetSupportedImages(IHasImages item)
  57. {
  58. return new List<ImageType>
  59. {
  60. ImageType.Primary,
  61. ImageType.Thumb,
  62. ImageType.Art,
  63. ImageType.Logo,
  64. ImageType.Backdrop,
  65. ImageType.Banner
  66. };
  67. }
  68. public async Task<IEnumerable<RemoteImageInfo>> GetImages(IHasImages item, CancellationToken cancellationToken)
  69. {
  70. var list = new List<RemoteImageInfo>();
  71. var series = (Series)item;
  72. var id = series.GetProviderId(MetadataProviders.Tvdb);
  73. if (!string.IsNullOrEmpty(id))
  74. {
  75. // Bad id entered
  76. try
  77. {
  78. await EnsureSeriesJson(id, cancellationToken).ConfigureAwait(false);
  79. }
  80. catch (HttpException ex)
  81. {
  82. if (!ex.StatusCode.HasValue || ex.StatusCode.Value != HttpStatusCode.NotFound)
  83. {
  84. throw;
  85. }
  86. }
  87. var path = GetFanartJsonPath(id);
  88. try
  89. {
  90. AddImages(list, path, cancellationToken);
  91. }
  92. catch (FileNotFoundException)
  93. {
  94. // No biggie. Don't blow up
  95. }
  96. catch (DirectoryNotFoundException)
  97. {
  98. // No biggie. Don't blow up
  99. }
  100. }
  101. var language = item.GetPreferredMetadataLanguage();
  102. var isLanguageEn = string.Equals(language, "en", StringComparison.OrdinalIgnoreCase);
  103. // Sort first by width to prioritize HD versions
  104. return list.OrderByDescending(i => i.Width ?? 0)
  105. .ThenByDescending(i =>
  106. {
  107. if (string.Equals(language, i.Language, StringComparison.OrdinalIgnoreCase))
  108. {
  109. return 3;
  110. }
  111. if (!isLanguageEn)
  112. {
  113. if (string.Equals("en", i.Language, StringComparison.OrdinalIgnoreCase))
  114. {
  115. return 2;
  116. }
  117. }
  118. if (string.IsNullOrEmpty(i.Language))
  119. {
  120. return isLanguageEn ? 3 : 2;
  121. }
  122. return 0;
  123. })
  124. .ThenByDescending(i => i.CommunityRating ?? 0)
  125. .ThenByDescending(i => i.VoteCount ?? 0);
  126. }
  127. private void AddImages(List<RemoteImageInfo> list, string path, CancellationToken cancellationToken)
  128. {
  129. var root = _json.DeserializeFromFile<RootObject>(path);
  130. AddImages(list, root, cancellationToken);
  131. }
  132. private void AddImages(List<RemoteImageInfo> list, RootObject obj, CancellationToken cancellationToken)
  133. {
  134. PopulateImages(list, obj.hdtvlogo, ImageType.Logo, 800, 310);
  135. PopulateImages(list, obj.hdclearart, ImageType.Art, 1000, 562);
  136. PopulateImages(list, obj.clearlogo, ImageType.Logo, 400, 155);
  137. PopulateImages(list, obj.clearart, ImageType.Art, 500, 281);
  138. PopulateImages(list, obj.showbackground, ImageType.Backdrop, 1920, 1080, true);
  139. PopulateImages(list, obj.seasonthumb, ImageType.Thumb, 500, 281);
  140. PopulateImages(list, obj.tvthumb, ImageType.Thumb, 500, 281);
  141. PopulateImages(list, obj.tvbanner, ImageType.Banner, 1000, 185);
  142. PopulateImages(list, obj.tvposter, ImageType.Primary, 1000, 1426);
  143. }
  144. private void PopulateImages(List<RemoteImageInfo> list,
  145. List<Image> images,
  146. ImageType type,
  147. int width,
  148. int height,
  149. bool allowSeasonAll = false)
  150. {
  151. if (images == null)
  152. {
  153. return;
  154. }
  155. list.AddRange(images.Select(i =>
  156. {
  157. var url = i.url;
  158. var season = i.season;
  159. var isSeasonValid = string.IsNullOrEmpty(season) ||
  160. (allowSeasonAll && string.Equals(season, "all", StringComparison.OrdinalIgnoreCase));
  161. if (!string.IsNullOrEmpty(url) && isSeasonValid)
  162. {
  163. var likesString = i.likes;
  164. int likes;
  165. var info = new RemoteImageInfo
  166. {
  167. RatingType = RatingType.Likes,
  168. Type = type,
  169. Width = width,
  170. Height = height,
  171. ProviderName = Name,
  172. Url = url,
  173. Language = i.lang
  174. };
  175. if (!string.IsNullOrEmpty(likesString) && int.TryParse(likesString, NumberStyles.Any, _usCulture, out likes))
  176. {
  177. info.CommunityRating = likes;
  178. }
  179. return info;
  180. }
  181. return null;
  182. }).Where(i => i != null));
  183. }
  184. public int Order
  185. {
  186. get { return 1; }
  187. }
  188. public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
  189. {
  190. return _httpClient.GetResponse(new HttpRequestOptions
  191. {
  192. CancellationToken = cancellationToken,
  193. Url = url,
  194. ResourcePool = FanartArtistProvider.Current.FanArtResourcePool
  195. });
  196. }
  197. /// <summary>
  198. /// Gets the series data path.
  199. /// </summary>
  200. /// <param name="appPaths">The app paths.</param>
  201. /// <param name="seriesId">The series id.</param>
  202. /// <returns>System.String.</returns>
  203. internal static string GetSeriesDataPath(IApplicationPaths appPaths, string seriesId)
  204. {
  205. var seriesDataPath = Path.Combine(GetSeriesDataPath(appPaths), seriesId);
  206. return seriesDataPath;
  207. }
  208. /// <summary>
  209. /// Gets the series data path.
  210. /// </summary>
  211. /// <param name="appPaths">The app paths.</param>
  212. /// <returns>System.String.</returns>
  213. internal static string GetSeriesDataPath(IApplicationPaths appPaths)
  214. {
  215. var dataPath = Path.Combine(appPaths.CachePath, "fanart-tv");
  216. return dataPath;
  217. }
  218. public string GetFanartJsonPath(string tvdbId)
  219. {
  220. var dataPath = GetSeriesDataPath(_config.ApplicationPaths, tvdbId);
  221. return Path.Combine(dataPath, "fanart.json");
  222. }
  223. private readonly SemaphoreSlim _ensureSemaphore = new SemaphoreSlim(1, 1);
  224. internal async Task EnsureSeriesJson(string tvdbId, CancellationToken cancellationToken)
  225. {
  226. var path = GetFanartJsonPath(tvdbId);
  227. // Only allow one thread in here at a time since every season will be calling this method, possibly concurrently
  228. await _ensureSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  229. try
  230. {
  231. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  232. if (fileInfo.Exists)
  233. {
  234. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
  235. {
  236. return;
  237. }
  238. }
  239. await DownloadSeriesJson(tvdbId, cancellationToken).ConfigureAwait(false);
  240. }
  241. finally
  242. {
  243. _ensureSemaphore.Release();
  244. }
  245. }
  246. public FanartOptions GetFanartOptions()
  247. {
  248. return _config.GetConfiguration<FanartOptions>("fanart");
  249. }
  250. /// <summary>
  251. /// Downloads the series json.
  252. /// </summary>
  253. /// <param name="tvdbId">The TVDB identifier.</param>
  254. /// <param name="cancellationToken">The cancellation token.</param>
  255. /// <returns>Task.</returns>
  256. internal async Task DownloadSeriesJson(string tvdbId, CancellationToken cancellationToken)
  257. {
  258. cancellationToken.ThrowIfCancellationRequested();
  259. var url = string.Format(FanArtBaseUrl, FanartArtistProvider.ApiKey, tvdbId);
  260. var clientKey = GetFanartOptions().UserApiKey;
  261. if (!string.IsNullOrWhiteSpace(clientKey))
  262. {
  263. url += "&client_key=" + clientKey;
  264. }
  265. var path = GetFanartJsonPath(tvdbId);
  266. _fileSystem.CreateDirectory(Path.GetDirectoryName(path));
  267. try
  268. {
  269. using (var response = await _httpClient.Get(new HttpRequestOptions
  270. {
  271. Url = url,
  272. ResourcePool = FanartArtistProvider.Current.FanArtResourcePool,
  273. CancellationToken = cancellationToken
  274. }).ConfigureAwait(false))
  275. {
  276. using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  277. {
  278. await response.CopyToAsync(fileStream).ConfigureAwait(false);
  279. }
  280. }
  281. }
  282. catch (HttpException exception)
  283. {
  284. if (exception.StatusCode.HasValue && exception.StatusCode.Value == HttpStatusCode.NotFound)
  285. {
  286. // If the user has automatic updates enabled, save a dummy object to prevent repeated download attempts
  287. _json.SerializeToFile(new RootObject(), path);
  288. return;
  289. }
  290. throw;
  291. }
  292. }
  293. public bool HasChanged(IHasMetadata item, IDirectoryService directoryService, DateTime date)
  294. {
  295. var options = GetFanartOptions();
  296. if (!options.EnableAutomaticUpdates)
  297. {
  298. return false;
  299. }
  300. var tvdbId = item.GetProviderId(MetadataProviders.Tvdb);
  301. if (!String.IsNullOrEmpty(tvdbId))
  302. {
  303. // Process images
  304. var imagesFilePath = GetFanartJsonPath(tvdbId);
  305. var fileInfo = _fileSystem.GetFileInfo(imagesFilePath);
  306. return !fileInfo.Exists || _fileSystem.GetLastWriteTimeUtc(fileInfo) > date;
  307. }
  308. return false;
  309. }
  310. public class Image
  311. {
  312. public string id { get; set; }
  313. public string url { get; set; }
  314. public string lang { get; set; }
  315. public string likes { get; set; }
  316. public string season { get; set; }
  317. }
  318. public class RootObject
  319. {
  320. public string name { get; set; }
  321. public string thetvdb_id { get; set; }
  322. public List<Image> clearlogo { get; set; }
  323. public List<Image> hdtvlogo { get; set; }
  324. public List<Image> clearart { get; set; }
  325. public List<Image> showbackground { get; set; }
  326. public List<Image> tvthumb { get; set; }
  327. public List<Image> seasonposter { get; set; }
  328. public List<Image> seasonthumb { get; set; }
  329. public List<Image> hdclearart { get; set; }
  330. public List<Image> tvbanner { get; set; }
  331. public List<Image> characterart { get; set; }
  332. public List<Image> tvposter { get; set; }
  333. public List<Image> seasonbanner { get; set; }
  334. }
  335. }
  336. public class FanartConfigStore : IConfigurationFactory
  337. {
  338. public IEnumerable<ConfigurationStore> GetConfigurations()
  339. {
  340. return new List<ConfigurationStore>
  341. {
  342. new ConfigurationStore
  343. {
  344. Key = "fanart",
  345. ConfigurationType = typeof(FanartOptions)
  346. }
  347. };
  348. }
  349. }
  350. }