GenericMovieDbInfo.cs 13 KB

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