TvDbClientManager.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. episodes.AddRange(episodePage.Data);
  73. if (!episodePage.Links.Next.HasValue || !episodePage.Links.Last.HasValue)
  74. {
  75. return episodes;
  76. }
  77. int next = episodePage.Links.Next.Value;
  78. int last = episodePage.Links.Last.Value;
  79. for (var page = next; page <= last; ++page)
  80. {
  81. episodePage = await GetEpisodesPageAsync(tvdbId, page, new EpisodeQuery(), language, cancellationToken);
  82. episodes.AddRange(episodePage.Data);
  83. }
  84. return episodes;
  85. }
  86. public Task<TvDbResponse<SeriesSearchResult[]>> GetSeriesByImdbIdAsync(string imdbId, string language,
  87. CancellationToken cancellationToken)
  88. {
  89. var cacheKey = GenerateKey("series", imdbId, language);
  90. return TryGetValue(cacheKey, language,() => TvDbClient.Search.SearchSeriesByImdbIdAsync(imdbId, cancellationToken));
  91. }
  92. public Task<TvDbResponse<SeriesSearchResult[]>> GetSeriesByZap2ItIdAsync(string zap2ItId, string language,
  93. CancellationToken cancellationToken)
  94. {
  95. var cacheKey = GenerateKey("series", zap2ItId, language);
  96. return TryGetValue( cacheKey, language,() => TvDbClient.Search.SearchSeriesByZap2ItIdAsync(zap2ItId, cancellationToken));
  97. }
  98. public Task<TvDbResponse<Actor[]>> GetActorsAsync(int tvdbId, string language,
  99. CancellationToken cancellationToken)
  100. {
  101. var cacheKey = GenerateKey("actors", tvdbId, language);
  102. return TryGetValue(cacheKey, language,() => TvDbClient.Series.GetActorsAsync(tvdbId, cancellationToken));
  103. }
  104. public Task<TvDbResponse<Image[]>> GetImagesAsync(int tvdbId, ImagesQuery imageQuery, string language,
  105. CancellationToken cancellationToken)
  106. {
  107. var cacheKey = GenerateKey("images", tvdbId, language, imageQuery);
  108. return TryGetValue(cacheKey, language,() => TvDbClient.Series.GetImagesAsync(tvdbId, imageQuery, cancellationToken));
  109. }
  110. public Task<TvDbResponse<Language[]>> GetLanguagesAsync(CancellationToken cancellationToken)
  111. {
  112. return TryGetValue("languages", null,() => TvDbClient.Languages.GetAllAsync(cancellationToken));
  113. }
  114. public Task<TvDbResponse<EpisodesSummary>> GetSeriesEpisodeSummaryAsync(int tvdbId, string language,
  115. CancellationToken cancellationToken)
  116. {
  117. var cacheKey = GenerateKey("seriesepisodesummary", tvdbId, language);
  118. return TryGetValue(cacheKey, language,
  119. () => TvDbClient.Series.GetEpisodesSummaryAsync(tvdbId, cancellationToken));
  120. }
  121. public Task<TvDbResponse<EpisodeRecord[]>> GetEpisodesPageAsync(int tvdbId, int page, EpisodeQuery episodeQuery,
  122. string language, CancellationToken cancellationToken)
  123. {
  124. var cacheKey = GenerateKey(language, tvdbId, episodeQuery);
  125. return TryGetValue(cacheKey, language,
  126. () => TvDbClient.Series.GetEpisodesAsync(tvdbId, page, episodeQuery, cancellationToken));
  127. }
  128. public Task<string> GetEpisodeTvdbId(EpisodeInfo searchInfo, string language,
  129. CancellationToken cancellationToken)
  130. {
  131. searchInfo.SeriesProviderIds.TryGetValue(MetadataProviders.Tvdb.ToString(),
  132. out var seriesTvdbId);
  133. var episodeQuery = new EpisodeQuery();
  134. // Prefer SxE over premiere date as it is more robust
  135. if (searchInfo.IndexNumber.HasValue && searchInfo.ParentIndexNumber.HasValue)
  136. {
  137. episodeQuery.AiredEpisode = searchInfo.IndexNumber.Value;
  138. episodeQuery.AiredSeason = searchInfo.ParentIndexNumber.Value;
  139. }
  140. else if (searchInfo.PremiereDate.HasValue)
  141. {
  142. // tvdb expects yyyy-mm-dd format
  143. episodeQuery.FirstAired = searchInfo.PremiereDate.Value.ToString("yyyy-MM-dd");
  144. }
  145. return GetEpisodeTvdbId(Convert.ToInt32(seriesTvdbId), episodeQuery, language, cancellationToken);
  146. }
  147. public async Task<string> GetEpisodeTvdbId(int seriesTvdbId, EpisodeQuery episodeQuery,
  148. string language,
  149. CancellationToken cancellationToken)
  150. {
  151. var episodePage = await GetEpisodesPageAsync(Convert.ToInt32(seriesTvdbId), episodeQuery, language, cancellationToken);
  152. return episodePage.Data.FirstOrDefault()?.Id.ToString();
  153. }
  154. public Task<TvDbResponse<EpisodeRecord[]>> GetEpisodesPageAsync(int tvdbId, EpisodeQuery episodeQuery,
  155. string language, CancellationToken cancellationToken)
  156. {
  157. return GetEpisodesPageAsync(tvdbId, 1, episodeQuery, language, cancellationToken);
  158. }
  159. private async Task<T> TryGetValue<T>(string key, string language, Func<Task<T>> resultFactory)
  160. {
  161. if (_cache.TryGetValue(key, out T cachedValue))
  162. {
  163. return cachedValue;
  164. }
  165. await _cacheWriteLock.WaitAsync().ConfigureAwait(false);
  166. try
  167. {
  168. if (_cache.TryGetValue(key, out cachedValue))
  169. {
  170. return cachedValue;
  171. }
  172. _tvDbClient.AcceptedLanguage = TvdbUtils.NormalizeLanguage(language) ?? DefaultLanguage;
  173. var result = await resultFactory.Invoke();
  174. _cache.Set(key, result, TimeSpan.FromHours(1));
  175. return result;
  176. }
  177. finally
  178. {
  179. _cacheWriteLock.Release();
  180. }
  181. }
  182. private static string GenerateKey(params object[] objects)
  183. {
  184. var key = string.Empty;
  185. foreach (var obj in objects)
  186. {
  187. var objType = obj.GetType();
  188. if (objType.IsPrimitive || objType == typeof(string))
  189. {
  190. key += obj + ";";
  191. }
  192. else
  193. {
  194. foreach (PropertyInfo propertyInfo in objType.GetProperties())
  195. {
  196. var currentValue = propertyInfo.GetValue(obj, null);
  197. if (currentValue == null)
  198. {
  199. continue;
  200. }
  201. key += propertyInfo.Name + "=" + currentValue + ";";
  202. }
  203. }
  204. }
  205. return key;
  206. }
  207. }
  208. }