GenericMovieDbInfo.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. .ToArray(movieData.production_countries.Count);
  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.SetStudios(movieData.production_companies.Select(c => c.name));
  175. }
  176. // genres
  177. // Movies get this from imdb
  178. var genres = movieData.genres ?? new List<MovieDbProvider.GenreItem>();
  179. foreach (var genre in genres.Select(g => g.name))
  180. {
  181. movie.AddGenre(genre);
  182. }
  183. resultItem.ResetPeople();
  184. var tmdbImageUrl = settings.images.secure_base_url + "original";
  185. //Actors, Directors, Writers - all in People
  186. //actors come from cast
  187. if (movieData.casts != null && movieData.casts.cast != null)
  188. {
  189. foreach (var actor in movieData.casts.cast.OrderBy(a => a.order))
  190. {
  191. var personInfo = new PersonInfo
  192. {
  193. Name = actor.name.Trim(),
  194. Role = actor.character,
  195. Type = PersonType.Actor,
  196. SortOrder = actor.order
  197. };
  198. if (!string.IsNullOrWhiteSpace(actor.profile_path))
  199. {
  200. personInfo.ImageUrl = tmdbImageUrl + actor.profile_path;
  201. }
  202. if (actor.id > 0)
  203. {
  204. personInfo.SetProviderId(MetadataProviders.Tmdb, actor.id.ToString(CultureInfo.InvariantCulture));
  205. }
  206. resultItem.AddPerson(personInfo);
  207. }
  208. }
  209. //and the rest from crew
  210. if (movieData.casts != null && movieData.casts.crew != null)
  211. {
  212. var keepTypes = new[]
  213. {
  214. PersonType.Director,
  215. PersonType.Writer,
  216. //PersonType.Producer
  217. };
  218. foreach (var person in movieData.casts.crew)
  219. {
  220. // Normalize this
  221. var type = person.department;
  222. if (string.Equals(type, "writing", StringComparison.OrdinalIgnoreCase))
  223. {
  224. type = PersonType.Writer;
  225. }
  226. if (!keepTypes.Contains(type ?? string.Empty, StringComparer.OrdinalIgnoreCase) &&
  227. !keepTypes.Contains(person.job ?? string.Empty, StringComparer.OrdinalIgnoreCase))
  228. {
  229. continue;
  230. }
  231. var personInfo = new PersonInfo
  232. {
  233. Name = person.name.Trim(),
  234. Role = person.job,
  235. Type = type
  236. };
  237. if (!string.IsNullOrWhiteSpace(person.profile_path))
  238. {
  239. personInfo.ImageUrl = tmdbImageUrl + person.profile_path;
  240. }
  241. if (person.id > 0)
  242. {
  243. personInfo.SetProviderId(MetadataProviders.Tmdb, person.id.ToString(CultureInfo.InvariantCulture));
  244. }
  245. resultItem.AddPerson(personInfo);
  246. }
  247. }
  248. //if (movieData.keywords != null && movieData.keywords.keywords != null)
  249. //{
  250. // movie.Keywords = movieData.keywords.keywords.Select(i => i.name).ToList();
  251. //}
  252. if (movieData.trailers != null && movieData.trailers.youtube != null &&
  253. movieData.trailers.youtube.Count > 0)
  254. {
  255. var hasTrailers = movie as IHasTrailers;
  256. if (hasTrailers != null)
  257. {
  258. hasTrailers.RemoteTrailers = movieData.trailers.youtube.Select(i => new MediaUrl
  259. {
  260. Url = string.Format("https://www.youtube.com/watch?v={0}", i.source),
  261. Name = i.name
  262. }).ToArray();
  263. }
  264. }
  265. }
  266. }
  267. }