TvDbClientManager.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Controller.Providers;
  8. using MediaBrowser.Model.Entities;
  9. using Microsoft.Extensions.Caching.Memory;
  10. using TvDbSharper;
  11. using TvDbSharper.Dto;
  12. namespace MediaBrowser.Providers.TV.TheTVDB
  13. {
  14. public class TvDbClientManager
  15. {
  16. private readonly SemaphoreSlim _cacheWriteLock = new SemaphoreSlim(1, 1);
  17. private readonly IMemoryCache _cache;
  18. private readonly TvDbClient _tvDbClient;
  19. private DateTime _tokenCreatedAt;
  20. private const string DefaultLanguage = "en";
  21. public TvDbClientManager(IMemoryCache memoryCache)
  22. {
  23. _cache = memoryCache;
  24. _tvDbClient = new TvDbClient();
  25. _tvDbClient.Authentication.AuthenticateAsync(TvdbUtils.TvdbApiKey);
  26. _tokenCreatedAt = DateTime.Now;
  27. }
  28. public TvDbClient TvDbClient
  29. {
  30. get
  31. {
  32. // Refresh if necessary
  33. if (_tokenCreatedAt > DateTime.Now.Subtract(TimeSpan.FromHours(20)))
  34. {
  35. try
  36. {
  37. _tvDbClient.Authentication.RefreshTokenAsync();
  38. }
  39. catch
  40. {
  41. _tvDbClient.Authentication.AuthenticateAsync(TvdbUtils.TvdbApiKey);
  42. }
  43. _tokenCreatedAt = DateTime.Now;
  44. }
  45. return _tvDbClient;
  46. }
  47. }
  48. public Task<TvDbResponse<SeriesSearchResult[]>> GetSeriesByNameAsync(string name, string language,
  49. CancellationToken cancellationToken)
  50. {
  51. var cacheKey = GenerateKey("series", name, language);
  52. return TryGetValue(cacheKey, language,() => TvDbClient.Search.SearchSeriesByNameAsync(name, cancellationToken));
  53. }
  54. public Task<TvDbResponse<Series>> GetSeriesByIdAsync(int tvdbId, string language,
  55. CancellationToken cancellationToken)
  56. {
  57. var cacheKey = GenerateKey("series", tvdbId, language);
  58. return TryGetValue(cacheKey, language,() => TvDbClient.Series.GetAsync(tvdbId, cancellationToken));
  59. }
  60. public Task<TvDbResponse<EpisodeRecord>> GetEpisodesAsync(int episodeTvdbId, string language,
  61. CancellationToken cancellationToken)
  62. {
  63. var cacheKey = GenerateKey("episode", episodeTvdbId, language);
  64. return TryGetValue(cacheKey, language,() => TvDbClient.Episodes.GetAsync(episodeTvdbId, cancellationToken));
  65. }
  66. public async Task<List<EpisodeRecord>> GetAllEpisodesAsync(int tvdbId, string language,
  67. CancellationToken cancellationToken)
  68. {
  69. // Traverse all episode pages and join them together
  70. var episodes = new List<EpisodeRecord>();
  71. var episodePage = await GetEpisodesPageAsync(tvdbId, new EpisodeQuery(), language, cancellationToken)
  72. .ConfigureAwait(false);
  73. episodes.AddRange(episodePage.Data);
  74. if (!episodePage.Links.Next.HasValue || !episodePage.Links.Last.HasValue)
  75. {
  76. return episodes;
  77. }
  78. int next = episodePage.Links.Next.Value;
  79. int last = episodePage.Links.Last.Value;
  80. for (var page = next; page <= last; ++page)
  81. {
  82. episodePage = await GetEpisodesPageAsync(tvdbId, page, new EpisodeQuery(), language, cancellationToken)
  83. .ConfigureAwait(false);
  84. episodes.AddRange(episodePage.Data);
  85. }
  86. return episodes;
  87. }
  88. public Task<TvDbResponse<SeriesSearchResult[]>> GetSeriesByImdbIdAsync(string imdbId, string language,
  89. CancellationToken cancellationToken)
  90. {
  91. var cacheKey = GenerateKey("series", imdbId, language);
  92. return TryGetValue(cacheKey, language,() => TvDbClient.Search.SearchSeriesByImdbIdAsync(imdbId, cancellationToken));
  93. }
  94. public Task<TvDbResponse<SeriesSearchResult[]>> GetSeriesByZap2ItIdAsync(string zap2ItId, string language,
  95. CancellationToken cancellationToken)
  96. {
  97. var cacheKey = GenerateKey("series", zap2ItId, language);
  98. return TryGetValue( cacheKey, language,() => TvDbClient.Search.SearchSeriesByZap2ItIdAsync(zap2ItId, cancellationToken));
  99. }
  100. public Task<TvDbResponse<Actor[]>> GetActorsAsync(int tvdbId, string language,
  101. CancellationToken cancellationToken)
  102. {
  103. var cacheKey = GenerateKey("actors", tvdbId, language);
  104. return TryGetValue(cacheKey, language,() => TvDbClient.Series.GetActorsAsync(tvdbId, cancellationToken));
  105. }
  106. public Task<TvDbResponse<Image[]>> GetImagesAsync(int tvdbId, ImagesQuery imageQuery, string language,
  107. CancellationToken cancellationToken)
  108. {
  109. var cacheKey = GenerateKey("images", tvdbId, language, imageQuery);
  110. return TryGetValue(cacheKey, language,() => TvDbClient.Series.GetImagesAsync(tvdbId, imageQuery, cancellationToken));
  111. }
  112. public Task<TvDbResponse<Language[]>> GetLanguagesAsync(CancellationToken cancellationToken)
  113. {
  114. return TryGetValue("languages", null,() => TvDbClient.Languages.GetAllAsync(cancellationToken));
  115. }
  116. public Task<TvDbResponse<EpisodesSummary>> GetSeriesEpisodeSummaryAsync(int tvdbId, string language,
  117. CancellationToken cancellationToken)
  118. {
  119. var cacheKey = GenerateKey("seriesepisodesummary", tvdbId, language);
  120. return TryGetValue(cacheKey, language,
  121. () => TvDbClient.Series.GetEpisodesSummaryAsync(tvdbId, cancellationToken));
  122. }
  123. public Task<TvDbResponse<EpisodeRecord[]>> GetEpisodesPageAsync(int tvdbId, int page, EpisodeQuery episodeQuery,
  124. string language, CancellationToken cancellationToken)
  125. {
  126. var cacheKey = GenerateKey(language, tvdbId, episodeQuery);
  127. return TryGetValue(cacheKey, language,
  128. () => TvDbClient.Series.GetEpisodesAsync(tvdbId, page, episodeQuery, cancellationToken));
  129. }
  130. public Task<string> GetEpisodeTvdbId(EpisodeInfo searchInfo, string language,
  131. CancellationToken cancellationToken)
  132. {
  133. searchInfo.SeriesProviderIds.TryGetValue(MetadataProviders.Tvdb.ToString(),
  134. out var seriesTvdbId);
  135. var episodeQuery = new EpisodeQuery();
  136. // Prefer SxE over premiere date as it is more robust
  137. if (searchInfo.IndexNumber.HasValue && searchInfo.ParentIndexNumber.HasValue)
  138. {
  139. episodeQuery.AiredEpisode = searchInfo.IndexNumber.Value;
  140. episodeQuery.AiredSeason = searchInfo.ParentIndexNumber.Value;
  141. }
  142. else if (searchInfo.PremiereDate.HasValue)
  143. {
  144. // tvdb expects yyyy-mm-dd format
  145. episodeQuery.FirstAired = searchInfo.PremiereDate.Value.ToString("yyyy-MM-dd");
  146. }
  147. return GetEpisodeTvdbId(Convert.ToInt32(seriesTvdbId), episodeQuery, language, cancellationToken);
  148. }
  149. public async Task<string> GetEpisodeTvdbId(int seriesTvdbId, EpisodeQuery episodeQuery,
  150. string language,
  151. CancellationToken cancellationToken)
  152. {
  153. var episodePage =
  154. await GetEpisodesPageAsync(Convert.ToInt32(seriesTvdbId), episodeQuery, language, cancellationToken)
  155. .ConfigureAwait(false);
  156. return episodePage.Data.FirstOrDefault()?.Id.ToString();
  157. }
  158. public Task<TvDbResponse<EpisodeRecord[]>> GetEpisodesPageAsync(int tvdbId, EpisodeQuery episodeQuery,
  159. string language, CancellationToken cancellationToken)
  160. {
  161. return GetEpisodesPageAsync(tvdbId, 1, episodeQuery, language, cancellationToken);
  162. }
  163. private async Task<T> TryGetValue<T>(string key, string language, Func<Task<T>> resultFactory)
  164. {
  165. if (_cache.TryGetValue(key, out T cachedValue))
  166. {
  167. return cachedValue;
  168. }
  169. await _cacheWriteLock.WaitAsync().ConfigureAwait(false);
  170. try
  171. {
  172. if (_cache.TryGetValue(key, out cachedValue))
  173. {
  174. return cachedValue;
  175. }
  176. _tvDbClient.AcceptedLanguage = TvdbUtils.NormalizeLanguage(language) ?? DefaultLanguage;
  177. var result = await resultFactory.Invoke().ConfigureAwait(false);
  178. _cache.Set(key, result, TimeSpan.FromHours(1));
  179. return result;
  180. }
  181. finally
  182. {
  183. _cacheWriteLock.Release();
  184. }
  185. }
  186. private static string GenerateKey(params object[] objects)
  187. {
  188. var key = string.Empty;
  189. foreach (var obj in objects)
  190. {
  191. var objType = obj.GetType();
  192. if (objType.IsPrimitive || objType == typeof(string))
  193. {
  194. key += obj + ";";
  195. }
  196. else
  197. {
  198. foreach (PropertyInfo propertyInfo in objType.GetProperties())
  199. {
  200. var currentValue = propertyInfo.GetValue(obj, null);
  201. if (currentValue == null)
  202. {
  203. continue;
  204. }
  205. key += propertyInfo.Name + "=" + currentValue + ";";
  206. }
  207. }
  208. }
  209. return key;
  210. }
  211. }
  212. }