TvdbEpisodeProvider.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Net.Http;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Common.Net;
  8. using MediaBrowser.Controller.Entities;
  9. using MediaBrowser.Controller.Entities.TV;
  10. using MediaBrowser.Controller.Providers;
  11. using MediaBrowser.Model.Entities;
  12. using MediaBrowser.Model.Providers;
  13. using Microsoft.Extensions.Logging;
  14. using TvDbSharper;
  15. using TvDbSharper.Dto;
  16. namespace MediaBrowser.Providers.Plugins.TheTvdb
  17. {
  18. /// <summary>
  19. /// Class RemoteEpisodeProvider.
  20. /// </summary>
  21. public class TvdbEpisodeProvider : IRemoteMetadataProvider<Episode, EpisodeInfo>, IHasOrder
  22. {
  23. private readonly IHttpClientFactory _httpClientFactory;
  24. private readonly ILogger<TvdbEpisodeProvider> _logger;
  25. private readonly TvdbClientManager _tvdbClientManager;
  26. public TvdbEpisodeProvider(IHttpClientFactory httpClientFactory, ILogger<TvdbEpisodeProvider> logger, TvdbClientManager tvdbClientManager)
  27. {
  28. _httpClientFactory = httpClientFactory;
  29. _logger = logger;
  30. _tvdbClientManager = tvdbClientManager;
  31. }
  32. public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(EpisodeInfo searchInfo, CancellationToken cancellationToken)
  33. {
  34. var list = new List<RemoteSearchResult>();
  35. // Either an episode number or date must be provided; and the dictionary of provider ids must be valid
  36. if ((searchInfo.IndexNumber == null && searchInfo.PremiereDate == null)
  37. || !TvdbSeriesProvider.IsValidSeries(searchInfo.SeriesProviderIds))
  38. {
  39. return list;
  40. }
  41. var metadataResult = await GetEpisode(searchInfo, cancellationToken).ConfigureAwait(false);
  42. if (!metadataResult.HasMetadata)
  43. {
  44. return list;
  45. }
  46. var item = metadataResult.Item;
  47. list.Add(new RemoteSearchResult
  48. {
  49. IndexNumber = item.IndexNumber,
  50. Name = item.Name,
  51. ParentIndexNumber = item.ParentIndexNumber,
  52. PremiereDate = item.PremiereDate,
  53. ProductionYear = item.ProductionYear,
  54. ProviderIds = item.ProviderIds,
  55. SearchProviderName = Name,
  56. IndexNumberEnd = item.IndexNumberEnd
  57. });
  58. return list;
  59. }
  60. public string Name => "TheTVDB";
  61. public async Task<MetadataResult<Episode>> GetMetadata(EpisodeInfo searchInfo, CancellationToken cancellationToken)
  62. {
  63. var result = new MetadataResult<Episode>
  64. {
  65. QueriedById = true
  66. };
  67. if (TvdbSeriesProvider.IsValidSeries(searchInfo.SeriesProviderIds) &&
  68. (searchInfo.IndexNumber.HasValue || searchInfo.PremiereDate.HasValue))
  69. {
  70. result = await GetEpisode(searchInfo, cancellationToken).ConfigureAwait(false);
  71. }
  72. else
  73. {
  74. _logger.LogDebug("No series identity found for {EpisodeName}", searchInfo.Name);
  75. }
  76. return result;
  77. }
  78. private async Task<MetadataResult<Episode>> GetEpisode(EpisodeInfo searchInfo, CancellationToken cancellationToken)
  79. {
  80. var result = new MetadataResult<Episode>
  81. {
  82. QueriedById = true
  83. };
  84. string seriesTvdbId = searchInfo.GetProviderId(MetadataProvider.Tvdb);
  85. string episodeTvdbId = null;
  86. try
  87. {
  88. episodeTvdbId = await _tvdbClientManager
  89. .GetEpisodeTvdbId(searchInfo, searchInfo.MetadataLanguage, cancellationToken)
  90. .ConfigureAwait(false);
  91. if (string.IsNullOrEmpty(episodeTvdbId))
  92. {
  93. _logger.LogError("Episode {SeasonNumber}x{EpisodeNumber} not found for series {SeriesTvdbId}",
  94. searchInfo.ParentIndexNumber, searchInfo.IndexNumber, seriesTvdbId);
  95. return result;
  96. }
  97. var episodeResult = await _tvdbClientManager.GetEpisodesAsync(
  98. Convert.ToInt32(episodeTvdbId), searchInfo.MetadataLanguage,
  99. cancellationToken).ConfigureAwait(false);
  100. result = MapEpisodeToResult(searchInfo, episodeResult.Data);
  101. }
  102. catch (TvDbServerException e)
  103. {
  104. _logger.LogError(e, "Failed to retrieve episode with id {EpisodeTvDbId}, series id {SeriesTvdbId}", episodeTvdbId, seriesTvdbId);
  105. }
  106. return result;
  107. }
  108. private static MetadataResult<Episode> MapEpisodeToResult(EpisodeInfo id, EpisodeRecord episode)
  109. {
  110. var result = new MetadataResult<Episode>
  111. {
  112. HasMetadata = true,
  113. Item = new Episode
  114. {
  115. IndexNumber = id.IndexNumber,
  116. ParentIndexNumber = id.ParentIndexNumber,
  117. IndexNumberEnd = id.IndexNumberEnd,
  118. AirsBeforeEpisodeNumber = episode.AirsBeforeEpisode,
  119. AirsAfterSeasonNumber = episode.AirsAfterSeason,
  120. AirsBeforeSeasonNumber = episode.AirsBeforeSeason,
  121. Name = episode.EpisodeName,
  122. Overview = episode.Overview,
  123. CommunityRating = (float?)episode.SiteRating,
  124. }
  125. };
  126. result.ResetPeople();
  127. var item = result.Item;
  128. item.SetProviderId(MetadataProvider.Tvdb, episode.Id.ToString());
  129. item.SetProviderId(MetadataProvider.Imdb, episode.ImdbId);
  130. if (string.Equals(id.SeriesDisplayOrder, "dvd", StringComparison.OrdinalIgnoreCase))
  131. {
  132. item.IndexNumber = Convert.ToInt32(episode.DvdEpisodeNumber ?? episode.AiredEpisodeNumber);
  133. item.ParentIndexNumber = episode.DvdSeason ?? episode.AiredSeason;
  134. }
  135. else if (string.Equals(id.SeriesDisplayOrder, "absolute", StringComparison.OrdinalIgnoreCase))
  136. {
  137. if (episode.AbsoluteNumber.GetValueOrDefault() != 0)
  138. {
  139. item.IndexNumber = episode.AbsoluteNumber;
  140. }
  141. }
  142. else if (episode.AiredEpisodeNumber.HasValue)
  143. {
  144. item.IndexNumber = episode.AiredEpisodeNumber;
  145. }
  146. else if (episode.AiredSeason.HasValue)
  147. {
  148. item.ParentIndexNumber = episode.AiredSeason;
  149. }
  150. if (DateTime.TryParse(episode.FirstAired, out var date))
  151. {
  152. // dates from tvdb are UTC but without offset or Z
  153. item.PremiereDate = date;
  154. item.ProductionYear = date.Year;
  155. }
  156. foreach (var director in episode.Directors)
  157. {
  158. result.AddPerson(new PersonInfo
  159. {
  160. Name = director,
  161. Type = PersonType.Director
  162. });
  163. }
  164. // GuestStars is a weird list of names and roles
  165. // Example:
  166. // 1: Some Actor (Role1
  167. // 2: Role2
  168. // 3: Role3)
  169. // 4: Another Actor (Role1
  170. // ...
  171. for (var i = 0; i < episode.GuestStars.Length; ++i)
  172. {
  173. var currentActor = episode.GuestStars[i];
  174. var roleStartIndex = currentActor.IndexOf('(', StringComparison.Ordinal);
  175. if (roleStartIndex == -1)
  176. {
  177. result.AddPerson(new PersonInfo
  178. {
  179. Type = PersonType.GuestStar,
  180. Name = currentActor,
  181. Role = string.Empty
  182. });
  183. continue;
  184. }
  185. var roles = new List<string> { currentActor.Substring(roleStartIndex + 1) };
  186. // Fetch all roles
  187. for (var j = i + 1; j < episode.GuestStars.Length; ++j)
  188. {
  189. var currentRole = episode.GuestStars[j];
  190. var roleEndIndex = currentRole.IndexOf(')', StringComparison.Ordinal);
  191. if (roleEndIndex == -1)
  192. {
  193. roles.Add(currentRole);
  194. continue;
  195. }
  196. roles.Add(currentRole.TrimEnd(')'));
  197. // Update the outer index (keep in mind it adds 1 after the iteration)
  198. i = j;
  199. break;
  200. }
  201. result.AddPerson(new PersonInfo
  202. {
  203. Type = PersonType.GuestStar,
  204. Name = currentActor.Substring(0, roleStartIndex).Trim(),
  205. Role = string.Join(", ", roles)
  206. });
  207. }
  208. foreach (var writer in episode.Writers)
  209. {
  210. result.AddPerson(new PersonInfo
  211. {
  212. Name = writer,
  213. Type = PersonType.Writer
  214. });
  215. }
  216. result.ResultLanguage = episode.Language.EpisodeName;
  217. return result;
  218. }
  219. public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
  220. {
  221. return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
  222. }
  223. public int Order => 0;
  224. }
  225. }