TmdbMovieProvider.cs 14 KB

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