FanartSeriesProvider.cs 13 KB

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