FanartSeriesProvider.cs 14 KB

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