TvDbClientManager.cs 10 KB

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