FanartSeriesProvider.cs 13 KB

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