TvdbEpisodeProvider.cs 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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. OfficialRating = episode.ContentRating,
  125. }
  126. };
  127. result.ResetPeople();
  128. var item = result.Item;
  129. item.SetProviderId(MetadataProvider.Tvdb, episode.Id.ToString());
  130. item.SetProviderId(MetadataProvider.Imdb, episode.ImdbId);
  131. if (string.Equals(id.SeriesDisplayOrder, "dvd", StringComparison.OrdinalIgnoreCase))
  132. {
  133. item.IndexNumber = Convert.ToInt32(episode.DvdEpisodeNumber ?? episode.AiredEpisodeNumber);
  134. item.ParentIndexNumber = episode.DvdSeason ?? episode.AiredSeason;
  135. }
  136. else if (string.Equals(id.SeriesDisplayOrder, "absolute", StringComparison.OrdinalIgnoreCase))
  137. {
  138. if (episode.AbsoluteNumber.GetValueOrDefault() != 0)
  139. {
  140. item.IndexNumber = episode.AbsoluteNumber;
  141. }
  142. }
  143. else if (episode.AiredEpisodeNumber.HasValue)
  144. {
  145. item.IndexNumber = episode.AiredEpisodeNumber;
  146. }
  147. else if (episode.AiredSeason.HasValue)
  148. {
  149. item.ParentIndexNumber = episode.AiredSeason;
  150. }
  151. if (DateTime.TryParse(episode.FirstAired, out var date))
  152. {
  153. // dates from tvdb are UTC but without offset or Z
  154. item.PremiereDate = date;
  155. item.ProductionYear = date.Year;
  156. }
  157. foreach (var director in episode.Directors)
  158. {
  159. result.AddPerson(new PersonInfo
  160. {
  161. Name = director,
  162. Type = PersonType.Director
  163. });
  164. }
  165. // GuestStars is a weird list of names and roles
  166. // Example:
  167. // 1: Some Actor (Role1
  168. // 2: Role2
  169. // 3: Role3)
  170. // 4: Another Actor (Role1
  171. // ...
  172. for (var i = 0; i < episode.GuestStars.Length; ++i)
  173. {
  174. var currentActor = episode.GuestStars[i];
  175. var roleStartIndex = currentActor.IndexOf('(', StringComparison.Ordinal);
  176. if (roleStartIndex == -1)
  177. {
  178. result.AddPerson(new PersonInfo
  179. {
  180. Type = PersonType.GuestStar,
  181. Name = currentActor,
  182. Role = string.Empty
  183. });
  184. continue;
  185. }
  186. var roles = new List<string> { currentActor.Substring(roleStartIndex + 1) };
  187. // Fetch all roles
  188. for (var j = i + 1; j < episode.GuestStars.Length; ++j)
  189. {
  190. var currentRole = episode.GuestStars[j];
  191. var roleEndIndex = currentRole.IndexOf(')', StringComparison.Ordinal);
  192. if (roleEndIndex == -1)
  193. {
  194. roles.Add(currentRole);
  195. continue;
  196. }
  197. roles.Add(currentRole.TrimEnd(')'));
  198. // Update the outer index (keep in mind it adds 1 after the iteration)
  199. i = j;
  200. break;
  201. }
  202. result.AddPerson(new PersonInfo
  203. {
  204. Type = PersonType.GuestStar,
  205. Name = currentActor.Substring(0, roleStartIndex).Trim(),
  206. Role = string.Join(", ", roles)
  207. });
  208. }
  209. foreach (var writer in episode.Writers)
  210. {
  211. result.AddPerson(new PersonInfo
  212. {
  213. Name = writer,
  214. Type = PersonType.Writer
  215. });
  216. }
  217. result.ResultLanguage = episode.Language.EpisodeName;
  218. return result;
  219. }
  220. public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
  221. {
  222. return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
  223. }
  224. public int Order => 0;
  225. }
  226. }