MovieDbProvider.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Entities.Movies;
  7. using MediaBrowser.Controller.Localization;
  8. using MediaBrowser.Controller.Providers;
  9. using MediaBrowser.Model.Entities;
  10. using MediaBrowser.Model.Logging;
  11. using MediaBrowser.Model.Providers;
  12. using MediaBrowser.Model.Serialization;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.Providers.Movies
  21. {
  22. /// <summary>
  23. /// Class MovieDbProvider
  24. /// </summary>
  25. public class MovieDbProvider : IRemoteMetadataProvider<Movie, MovieInfo>, IDisposable, IHasOrder
  26. {
  27. internal readonly SemaphoreSlim MovieDbResourcePool = new SemaphoreSlim(1, 1);
  28. internal static MovieDbProvider Current { get; private set; }
  29. private readonly IJsonSerializer _jsonSerializer;
  30. private readonly IHttpClient _httpClient;
  31. private readonly IFileSystem _fileSystem;
  32. private readonly IServerConfigurationManager _configurationManager;
  33. private readonly ILogger _logger;
  34. private readonly ILocalizationManager _localization;
  35. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  36. public MovieDbProvider(IJsonSerializer jsonSerializer, IHttpClient httpClient, IFileSystem fileSystem, IServerConfigurationManager configurationManager, ILogger logger, ILocalizationManager localization)
  37. {
  38. _jsonSerializer = jsonSerializer;
  39. _httpClient = httpClient;
  40. _fileSystem = fileSystem;
  41. _configurationManager = configurationManager;
  42. _logger = logger;
  43. _localization = localization;
  44. Current = this;
  45. }
  46. public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(MovieInfo searchInfo, CancellationToken cancellationToken)
  47. {
  48. return GetMovieSearchResults(searchInfo, cancellationToken);
  49. }
  50. public async Task<IEnumerable<RemoteSearchResult>> GetMovieSearchResults(ItemLookupInfo searchInfo, CancellationToken cancellationToken)
  51. {
  52. var tmdbSettings = await GetTmdbSettings(cancellationToken).ConfigureAwait(false);
  53. var tmdbImageUrl = tmdbSettings.images.base_url + "original";
  54. var tmdbId = searchInfo.GetProviderId(MetadataProviders.Tmdb);
  55. if (!string.IsNullOrEmpty(tmdbId))
  56. {
  57. cancellationToken.ThrowIfCancellationRequested();
  58. await EnsureMovieInfo(tmdbId, searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);
  59. var dataFilePath = GetDataFilePath(tmdbId, searchInfo.MetadataLanguage);
  60. var obj = _jsonSerializer.DeserializeFromFile<CompleteMovieData>(dataFilePath);
  61. var remoteResult = new RemoteSearchResult
  62. {
  63. Name = obj.title ?? obj.original_title ?? obj.name,
  64. SearchProviderName = Name,
  65. ImageUrl = string.IsNullOrWhiteSpace(obj.poster_path) ? null : tmdbImageUrl + obj.poster_path
  66. };
  67. if (!string.IsNullOrWhiteSpace(obj.release_date))
  68. {
  69. DateTime r;
  70. // These dates are always in this exact format
  71. if (DateTime.TryParse(obj.release_date, _usCulture, DateTimeStyles.None, out r))
  72. {
  73. remoteResult.PremiereDate = r.ToUniversalTime();
  74. remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year;
  75. }
  76. }
  77. remoteResult.SetProviderId(MetadataProviders.Tmdb, obj.id.ToString(_usCulture));
  78. if (!string.IsNullOrWhiteSpace(obj.imdb_id))
  79. {
  80. remoteResult.SetProviderId(MetadataProviders.Imdb, obj.imdb_id);
  81. }
  82. return new[] { remoteResult };
  83. }
  84. return await new MovieDbSearch(_logger, _jsonSerializer).GetMovieSearchResults(searchInfo, cancellationToken).ConfigureAwait(false);
  85. }
  86. public Task<MetadataResult<Movie>> GetMetadata(MovieInfo info, CancellationToken cancellationToken)
  87. {
  88. return GetItemMetadata<Movie>(info, cancellationToken);
  89. }
  90. public Task<MetadataResult<T>> GetItemMetadata<T>(ItemLookupInfo id, CancellationToken cancellationToken)
  91. where T : Video, new()
  92. {
  93. var movieDb = new GenericMovieDbInfo<T>(_logger, _jsonSerializer);
  94. return movieDb.GetMetadata(id, cancellationToken);
  95. }
  96. public string Name
  97. {
  98. get { return "TheMovieDb"; }
  99. }
  100. /// <summary>
  101. /// Releases unmanaged and - optionally - managed resources.
  102. /// </summary>
  103. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  104. protected virtual void Dispose(bool dispose)
  105. {
  106. if (dispose)
  107. {
  108. MovieDbResourcePool.Dispose();
  109. }
  110. }
  111. /// <summary>
  112. /// The _TMDB settings task
  113. /// </summary>
  114. private TmdbSettingsResult _tmdbSettings;
  115. private readonly SemaphoreSlim _tmdbSettingsSemaphore = new SemaphoreSlim(1, 1);
  116. /// <summary>
  117. /// Gets the TMDB settings.
  118. /// </summary>
  119. /// <returns>Task{TmdbSettingsResult}.</returns>
  120. internal async Task<TmdbSettingsResult> GetTmdbSettings(CancellationToken cancellationToken)
  121. {
  122. if (_tmdbSettings != null)
  123. {
  124. return _tmdbSettings;
  125. }
  126. await _tmdbSettingsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  127. try
  128. {
  129. // Check again in case it got populated while we were waiting.
  130. if (_tmdbSettings != null)
  131. {
  132. return _tmdbSettings;
  133. }
  134. using (var json = await GetMovieDbResponse(new HttpRequestOptions
  135. {
  136. Url = string.Format(TmdbConfigUrl, ApiKey),
  137. CancellationToken = cancellationToken,
  138. AcceptHeader = AcceptHeader
  139. }).ConfigureAwait(false))
  140. {
  141. _tmdbSettings = _jsonSerializer.DeserializeFromStream<TmdbSettingsResult>(json);
  142. return _tmdbSettings;
  143. }
  144. }
  145. finally
  146. {
  147. _tmdbSettingsSemaphore.Release();
  148. }
  149. }
  150. private const string TmdbConfigUrl = "http://api.themoviedb.org/3/configuration?api_key={0}";
  151. private const string GetMovieInfo3 = @"http://api.themoviedb.org/3/movie/{0}?api_key={1}&append_to_response=casts,releases,images,keywords,trailers";
  152. internal static string ApiKey = "f6bd687ffa63cd282b6ff2c6877f2669";
  153. internal static string AcceptHeader = "application/json,image/*";
  154. /// <summary>
  155. /// Gets the movie data path.
  156. /// </summary>
  157. /// <param name="appPaths">The app paths.</param>
  158. /// <param name="tmdbId">The TMDB id.</param>
  159. /// <returns>System.String.</returns>
  160. internal static string GetMovieDataPath(IApplicationPaths appPaths, string tmdbId)
  161. {
  162. var dataPath = GetMoviesDataPath(appPaths);
  163. return Path.Combine(dataPath, tmdbId);
  164. }
  165. internal static string GetMoviesDataPath(IApplicationPaths appPaths)
  166. {
  167. var dataPath = Path.Combine(appPaths.CachePath, "tmdb-movies");
  168. return dataPath;
  169. }
  170. /// <summary>
  171. /// Downloads the movie info.
  172. /// </summary>
  173. /// <param name="id">The id.</param>
  174. /// <param name="preferredMetadataLanguage">The preferred metadata language.</param>
  175. /// <param name="cancellationToken">The cancellation token.</param>
  176. /// <returns>Task.</returns>
  177. internal async Task DownloadMovieInfo(string id, string preferredMetadataLanguage, CancellationToken cancellationToken)
  178. {
  179. var mainResult = await FetchMainResult(id, preferredMetadataLanguage, cancellationToken).ConfigureAwait(false);
  180. if (mainResult == null) return;
  181. var dataFilePath = GetDataFilePath(id, preferredMetadataLanguage);
  182. Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
  183. _jsonSerializer.SerializeToFile(mainResult, dataFilePath);
  184. }
  185. private readonly Task _cachedTask = Task.FromResult(true);
  186. internal Task EnsureMovieInfo(string tmdbId, string language, CancellationToken cancellationToken)
  187. {
  188. if (string.IsNullOrEmpty(tmdbId))
  189. {
  190. throw new ArgumentNullException("tmdbId");
  191. }
  192. if (string.IsNullOrEmpty(language))
  193. {
  194. throw new ArgumentNullException("language");
  195. }
  196. var path = GetDataFilePath(tmdbId, language);
  197. var fileInfo = _fileSystem.GetFileSystemInfo(path);
  198. if (fileInfo.Exists)
  199. {
  200. // If it's recent or automatic updates are enabled, don't re-download
  201. if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 7)
  202. {
  203. return _cachedTask;
  204. }
  205. }
  206. return DownloadMovieInfo(tmdbId, language, cancellationToken);
  207. }
  208. internal string GetDataFilePath(string tmdbId, string preferredLanguage)
  209. {
  210. if (string.IsNullOrEmpty(tmdbId))
  211. {
  212. throw new ArgumentNullException("tmdbId");
  213. }
  214. if (string.IsNullOrEmpty(preferredLanguage))
  215. {
  216. throw new ArgumentNullException("preferredLanguage");
  217. }
  218. var path = GetMovieDataPath(_configurationManager.ApplicationPaths, tmdbId);
  219. var filename = string.Format("all-{0}.json",
  220. preferredLanguage ?? string.Empty);
  221. return Path.Combine(path, filename);
  222. }
  223. /// <summary>
  224. /// Fetches the main result.
  225. /// </summary>
  226. /// <param name="id">The id.</param>
  227. /// <param name="language">The language.</param>
  228. /// <param name="cancellationToken">The cancellation token</param>
  229. /// <returns>Task{CompleteMovieData}.</returns>
  230. internal async Task<CompleteMovieData> FetchMainResult(string id, string language, CancellationToken cancellationToken)
  231. {
  232. var url = string.Format(GetMovieInfo3, id, ApiKey);
  233. var imageLanguages = _localization.GetCultures()
  234. .Select(i => i.TwoLetterISOLanguageName)
  235. .Distinct(StringComparer.OrdinalIgnoreCase)
  236. .ToList();
  237. imageLanguages.Add("null");
  238. if (!string.IsNullOrEmpty(language))
  239. {
  240. // If preferred language isn't english, get those images too
  241. if (imageLanguages.Contains(language, StringComparer.OrdinalIgnoreCase))
  242. {
  243. imageLanguages.Add(language);
  244. }
  245. url += string.Format("&language={0}", language);
  246. }
  247. // Get images in english and with no language
  248. url += "&include_image_language=" + string.Join(",", imageLanguages.ToArray());
  249. CompleteMovieData mainResult;
  250. cancellationToken.ThrowIfCancellationRequested();
  251. using (var json = await GetMovieDbResponse(new HttpRequestOptions
  252. {
  253. Url = url,
  254. CancellationToken = cancellationToken,
  255. AcceptHeader = AcceptHeader
  256. }).ConfigureAwait(false))
  257. {
  258. mainResult = _jsonSerializer.DeserializeFromStream<CompleteMovieData>(json);
  259. }
  260. cancellationToken.ThrowIfCancellationRequested();
  261. if (mainResult != null && string.IsNullOrEmpty(mainResult.overview))
  262. {
  263. if (!string.IsNullOrEmpty(language) && !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
  264. {
  265. _logger.Info("MovieDbProvider couldn't find meta for language " + language + ". Trying English...");
  266. url = string.Format(GetMovieInfo3, id, ApiKey) + "&include_image_language=en,null&language=en";
  267. using (var json = await GetMovieDbResponse(new HttpRequestOptions
  268. {
  269. Url = url,
  270. CancellationToken = cancellationToken,
  271. AcceptHeader = AcceptHeader
  272. }).ConfigureAwait(false))
  273. {
  274. mainResult = _jsonSerializer.DeserializeFromStream<CompleteMovieData>(json);
  275. }
  276. if (String.IsNullOrEmpty(mainResult.overview))
  277. {
  278. _logger.Error("MovieDbProvider - Unable to find information for (id:" + id + ")");
  279. return null;
  280. }
  281. }
  282. }
  283. return mainResult;
  284. }
  285. private DateTime _lastRequestDate = DateTime.MinValue;
  286. /// <summary>
  287. /// Gets the movie db response.
  288. /// </summary>
  289. internal async Task<Stream> GetMovieDbResponse(HttpRequestOptions options)
  290. {
  291. var cancellationToken = options.CancellationToken;
  292. await MovieDbResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  293. try
  294. {
  295. // Limit to three requests per second
  296. var diff = 340 - (DateTime.Now - _lastRequestDate).TotalMilliseconds;
  297. if (diff > 0)
  298. {
  299. await Task.Delay(Convert.ToInt32(diff), cancellationToken).ConfigureAwait(false);
  300. }
  301. _lastRequestDate = DateTime.Now;
  302. return await _httpClient.Get(options).ConfigureAwait(false);
  303. }
  304. finally
  305. {
  306. _lastRequestDate = DateTime.Now;
  307. MovieDbResourcePool.Release();
  308. }
  309. }
  310. public bool HasChanged(IHasMetadata item, DateTime date)
  311. {
  312. if (!_configurationManager.Configuration.EnableTmdbUpdates)
  313. {
  314. return false;
  315. }
  316. var tmdbId = item.GetProviderId(MetadataProviders.Tmdb);
  317. if (!String.IsNullOrEmpty(tmdbId))
  318. {
  319. // Process images
  320. var dataFilePath = GetDataFilePath(tmdbId, item.GetPreferredMetadataLanguage());
  321. var fileInfo = new FileInfo(dataFilePath);
  322. return !fileInfo.Exists || _fileSystem.GetLastWriteTimeUtc(fileInfo) > date;
  323. }
  324. return false;
  325. }
  326. public void Dispose()
  327. {
  328. Dispose(true);
  329. }
  330. /// <summary>
  331. /// Class TmdbTitle
  332. /// </summary>
  333. internal class TmdbTitle
  334. {
  335. /// <summary>
  336. /// Gets or sets the iso_3166_1.
  337. /// </summary>
  338. /// <value>The iso_3166_1.</value>
  339. public string iso_3166_1 { get; set; }
  340. /// <summary>
  341. /// Gets or sets the title.
  342. /// </summary>
  343. /// <value>The title.</value>
  344. public string title { get; set; }
  345. }
  346. /// <summary>
  347. /// Class TmdbAltTitleResults
  348. /// </summary>
  349. internal class TmdbAltTitleResults
  350. {
  351. /// <summary>
  352. /// Gets or sets the id.
  353. /// </summary>
  354. /// <value>The id.</value>
  355. public int id { get; set; }
  356. /// <summary>
  357. /// Gets or sets the titles.
  358. /// </summary>
  359. /// <value>The titles.</value>
  360. public List<TmdbTitle> titles { get; set; }
  361. }
  362. internal class BelongsToCollection
  363. {
  364. public int id { get; set; }
  365. public string name { get; set; }
  366. public string poster_path { get; set; }
  367. public string backdrop_path { get; set; }
  368. }
  369. internal class GenreItem
  370. {
  371. public int id { get; set; }
  372. public string name { get; set; }
  373. }
  374. internal class ProductionCompany
  375. {
  376. public string name { get; set; }
  377. public int id { get; set; }
  378. }
  379. internal class ProductionCountry
  380. {
  381. public string iso_3166_1 { get; set; }
  382. public string name { get; set; }
  383. }
  384. internal class SpokenLanguage
  385. {
  386. public string iso_639_1 { get; set; }
  387. public string name { get; set; }
  388. }
  389. internal class Cast
  390. {
  391. public int id { get; set; }
  392. public string name { get; set; }
  393. public string character { get; set; }
  394. public int order { get; set; }
  395. public int cast_id { get; set; }
  396. public string profile_path { get; set; }
  397. }
  398. internal class Crew
  399. {
  400. public int id { get; set; }
  401. public string name { get; set; }
  402. public string department { get; set; }
  403. public string job { get; set; }
  404. public string profile_path { get; set; }
  405. }
  406. internal class Casts
  407. {
  408. public List<Cast> cast { get; set; }
  409. public List<Crew> crew { get; set; }
  410. }
  411. internal class Country
  412. {
  413. public string iso_3166_1 { get; set; }
  414. public string certification { get; set; }
  415. public DateTime release_date { get; set; }
  416. }
  417. internal class Releases
  418. {
  419. public List<Country> countries { get; set; }
  420. }
  421. internal class Backdrop
  422. {
  423. public string file_path { get; set; }
  424. public int width { get; set; }
  425. public int height { get; set; }
  426. public object iso_639_1 { get; set; }
  427. public double aspect_ratio { get; set; }
  428. public double vote_average { get; set; }
  429. public int vote_count { get; set; }
  430. }
  431. internal class Poster
  432. {
  433. public string file_path { get; set; }
  434. public int width { get; set; }
  435. public int height { get; set; }
  436. public string iso_639_1 { get; set; }
  437. public double aspect_ratio { get; set; }
  438. public double vote_average { get; set; }
  439. public int vote_count { get; set; }
  440. }
  441. internal class Images
  442. {
  443. public List<Backdrop> backdrops { get; set; }
  444. public List<Poster> posters { get; set; }
  445. }
  446. internal class Keyword
  447. {
  448. public int id { get; set; }
  449. public string name { get; set; }
  450. }
  451. internal class Keywords
  452. {
  453. public List<Keyword> keywords { get; set; }
  454. }
  455. internal class Youtube
  456. {
  457. public string name { get; set; }
  458. public string size { get; set; }
  459. public string source { get; set; }
  460. }
  461. internal class Trailers
  462. {
  463. public List<object> quicktime { get; set; }
  464. public List<Youtube> youtube { get; set; }
  465. }
  466. internal class CompleteMovieData
  467. {
  468. public bool adult { get; set; }
  469. public string backdrop_path { get; set; }
  470. public BelongsToCollection belongs_to_collection { get; set; }
  471. public int budget { get; set; }
  472. public List<GenreItem> genres { get; set; }
  473. public string homepage { get; set; }
  474. public int id { get; set; }
  475. public string imdb_id { get; set; }
  476. public string original_title { get; set; }
  477. public string overview { get; set; }
  478. public double popularity { get; set; }
  479. public string poster_path { get; set; }
  480. public List<ProductionCompany> production_companies { get; set; }
  481. public List<ProductionCountry> production_countries { get; set; }
  482. public string release_date { get; set; }
  483. public int revenue { get; set; }
  484. public int runtime { get; set; }
  485. public List<SpokenLanguage> spoken_languages { get; set; }
  486. public string status { get; set; }
  487. public string tagline { get; set; }
  488. public string title { get; set; }
  489. public string name { get; set; }
  490. public double vote_average { get; set; }
  491. public int vote_count { get; set; }
  492. public Casts casts { get; set; }
  493. public Releases releases { get; set; }
  494. public Images images { get; set; }
  495. public Keywords keywords { get; set; }
  496. public Trailers trailers { get; set; }
  497. }
  498. public int Order
  499. {
  500. get
  501. {
  502. // After Omdb
  503. return 1;
  504. }
  505. }
  506. public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
  507. {
  508. return _httpClient.GetResponse(new HttpRequestOptions
  509. {
  510. CancellationToken = cancellationToken,
  511. Url = url,
  512. ResourcePool = MovieDbResourcePool
  513. });
  514. }
  515. }
  516. }