TmdbMovieProvider.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Net.Http;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Jellyfin.Extensions;
  11. using MediaBrowser.Common.Net;
  12. using MediaBrowser.Controller.Entities;
  13. using MediaBrowser.Controller.Entities.Movies;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Controller.Providers;
  16. using MediaBrowser.Model.Entities;
  17. using MediaBrowser.Model.Providers;
  18. using TMDbLib.Objects.Find;
  19. using TMDbLib.Objects.Search;
  20. namespace MediaBrowser.Providers.Plugins.Tmdb.Movies
  21. {
  22. /// <summary>
  23. /// Class MovieDbProvider.
  24. /// </summary>
  25. public class TmdbMovieProvider : IRemoteMetadataProvider<Movie, MovieInfo>, IHasOrder
  26. {
  27. private readonly IHttpClientFactory _httpClientFactory;
  28. private readonly ILibraryManager _libraryManager;
  29. private readonly TmdbClientManager _tmdbClientManager;
  30. public TmdbMovieProvider(
  31. ILibraryManager libraryManager,
  32. TmdbClientManager tmdbClientManager,
  33. IHttpClientFactory httpClientFactory)
  34. {
  35. _libraryManager = libraryManager;
  36. _tmdbClientManager = tmdbClientManager;
  37. _httpClientFactory = httpClientFactory;
  38. }
  39. public string Name => TmdbUtils.ProviderName;
  40. /// <inheritdoc />
  41. public int Order => 1;
  42. public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(MovieInfo searchInfo, CancellationToken cancellationToken)
  43. {
  44. if (searchInfo.TryGetProviderId(MetadataProvider.Tmdb, out var id))
  45. {
  46. var movie = await _tmdbClientManager
  47. .GetMovieAsync(
  48. int.Parse(id, CultureInfo.InvariantCulture),
  49. searchInfo.MetadataLanguage,
  50. TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage),
  51. cancellationToken)
  52. .ConfigureAwait(false);
  53. var remoteResult = new RemoteSearchResult
  54. {
  55. Name = movie.Title ?? movie.OriginalTitle,
  56. SearchProviderName = Name,
  57. ImageUrl = _tmdbClientManager.GetPosterUrl(movie.PosterPath),
  58. Overview = movie.Overview
  59. };
  60. if (movie.ReleaseDate != null)
  61. {
  62. var releaseDate = movie.ReleaseDate.Value.ToUniversalTime();
  63. remoteResult.PremiereDate = releaseDate;
  64. remoteResult.ProductionYear = releaseDate.Year;
  65. }
  66. remoteResult.SetProviderId(MetadataProvider.Tmdb, movie.Id.ToString(CultureInfo.InvariantCulture));
  67. if (!string.IsNullOrWhiteSpace(movie.ImdbId))
  68. {
  69. remoteResult.SetProviderId(MetadataProvider.Imdb, movie.ImdbId);
  70. }
  71. return new[] { remoteResult };
  72. }
  73. IReadOnlyList<SearchMovie> movieResults;
  74. if (searchInfo.TryGetProviderId(MetadataProvider.Imdb, out id))
  75. {
  76. var result = await _tmdbClientManager.FindByExternalIdAsync(
  77. id,
  78. FindExternalSource.Imdb,
  79. TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage),
  80. cancellationToken).ConfigureAwait(false);
  81. movieResults = result.MovieResults;
  82. }
  83. else if (searchInfo.TryGetProviderId(MetadataProvider.Tvdb, out id))
  84. {
  85. var result = await _tmdbClientManager.FindByExternalIdAsync(
  86. id,
  87. FindExternalSource.TvDb,
  88. TmdbUtils.GetImageLanguagesParam(searchInfo.MetadataLanguage),
  89. cancellationToken).ConfigureAwait(false);
  90. movieResults = result.MovieResults;
  91. }
  92. else
  93. {
  94. movieResults = await _tmdbClientManager
  95. .SearchMovieAsync(searchInfo.Name, searchInfo.Year ?? 0, searchInfo.MetadataLanguage, cancellationToken)
  96. .ConfigureAwait(false);
  97. }
  98. var len = movieResults.Count;
  99. var remoteSearchResults = new RemoteSearchResult[len];
  100. for (var i = 0; i < len; i++)
  101. {
  102. var movieResult = movieResults[i];
  103. var remoteSearchResult = new RemoteSearchResult
  104. {
  105. Name = movieResult.Title ?? movieResult.OriginalTitle,
  106. ImageUrl = _tmdbClientManager.GetPosterUrl(movieResult.PosterPath),
  107. Overview = movieResult.Overview,
  108. SearchProviderName = Name
  109. };
  110. var releaseDate = movieResult.ReleaseDate?.ToUniversalTime();
  111. remoteSearchResult.PremiereDate = releaseDate;
  112. remoteSearchResult.ProductionYear = releaseDate?.Year;
  113. remoteSearchResult.SetProviderId(MetadataProvider.Tmdb, movieResult.Id.ToString(CultureInfo.InvariantCulture));
  114. remoteSearchResults[i] = remoteSearchResult;
  115. }
  116. return remoteSearchResults;
  117. }
  118. public async Task<MetadataResult<Movie>> GetMetadata(MovieInfo info, CancellationToken cancellationToken)
  119. {
  120. var tmdbId = info.GetProviderId(MetadataProvider.Tmdb);
  121. var imdbId = info.GetProviderId(MetadataProvider.Imdb);
  122. if (string.IsNullOrEmpty(tmdbId) && string.IsNullOrEmpty(imdbId))
  123. {
  124. // ParseName is required here.
  125. // Caller provides the filename with extension stripped and NOT the parsed filename
  126. var parsedName = _libraryManager.ParseName(info.Name);
  127. var cleanedName = TmdbUtils.CleanName(parsedName.Name);
  128. var searchResults = await _tmdbClientManager.SearchMovieAsync(cleanedName, info.Year ?? parsedName.Year ?? 0, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);
  129. if (searchResults.Count > 0)
  130. {
  131. tmdbId = searchResults[0].Id.ToString(CultureInfo.InvariantCulture);
  132. }
  133. }
  134. if (string.IsNullOrEmpty(tmdbId) && !string.IsNullOrEmpty(imdbId))
  135. {
  136. var movieResultFromImdbId = await _tmdbClientManager.FindByExternalIdAsync(imdbId, FindExternalSource.Imdb, info.MetadataLanguage, cancellationToken).ConfigureAwait(false);
  137. if (movieResultFromImdbId?.MovieResults.Count > 0)
  138. {
  139. tmdbId = movieResultFromImdbId.MovieResults[0].Id.ToString(CultureInfo.InvariantCulture);
  140. }
  141. }
  142. if (string.IsNullOrEmpty(tmdbId))
  143. {
  144. return new MetadataResult<Movie>();
  145. }
  146. var movieResult = await _tmdbClientManager
  147. .GetMovieAsync(Convert.ToInt32(tmdbId, CultureInfo.InvariantCulture), info.MetadataLanguage, TmdbUtils.GetImageLanguagesParam(info.MetadataLanguage), cancellationToken)
  148. .ConfigureAwait(false);
  149. if (movieResult == null)
  150. {
  151. return new MetadataResult<Movie>();
  152. }
  153. var movie = new Movie
  154. {
  155. Name = movieResult.Title ?? movieResult.OriginalTitle,
  156. OriginalTitle = movieResult.OriginalTitle,
  157. Overview = movieResult.Overview?.Replace("\n\n", "\n", StringComparison.InvariantCulture),
  158. Tagline = movieResult.Tagline,
  159. ProductionLocations = movieResult.ProductionCountries.Select(pc => pc.Name).ToArray()
  160. };
  161. var metadataResult = new MetadataResult<Movie>
  162. {
  163. HasMetadata = true,
  164. ResultLanguage = info.MetadataLanguage,
  165. Item = movie
  166. };
  167. movie.SetProviderId(MetadataProvider.Tmdb, tmdbId);
  168. movie.SetProviderId(MetadataProvider.Imdb, movieResult.ImdbId);
  169. if (movieResult.BelongsToCollection != null)
  170. {
  171. movie.SetProviderId(MetadataProvider.TmdbCollection, movieResult.BelongsToCollection.Id.ToString(CultureInfo.InvariantCulture));
  172. movie.CollectionName = movieResult.BelongsToCollection.Name;
  173. }
  174. movie.CommunityRating = Convert.ToSingle(movieResult.VoteAverage);
  175. if (movieResult.Releases?.Countries != null)
  176. {
  177. var releases = movieResult.Releases.Countries.Where(i => !string.IsNullOrWhiteSpace(i.Certification)).ToList();
  178. var ourRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, info.MetadataCountryCode, StringComparison.OrdinalIgnoreCase));
  179. var usRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));
  180. if (ourRelease != null)
  181. {
  182. movie.OfficialRating = TmdbUtils.BuildParentalRating(ourRelease.Iso_3166_1, ourRelease.Certification);
  183. }
  184. else if (usRelease != null)
  185. {
  186. movie.OfficialRating = usRelease.Certification;
  187. }
  188. }
  189. movie.PremiereDate = movieResult.ReleaseDate;
  190. movie.ProductionYear = movieResult.ReleaseDate?.Year;
  191. if (movieResult.ProductionCompanies != null)
  192. {
  193. movie.SetStudios(movieResult.ProductionCompanies.Select(c => c.Name));
  194. }
  195. var genres = movieResult.Genres;
  196. foreach (var genre in genres.Select(g => g.Name))
  197. {
  198. movie.AddGenre(genre);
  199. }
  200. if (movieResult.Keywords?.Keywords != null)
  201. {
  202. for (var i = 0; i < movieResult.Keywords.Keywords.Count; i++)
  203. {
  204. movie.AddTag(movieResult.Keywords.Keywords[i].Name);
  205. }
  206. }
  207. if (movieResult.Credits?.Cast != null)
  208. {
  209. foreach (var actor in movieResult.Credits.Cast.OrderBy(a => a.Order).Take(Plugin.Instance.Configuration.MaxCastMembers))
  210. {
  211. var personInfo = new PersonInfo
  212. {
  213. Name = actor.Name.Trim(),
  214. Role = actor.Character,
  215. Type = PersonType.Actor,
  216. SortOrder = actor.Order
  217. };
  218. if (!string.IsNullOrWhiteSpace(actor.ProfilePath))
  219. {
  220. personInfo.ImageUrl = _tmdbClientManager.GetProfileUrl(actor.ProfilePath);
  221. }
  222. if (actor.Id > 0)
  223. {
  224. personInfo.SetProviderId(MetadataProvider.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture));
  225. }
  226. metadataResult.AddPerson(personInfo);
  227. }
  228. }
  229. if (movieResult.Credits?.Crew != null)
  230. {
  231. var keepTypes = new[]
  232. {
  233. PersonType.Director,
  234. PersonType.Writer,
  235. PersonType.Producer
  236. };
  237. foreach (var person in movieResult.Credits.Crew)
  238. {
  239. // Normalize this
  240. var type = TmdbUtils.MapCrewToPersonType(person);
  241. if (!keepTypes.Contains(type, StringComparison.OrdinalIgnoreCase) &&
  242. !keepTypes.Contains(person.Job ?? string.Empty, StringComparison.OrdinalIgnoreCase))
  243. {
  244. continue;
  245. }
  246. var personInfo = new PersonInfo
  247. {
  248. Name = person.Name.Trim(),
  249. Role = person.Job,
  250. Type = type
  251. };
  252. if (!string.IsNullOrWhiteSpace(person.ProfilePath))
  253. {
  254. personInfo.ImageUrl = _tmdbClientManager.GetPosterUrl(person.ProfilePath);
  255. }
  256. if (person.Id > 0)
  257. {
  258. personInfo.SetProviderId(MetadataProvider.Tmdb, person.Id.ToString(CultureInfo.InvariantCulture));
  259. }
  260. metadataResult.AddPerson(personInfo);
  261. }
  262. }
  263. if (movieResult.Videos?.Results != null)
  264. {
  265. var trailers = new List<MediaUrl>();
  266. for (var i = 0; i < movieResult.Videos.Results.Count; i++)
  267. {
  268. var video = movieResult.Videos.Results[i];
  269. if (!TmdbUtils.IsTrailerType(video))
  270. {
  271. continue;
  272. }
  273. trailers.Add(new MediaUrl
  274. {
  275. Url = string.Format(CultureInfo.InvariantCulture, "https://www.youtube.com/watch?v={0}", video.Key),
  276. Name = video.Name
  277. });
  278. }
  279. movie.RemoteTrailers = trailers;
  280. }
  281. return metadataResult;
  282. }
  283. /// <inheritdoc />
  284. public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
  285. {
  286. return _httpClientFactory.CreateClient(NamedClient.Default).GetAsync(url, cancellationToken);
  287. }
  288. }
  289. }