GenericTmdbMovieInfo.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Controller.Entities;
  10. using MediaBrowser.Controller.Entities.Movies;
  11. using MediaBrowser.Controller.Library;
  12. using MediaBrowser.Controller.Providers;
  13. using MediaBrowser.Model.Entities;
  14. using MediaBrowser.Model.IO;
  15. using MediaBrowser.Model.Serialization;
  16. using MediaBrowser.Providers.Plugins.Tmdb.Models.Movies;
  17. using Microsoft.Extensions.Logging;
  18. namespace MediaBrowser.Providers.Plugins.Tmdb.Movies
  19. {
  20. public class GenericTmdbMovieInfo<T>
  21. where T : BaseItem, new()
  22. {
  23. private readonly ILogger _logger;
  24. private readonly IJsonSerializer _jsonSerializer;
  25. private readonly ILibraryManager _libraryManager;
  26. private readonly IFileSystem _fileSystem;
  27. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  28. public GenericTmdbMovieInfo(ILogger logger, IJsonSerializer jsonSerializer, ILibraryManager libraryManager, IFileSystem fileSystem)
  29. {
  30. _logger = logger;
  31. _jsonSerializer = jsonSerializer;
  32. _libraryManager = libraryManager;
  33. _fileSystem = fileSystem;
  34. }
  35. public async Task<MetadataResult<T>> GetMetadata(ItemLookupInfo itemId, CancellationToken cancellationToken)
  36. {
  37. var tmdbId = itemId.GetProviderId(MetadataProvider.Tmdb);
  38. var imdbId = itemId.GetProviderId(MetadataProvider.Imdb);
  39. // Don't search for music video id's because it is very easy to misidentify.
  40. if (string.IsNullOrEmpty(tmdbId) && string.IsNullOrEmpty(imdbId) && typeof(T) != typeof(MusicVideo))
  41. {
  42. var searchResults = await new TmdbSearch(_logger, _jsonSerializer, _libraryManager).GetMovieSearchResults(itemId, cancellationToken).ConfigureAwait(false);
  43. var searchResult = searchResults.FirstOrDefault();
  44. if (searchResult != null)
  45. {
  46. tmdbId = searchResult.GetProviderId(MetadataProvider.Tmdb);
  47. }
  48. }
  49. if (!string.IsNullOrEmpty(tmdbId) || !string.IsNullOrEmpty(imdbId))
  50. {
  51. cancellationToken.ThrowIfCancellationRequested();
  52. return await FetchMovieData(tmdbId, imdbId, itemId.MetadataLanguage, itemId.MetadataCountryCode, cancellationToken).ConfigureAwait(false);
  53. }
  54. return new MetadataResult<T>();
  55. }
  56. /// <summary>
  57. /// Fetches the movie data.
  58. /// </summary>
  59. /// <param name="tmdbId">The TMDB identifier.</param>
  60. /// <param name="imdbId">The imdb identifier.</param>
  61. /// <param name="language">The language.</param>
  62. /// <param name="preferredCountryCode">The preferred country code.</param>
  63. /// <param name="cancellationToken">The cancellation token.</param>
  64. /// <returns>Task{`0}.</returns>
  65. private async Task<MetadataResult<T>> FetchMovieData(string tmdbId, string imdbId, string language, string preferredCountryCode, CancellationToken cancellationToken)
  66. {
  67. var item = new MetadataResult<T>
  68. {
  69. Item = new T()
  70. };
  71. string dataFilePath = null;
  72. MovieResult movieInfo = null;
  73. // Id could be ImdbId or TmdbId
  74. if (string.IsNullOrEmpty(tmdbId))
  75. {
  76. movieInfo = await TmdbMovieProvider.Current.FetchMainResult(imdbId, false, language, cancellationToken).ConfigureAwait(false);
  77. if (movieInfo != null)
  78. {
  79. tmdbId = movieInfo.Id.ToString(_usCulture);
  80. dataFilePath = TmdbMovieProvider.Current.GetDataFilePath(tmdbId, language);
  81. Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
  82. _jsonSerializer.SerializeToFile(movieInfo, dataFilePath);
  83. }
  84. }
  85. if (!string.IsNullOrWhiteSpace(tmdbId))
  86. {
  87. await TmdbMovieProvider.Current.EnsureMovieInfo(tmdbId, language, cancellationToken).ConfigureAwait(false);
  88. dataFilePath = dataFilePath ?? TmdbMovieProvider.Current.GetDataFilePath(tmdbId, language);
  89. movieInfo = movieInfo ?? _jsonSerializer.DeserializeFromFile<MovieResult>(dataFilePath);
  90. var settings = await TmdbMovieProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
  91. ProcessMainInfo(item, settings, preferredCountryCode, movieInfo);
  92. item.HasMetadata = true;
  93. }
  94. return item;
  95. }
  96. /// <summary>
  97. /// Processes the main info.
  98. /// </summary>
  99. /// <param name="resultItem">The result item.</param>
  100. /// <param name="settings">The settings.</param>
  101. /// <param name="preferredCountryCode">The preferred country code.</param>
  102. /// <param name="movieData">The movie data.</param>
  103. private void ProcessMainInfo(MetadataResult<T> resultItem, TmdbSettingsResult settings, string preferredCountryCode, MovieResult movieData)
  104. {
  105. var movie = resultItem.Item;
  106. movie.Name = movieData.GetTitle() ?? movie.Name;
  107. movie.OriginalTitle = movieData.GetOriginalTitle();
  108. movie.Overview = string.IsNullOrWhiteSpace(movieData.Overview) ? null : WebUtility.HtmlDecode(movieData.Overview);
  109. movie.Overview = movie.Overview != null ? movie.Overview.Replace("\n\n", "\n") : null;
  110. //movie.HomePageUrl = movieData.homepage;
  111. if (!string.IsNullOrEmpty(movieData.Tagline))
  112. {
  113. movie.Tagline = movieData.Tagline;
  114. }
  115. if (movieData.Production_Countries != null)
  116. {
  117. movie.ProductionLocations = movieData
  118. .Production_Countries
  119. .Select(i => i.Name)
  120. .ToArray();
  121. }
  122. movie.SetProviderId(MetadataProvider.Tmdb, movieData.Id.ToString(_usCulture));
  123. movie.SetProviderId(MetadataProvider.Imdb, movieData.Imdb_Id);
  124. if (movieData.Belongs_To_Collection != null)
  125. {
  126. movie.SetProviderId(MetadataProvider.TmdbCollection,
  127. movieData.Belongs_To_Collection.Id.ToString(CultureInfo.InvariantCulture));
  128. if (movie is Movie movieItem)
  129. {
  130. movieItem.CollectionName = movieData.Belongs_To_Collection.Name;
  131. }
  132. }
  133. string voteAvg = movieData.Vote_Average.ToString(CultureInfo.InvariantCulture);
  134. if (float.TryParse(voteAvg, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var rating))
  135. {
  136. movie.CommunityRating = rating;
  137. }
  138. //movie.VoteCount = movieData.vote_count;
  139. if (movieData.Releases != null && movieData.Releases.Countries != null)
  140. {
  141. var releases = movieData.Releases.Countries.Where(i => !string.IsNullOrWhiteSpace(i.Certification)).ToList();
  142. var ourRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, preferredCountryCode, StringComparison.OrdinalIgnoreCase));
  143. var usRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));
  144. if (ourRelease != null)
  145. {
  146. var ratingPrefix = string.Equals(preferredCountryCode, "us", StringComparison.OrdinalIgnoreCase) ? "" : preferredCountryCode + "-";
  147. var newRating = ratingPrefix + ourRelease.Certification;
  148. newRating = newRating.Replace("de-", "FSK-", StringComparison.OrdinalIgnoreCase);
  149. movie.OfficialRating = newRating;
  150. }
  151. else if (usRelease != null)
  152. {
  153. movie.OfficialRating = usRelease.Certification;
  154. }
  155. }
  156. if (!string.IsNullOrWhiteSpace(movieData.Release_Date))
  157. {
  158. // These dates are always in this exact format
  159. if (DateTime.TryParse(movieData.Release_Date, _usCulture, DateTimeStyles.None, out var r))
  160. {
  161. movie.PremiereDate = r.ToUniversalTime();
  162. movie.ProductionYear = movie.PremiereDate.Value.Year;
  163. }
  164. }
  165. //studios
  166. if (movieData.Production_Companies != null)
  167. {
  168. movie.SetStudios(movieData.Production_Companies.Select(c => c.Name));
  169. }
  170. // genres
  171. // Movies get this from imdb
  172. var genres = movieData.Genres ?? new List<Tmdb.Models.General.Genre>();
  173. foreach (var genre in genres.Select(g => g.Name))
  174. {
  175. movie.AddGenre(genre);
  176. }
  177. resultItem.ResetPeople();
  178. var tmdbImageUrl = settings.images.GetImageUrl("original");
  179. //Actors, Directors, Writers - all in People
  180. //actors come from cast
  181. if (movieData.Casts != null && movieData.Casts.Cast != null)
  182. {
  183. foreach (var actor in movieData.Casts.Cast.OrderBy(a => a.Order))
  184. {
  185. var personInfo = new PersonInfo
  186. {
  187. Name = actor.Name.Trim(),
  188. Role = actor.Character,
  189. Type = PersonType.Actor,
  190. SortOrder = actor.Order
  191. };
  192. if (!string.IsNullOrWhiteSpace(actor.Profile_Path))
  193. {
  194. personInfo.ImageUrl = tmdbImageUrl + actor.Profile_Path;
  195. }
  196. if (actor.Id > 0)
  197. {
  198. personInfo.SetProviderId(MetadataProvider.Tmdb, actor.Id.ToString(CultureInfo.InvariantCulture));
  199. }
  200. resultItem.AddPerson(personInfo);
  201. }
  202. }
  203. //and the rest from crew
  204. if (movieData.Casts?.Crew != null)
  205. {
  206. var keepTypes = new[]
  207. {
  208. PersonType.Director,
  209. PersonType.Writer,
  210. PersonType.Producer
  211. };
  212. foreach (var person in movieData.Casts.Crew)
  213. {
  214. // Normalize this
  215. var type = TmdbUtils.MapCrewToPersonType(person);
  216. if (!keepTypes.Contains(type, StringComparer.OrdinalIgnoreCase) &&
  217. !keepTypes.Contains(person.Job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  218. {
  219. continue;
  220. }
  221. var personInfo = new PersonInfo
  222. {
  223. Name = person.Name.Trim(),
  224. Role = person.Job,
  225. Type = type
  226. };
  227. if (!string.IsNullOrWhiteSpace(person.Profile_Path))
  228. {
  229. personInfo.ImageUrl = tmdbImageUrl + person.Profile_Path;
  230. }
  231. if (person.Id > 0)
  232. {
  233. personInfo.SetProviderId(MetadataProvider.Tmdb, person.Id.ToString(CultureInfo.InvariantCulture));
  234. }
  235. resultItem.AddPerson(personInfo);
  236. }
  237. }
  238. //if (movieData.keywords != null && movieData.keywords.keywords != null)
  239. //{
  240. // movie.Keywords = movieData.keywords.keywords.Select(i => i.name).ToList();
  241. //}
  242. if (movieData.Trailers != null && movieData.Trailers.Youtube != null)
  243. {
  244. movie.RemoteTrailers = movieData.Trailers.Youtube.Select(i => new MediaUrl
  245. {
  246. Url = string.Format("https://www.youtube.com/watch?v={0}", i.Source),
  247. Name = i.Name
  248. }).ToArray();
  249. }
  250. }
  251. }
  252. }