MovieDbProvider.cs 22 KB

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