MovieDbProvider.cs 23 KB

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