MovieDbProvider.cs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Net;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities;
  5. using MediaBrowser.Controller.Entities.Movies;
  6. using MediaBrowser.Controller.Providers;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Logging;
  9. using MediaBrowser.Model.Serialization;
  10. using MediaBrowser.Providers.Savers;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Globalization;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Net;
  17. using System.Text.RegularExpressions;
  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 : BaseMetadataProvider, IDisposable
  26. {
  27. protected static CultureInfo EnUs = new CultureInfo("en-US");
  28. protected readonly IProviderManager ProviderManager;
  29. /// <summary>
  30. /// The movie db
  31. /// </summary>
  32. internal readonly SemaphoreSlim MovieDbResourcePool = new SemaphoreSlim(1, 1);
  33. internal static MovieDbProvider Current { get; private set; }
  34. /// <summary>
  35. /// Gets the json serializer.
  36. /// </summary>
  37. /// <value>The json serializer.</value>
  38. protected IJsonSerializer JsonSerializer { get; private set; }
  39. /// <summary>
  40. /// Gets the HTTP client.
  41. /// </summary>
  42. /// <value>The HTTP client.</value>
  43. protected IHttpClient HttpClient { get; private set; }
  44. /// <summary>
  45. /// Initializes a new instance of the <see cref="MovieDbProvider" /> class.
  46. /// </summary>
  47. /// <param name="logManager">The log manager.</param>
  48. /// <param name="configurationManager">The configuration manager.</param>
  49. /// <param name="jsonSerializer">The json serializer.</param>
  50. /// <param name="httpClient">The HTTP client.</param>
  51. /// <param name="providerManager">The provider manager.</param>
  52. public MovieDbProvider(ILogManager logManager, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IHttpClient httpClient, IProviderManager providerManager)
  53. : base(logManager, configurationManager)
  54. {
  55. JsonSerializer = jsonSerializer;
  56. HttpClient = httpClient;
  57. ProviderManager = providerManager;
  58. Current = this;
  59. }
  60. /// <summary>
  61. /// Releases unmanaged and - optionally - managed resources.
  62. /// </summary>
  63. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  64. protected virtual void Dispose(bool dispose)
  65. {
  66. if (dispose)
  67. {
  68. MovieDbResourcePool.Dispose();
  69. }
  70. }
  71. /// <summary>
  72. /// Gets the priority.
  73. /// </summary>
  74. /// <value>The priority.</value>
  75. public override MetadataProviderPriority Priority
  76. {
  77. get { return MetadataProviderPriority.Third; }
  78. }
  79. /// <summary>
  80. /// Supportses the specified item.
  81. /// </summary>
  82. /// <param name="item">The item.</param>
  83. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  84. public override bool Supports(BaseItem item)
  85. {
  86. var trailer = item as Trailer;
  87. if (trailer != null)
  88. {
  89. return !trailer.IsLocalTrailer;
  90. }
  91. // Don't support local trailers
  92. return item is Movie || item is BoxSet || item is MusicVideo;
  93. }
  94. /// <summary>
  95. /// Gets a value indicating whether [requires internet].
  96. /// </summary>
  97. /// <value><c>true</c> if [requires internet]; otherwise, <c>false</c>.</value>
  98. public override bool RequiresInternet
  99. {
  100. get
  101. {
  102. return true;
  103. }
  104. }
  105. protected override bool RefreshOnVersionChange
  106. {
  107. get
  108. {
  109. return true;
  110. }
  111. }
  112. protected override string ProviderVersion
  113. {
  114. get
  115. {
  116. return "3";
  117. }
  118. }
  119. /// <summary>
  120. /// The _TMDB settings task
  121. /// </summary>
  122. private TmdbSettingsResult _tmdbSettings;
  123. private readonly SemaphoreSlim _tmdbSettingsSemaphore = new SemaphoreSlim(1, 1);
  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. await _tmdbSettingsSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  135. try
  136. {
  137. // Check again in case it got populated while we were waiting.
  138. if (_tmdbSettings != null)
  139. {
  140. return _tmdbSettings;
  141. }
  142. using (var json = await GetMovieDbResponse(new HttpRequestOptions
  143. {
  144. Url = string.Format(TmdbConfigUrl, ApiKey),
  145. CancellationToken = cancellationToken,
  146. AcceptHeader = AcceptHeader
  147. }).ConfigureAwait(false))
  148. {
  149. _tmdbSettings = JsonSerializer.DeserializeFromStream<TmdbSettingsResult>(json);
  150. return _tmdbSettings;
  151. }
  152. }
  153. finally
  154. {
  155. _tmdbSettingsSemaphore.Release();
  156. }
  157. }
  158. private const string TmdbConfigUrl = "http://api.themoviedb.org/3/configuration?api_key={0}";
  159. private const string Search3 = @"http://api.themoviedb.org/3/search/{3}?api_key={1}&query={0}&language={2}";
  160. private const string GetMovieInfo3 = @"http://api.themoviedb.org/3/movie/{0}?api_key={1}&append_to_response=casts,releases,images,keywords,trailers";
  161. private const string GetBoxSetInfo3 = @"http://api.themoviedb.org/3/collection/{0}?api_key={1}&append_to_response=images";
  162. internal static string ApiKey = "f6bd687ffa63cd282b6ff2c6877f2669";
  163. internal static string AcceptHeader = "application/json,image/*";
  164. static readonly Regex[] NameMatches = new[] {
  165. new Regex(@"(?<name>.*)\((?<year>\d{4})\)"), // matches "My Movie (2001)" and gives us the name and the year
  166. new Regex(@"(?<name>.*)(\.(?<year>\d{4})(\.|$)).*$"),
  167. new Regex(@"(?<name>.*)") // last resort matches the whole string as the name
  168. };
  169. protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  170. {
  171. // Boxsets require two passes because we need the children to be refreshed
  172. if (item is BoxSet && string.IsNullOrEmpty(item.GetProviderId(MetadataProviders.Tmdb)))
  173. {
  174. return true;
  175. }
  176. return base.NeedsRefreshInternal(item, providerInfo);
  177. }
  178. protected override bool NeedsRefreshBasedOnCompareDate(BaseItem item, BaseProviderInfo providerInfo)
  179. {
  180. var language = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  181. var path = GetDataFilePath(item, language);
  182. if (!string.IsNullOrEmpty(path))
  183. {
  184. var fileInfo = new FileInfo(path);
  185. if (fileInfo.Exists)
  186. {
  187. return fileInfo.LastWriteTimeUtc > providerInfo.LastRefreshed;
  188. }
  189. return true;
  190. }
  191. return base.NeedsRefreshBasedOnCompareDate(item, providerInfo);
  192. }
  193. /// <summary>
  194. /// Gets the movie data path.
  195. /// </summary>
  196. /// <param name="appPaths">The app paths.</param>
  197. /// <param name="isBoxSet">if set to <c>true</c> [is box set].</param>
  198. /// <param name="tmdbId">The TMDB id.</param>
  199. /// <returns>System.String.</returns>
  200. internal static string GetMovieDataPath(IApplicationPaths appPaths, bool isBoxSet, string tmdbId)
  201. {
  202. var dataPath = isBoxSet ? GetBoxSetsDataPath(appPaths) : GetMoviesDataPath(appPaths);
  203. return Path.Combine(dataPath, tmdbId);
  204. }
  205. internal static string GetMoviesDataPath(IApplicationPaths appPaths)
  206. {
  207. var dataPath = Path.Combine(appPaths.DataPath, "tmdb-movies");
  208. return dataPath;
  209. }
  210. internal static string GetBoxSetsDataPath(IApplicationPaths appPaths)
  211. {
  212. var dataPath = Path.Combine(appPaths.DataPath, "tmdb-collections");
  213. return dataPath;
  214. }
  215. /// <summary>
  216. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  217. /// </summary>
  218. /// <param name="item">The item.</param>
  219. /// <param name="force">if set to <c>true</c> [force].</param>
  220. /// <param name="cancellationToken">The cancellation token</param>
  221. /// <returns>Task{System.Boolean}.</returns>
  222. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  223. {
  224. cancellationToken.ThrowIfCancellationRequested();
  225. var id = item.GetProviderId(MetadataProviders.Tmdb);
  226. if (string.IsNullOrEmpty(id))
  227. {
  228. id = item.GetProviderId(MetadataProviders.Imdb);
  229. }
  230. if (string.IsNullOrEmpty(id))
  231. {
  232. id = await FindId(item, cancellationToken).ConfigureAwait(false);
  233. if (!string.IsNullOrEmpty(id))
  234. {
  235. item.SetProviderId(MetadataProviders.Tmdb, id);
  236. }
  237. }
  238. if (!string.IsNullOrEmpty(id))
  239. {
  240. cancellationToken.ThrowIfCancellationRequested();
  241. await FetchMovieData(item, id, force, cancellationToken).ConfigureAwait(false);
  242. }
  243. SetLastRefreshed(item, DateTime.UtcNow);
  244. return true;
  245. }
  246. /// <summary>
  247. /// Determines whether [has alt meta] [the specified item].
  248. /// </summary>
  249. /// <param name="item">The item.</param>
  250. /// <returns><c>true</c> if [has alt meta] [the specified item]; otherwise, <c>false</c>.</returns>
  251. internal static bool HasAltMeta(BaseItem item)
  252. {
  253. if (item is BoxSet)
  254. {
  255. return item.LocationType == LocationType.FileSystem && item.ResolveArgs.ContainsMetaFileByName("collection.xml");
  256. }
  257. var path = MovieXmlSaver.GetMovieSavePath(item);
  258. if (item.LocationType == LocationType.FileSystem)
  259. {
  260. // If mixed with multiple movies in one folder, resolve args won't have the file system children
  261. return item.ResolveArgs.ContainsMetaFileByName(Path.GetFileName(path)) || File.Exists(path);
  262. }
  263. return false;
  264. }
  265. /// <summary>
  266. /// Parses the name.
  267. /// </summary>
  268. /// <param name="name">The name.</param>
  269. /// <param name="justName">Name of the just.</param>
  270. /// <param name="year">The year.</param>
  271. public static void ParseName(string name, out string justName, out int? year)
  272. {
  273. justName = null;
  274. year = null;
  275. foreach (var re in NameMatches)
  276. {
  277. Match m = re.Match(name);
  278. if (m.Success)
  279. {
  280. justName = m.Groups["name"].Value.Trim();
  281. string y = m.Groups["year"] != null ? m.Groups["year"].Value : null;
  282. int temp;
  283. year = Int32.TryParse(y, out temp) ? temp : (int?)null;
  284. break;
  285. }
  286. }
  287. }
  288. /// <summary>
  289. /// Finds the id.
  290. /// </summary>
  291. /// <param name="item">The item.</param>
  292. /// <param name="cancellationToken">The cancellation token</param>
  293. /// <returns>Task{System.String}.</returns>
  294. public async Task<string> FindId(BaseItem item, CancellationToken cancellationToken)
  295. {
  296. int? yearInName;
  297. string name = item.Name;
  298. ParseName(name, out name, out yearInName);
  299. var year = item.ProductionYear ?? yearInName;
  300. Logger.Info("MovieDbProvider: Finding id for item: " + name);
  301. string language = ConfigurationManager.Configuration.PreferredMetadataLanguage.ToLower();
  302. //if we are a boxset - look at our first child
  303. var boxset = item as BoxSet;
  304. if (boxset != null)
  305. {
  306. // See if any movies have a collection id already
  307. var collId = boxset.Children.Concat(boxset.GetLinkedChildren()).OfType<Video>()
  308. .Select(i => i.GetProviderId(MetadataProviders.TmdbCollection))
  309. .FirstOrDefault(i => i != null);
  310. if (collId != null) return collId;
  311. }
  312. //nope - search for it
  313. var searchType = item is BoxSet ? "collection" : "movie";
  314. var id = await AttemptFindId(name, searchType, year, language, cancellationToken).ConfigureAwait(false);
  315. if (id == null)
  316. {
  317. //try in english if wasn't before
  318. if (language != "en")
  319. {
  320. id = await AttemptFindId(name, searchType, year, "en", cancellationToken).ConfigureAwait(false);
  321. }
  322. else
  323. {
  324. // try with dot and _ turned to space
  325. var originalName = name;
  326. name = name.Replace(",", " ");
  327. name = name.Replace(".", " ");
  328. name = name.Replace("_", " ");
  329. name = name.Replace("-", " ");
  330. // Search again if the new name is different
  331. if (!string.Equals(name, originalName))
  332. {
  333. id = await AttemptFindId(name, searchType, year, language, cancellationToken).ConfigureAwait(false);
  334. if (id == null && language != "en")
  335. {
  336. //one more time, in english
  337. id = await AttemptFindId(name, searchType, year, "en", cancellationToken).ConfigureAwait(false);
  338. }
  339. }
  340. if (id == null && item.LocationType == LocationType.FileSystem)
  341. {
  342. //last resort - try using the actual folder name
  343. var pathName = Path.GetFileName(item.ResolveArgs.Path);
  344. // Only search if it's a name we haven't already tried.
  345. if (!string.Equals(pathName, name, StringComparison.OrdinalIgnoreCase)
  346. && !string.Equals(pathName, originalName, StringComparison.OrdinalIgnoreCase))
  347. {
  348. id = await AttemptFindId(pathName, searchType, year, "en", cancellationToken).ConfigureAwait(false);
  349. }
  350. }
  351. }
  352. }
  353. return id;
  354. }
  355. /// <summary>
  356. /// Attempts the find id.
  357. /// </summary>
  358. /// <param name="name">The name.</param>
  359. /// <param name="type">movie or collection</param>
  360. /// <param name="year">The year.</param>
  361. /// <param name="language">The language.</param>
  362. /// <param name="cancellationToken">The cancellation token</param>
  363. /// <returns>Task{System.String}.</returns>
  364. private async Task<string> AttemptFindId(string name, string type, int? year, string language, CancellationToken cancellationToken)
  365. {
  366. string url3 = string.Format(Search3, UrlEncode(name), ApiKey, language, type);
  367. TmdbMovieSearchResults searchResult = null;
  368. using (Stream json = await GetMovieDbResponse(new HttpRequestOptions
  369. {
  370. Url = url3,
  371. CancellationToken = cancellationToken,
  372. AcceptHeader = AcceptHeader
  373. }).ConfigureAwait(false))
  374. {
  375. searchResult = JsonSerializer.DeserializeFromStream<TmdbMovieSearchResults>(json);
  376. }
  377. if (searchResult != null)
  378. {
  379. foreach (var possible in searchResult.results)
  380. {
  381. string matchedName = possible.title ?? possible.name;
  382. string id = possible.id.ToString(CultureInfo.InvariantCulture);
  383. if (matchedName != null)
  384. {
  385. Logger.Debug("Match " + matchedName + " for " + name);
  386. if (year != null)
  387. {
  388. DateTime r;
  389. //These dates are always in this exact format
  390. if (DateTime.TryParseExact(possible.release_date, "yyyy-MM-dd", EnUs, DateTimeStyles.None, out r))
  391. {
  392. if (Math.Abs(r.Year - year.Value) > 1) // allow a 1 year tolerance on release date
  393. {
  394. Logger.Debug("Result " + matchedName + " released on " + r + " did not match year " + year);
  395. continue;
  396. }
  397. }
  398. }
  399. //matched name and year
  400. return id;
  401. }
  402. }
  403. }
  404. return null;
  405. }
  406. /// <summary>
  407. /// URLs the encode.
  408. /// </summary>
  409. /// <param name="name">The name.</param>
  410. /// <returns>System.String.</returns>
  411. private static string UrlEncode(string name)
  412. {
  413. return WebUtility.UrlEncode(name);
  414. }
  415. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  416. /// <summary>
  417. /// Fetches the movie data.
  418. /// </summary>
  419. /// <param name="item">The item.</param>
  420. /// <param name="id">The id.</param>
  421. /// <param name="isForcedRefresh">if set to <c>true</c> [is forced refresh].</param>
  422. /// <param name="cancellationToken">The cancellation token</param>
  423. /// <returns>Task.</returns>
  424. private async Task FetchMovieData(BaseItem item, string id, bool isForcedRefresh, CancellationToken cancellationToken)
  425. {
  426. // Id could be ImdbId or TmdbId
  427. var language = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  428. var dataFilePath = GetDataFilePath(item, language);
  429. if (string.IsNullOrEmpty(dataFilePath) || !File.Exists(dataFilePath))
  430. {
  431. var isBoxSet = item is BoxSet;
  432. var mainResult = await FetchMainResult(id, isBoxSet, language, cancellationToken).ConfigureAwait(false);
  433. if (mainResult == null) return;
  434. var movieDataPath = GetMovieDataPath(ConfigurationManager.ApplicationPaths, isBoxSet, mainResult.id.ToString(_usCulture));
  435. dataFilePath = Path.Combine(movieDataPath, language + ".json");
  436. var directory = Path.GetDirectoryName(dataFilePath);
  437. Directory.CreateDirectory(directory);
  438. JsonSerializer.SerializeToFile(mainResult, dataFilePath);
  439. // Now get the language-less version
  440. mainResult = await FetchMainResult(id, isBoxSet, null, cancellationToken).ConfigureAwait(false);
  441. dataFilePath = Path.Combine(movieDataPath, "default.json");
  442. JsonSerializer.SerializeToFile(mainResult, dataFilePath);
  443. }
  444. if (isForcedRefresh || ConfigurationManager.Configuration.EnableTmdbUpdates || !HasAltMeta(item))
  445. {
  446. dataFilePath = GetDataFilePath(item, language);
  447. var mainResult = JsonSerializer.DeserializeFromFile<CompleteMovieData>(dataFilePath);
  448. ProcessMainInfo(item, mainResult);
  449. }
  450. }
  451. /// <summary>
  452. /// Downloads the movie info.
  453. /// </summary>
  454. /// <param name="id">The id.</param>
  455. /// <param name="isBoxSet">if set to <c>true</c> [is box set].</param>
  456. /// <param name="dataPath">The data path.</param>
  457. /// <param name="cancellationToken">The cancellation token.</param>
  458. /// <returns>Task.</returns>
  459. internal async Task DownloadMovieInfo(string id, bool isBoxSet, string dataPath, CancellationToken cancellationToken)
  460. {
  461. var language = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  462. var mainResult = await FetchMainResult(id, isBoxSet, language, cancellationToken).ConfigureAwait(false);
  463. if (mainResult == null) return;
  464. var dataFilePath = Path.Combine(dataPath, language + ".json");
  465. Directory.CreateDirectory(dataPath);
  466. JsonSerializer.SerializeToFile(mainResult, dataFilePath);
  467. // Now get the language-less version
  468. mainResult = await FetchMainResult(id, isBoxSet, null, cancellationToken).ConfigureAwait(false);
  469. dataFilePath = Path.Combine(dataPath, "default.json");
  470. JsonSerializer.SerializeToFile(mainResult, dataFilePath);
  471. }
  472. /// <summary>
  473. /// Gets the data file path.
  474. /// </summary>
  475. /// <param name="item">The item.</param>
  476. /// <param name="language">The language.</param>
  477. /// <returns>System.String.</returns>
  478. internal string GetDataFilePath(BaseItem item, string language)
  479. {
  480. var id = item.GetProviderId(MetadataProviders.Tmdb);
  481. if (string.IsNullOrEmpty(id))
  482. {
  483. return null;
  484. }
  485. var path = GetMovieDataPath(ConfigurationManager.ApplicationPaths, item is BoxSet, id);
  486. path = Path.Combine(path, language + ".json");
  487. return path;
  488. }
  489. /// <summary>
  490. /// Fetches the main result.
  491. /// </summary>
  492. /// <param name="id">The id.</param>
  493. /// <param name="isBoxSet">if set to <c>true</c> [is box set].</param>
  494. /// <param name="language">The language.</param>
  495. /// <param name="cancellationToken">The cancellation token</param>
  496. /// <returns>Task{CompleteMovieData}.</returns>
  497. private async Task<CompleteMovieData> FetchMainResult(string id, bool isBoxSet, string language, CancellationToken cancellationToken)
  498. {
  499. var baseUrl = isBoxSet ? GetBoxSetInfo3 : GetMovieInfo3;
  500. var url = string.Format(baseUrl, id, ApiKey);
  501. if (!string.IsNullOrEmpty(language))
  502. {
  503. url += "&language=" + language;
  504. }
  505. CompleteMovieData mainResult;
  506. cancellationToken.ThrowIfCancellationRequested();
  507. using (var json = await GetMovieDbResponse(new HttpRequestOptions
  508. {
  509. Url = url,
  510. CancellationToken = cancellationToken,
  511. AcceptHeader = AcceptHeader
  512. }).ConfigureAwait(false))
  513. {
  514. mainResult = JsonSerializer.DeserializeFromStream<CompleteMovieData>(json);
  515. }
  516. cancellationToken.ThrowIfCancellationRequested();
  517. if (mainResult != null && string.IsNullOrEmpty(mainResult.overview))
  518. {
  519. if (!string.IsNullOrEmpty(language) && !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
  520. {
  521. Logger.Info("MovieDbProvider couldn't find meta for language " + language + ". Trying English...");
  522. url = string.Format(baseUrl, id, ApiKey, "en");
  523. using (var json = await GetMovieDbResponse(new HttpRequestOptions
  524. {
  525. Url = url,
  526. CancellationToken = cancellationToken,
  527. AcceptHeader = AcceptHeader
  528. }).ConfigureAwait(false))
  529. {
  530. mainResult = JsonSerializer.DeserializeFromStream<CompleteMovieData>(json);
  531. }
  532. if (String.IsNullOrEmpty(mainResult.overview))
  533. {
  534. Logger.Error("MovieDbProvider - Unable to find information for (id:" + id + ")");
  535. return null;
  536. }
  537. }
  538. }
  539. return mainResult;
  540. }
  541. /// <summary>
  542. /// Processes the main info.
  543. /// </summary>
  544. /// <param name="movie">The movie.</param>
  545. /// <param name="movieData">The movie data.</param>
  546. private void ProcessMainInfo(BaseItem movie, CompleteMovieData movieData)
  547. {
  548. if (movie != null && movieData != null)
  549. {
  550. if (!movie.LockedFields.Contains(MetadataFields.Name))
  551. {
  552. movie.Name = movieData.title ?? movieData.original_title ?? movieData.name ?? movie.Name;
  553. }
  554. if (!movie.LockedFields.Contains(MetadataFields.Overview))
  555. {
  556. movie.Overview = WebUtility.HtmlDecode(movieData.overview);
  557. movie.Overview = movie.Overview != null ? movie.Overview.Replace("\n\n", "\n") : null;
  558. }
  559. movie.HomePageUrl = movieData.homepage;
  560. movie.Budget = movieData.budget;
  561. movie.Revenue = movieData.revenue;
  562. if (!string.IsNullOrEmpty(movieData.tagline))
  563. {
  564. movie.Taglines.Clear();
  565. movie.AddTagline(movieData.tagline);
  566. }
  567. movie.SetProviderId(MetadataProviders.Imdb, movieData.imdb_id);
  568. if (movieData.belongs_to_collection != null)
  569. {
  570. movie.SetProviderId(MetadataProviders.TmdbCollection,
  571. movieData.belongs_to_collection.id.ToString(CultureInfo.InvariantCulture));
  572. var movieItem = movie as Movie;
  573. if (movieItem != null)
  574. {
  575. movieItem.TmdbCollectionName = movieData.belongs_to_collection.name;
  576. }
  577. }
  578. else
  579. {
  580. movie.SetProviderId(MetadataProviders.TmdbCollection, null); // clear out any old entry
  581. }
  582. float rating;
  583. string voteAvg = movieData.vote_average.ToString(CultureInfo.InvariantCulture);
  584. // tmdb appears to have unified their numbers to always report "7.3" regardless of country
  585. // so I removed the culture-specific processing here because it was not working for other countries -ebr
  586. // Movies get this from imdb
  587. if (movie is BoxSet && float.TryParse(voteAvg, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out rating))
  588. {
  589. movie.CommunityRating = rating;
  590. }
  591. // Movies get this from imdb
  592. if (movie is BoxSet)
  593. {
  594. movie.VoteCount = movieData.vote_count;
  595. }
  596. //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
  597. if (movieData.releases != null && movieData.releases.countries != null)
  598. {
  599. var ourRelease = movieData.releases.countries.FirstOrDefault(c => c.iso_3166_1.Equals(ConfigurationManager.Configuration.MetadataCountryCode, StringComparison.OrdinalIgnoreCase)) ?? new Country();
  600. var usRelease = movieData.releases.countries.FirstOrDefault(c => c.iso_3166_1.Equals("US", StringComparison.OrdinalIgnoreCase)) ?? new Country();
  601. var minimunRelease = movieData.releases.countries.OrderBy(c => c.release_date).FirstOrDefault() ?? new Country();
  602. if (!movie.LockedFields.Contains(MetadataFields.OfficialRating))
  603. {
  604. var ratingPrefix = ConfigurationManager.Configuration.MetadataCountryCode.Equals("us", StringComparison.OrdinalIgnoreCase) ? "" : ConfigurationManager.Configuration.MetadataCountryCode + "-";
  605. movie.OfficialRating = !string.IsNullOrEmpty(ourRelease.certification)
  606. ? ratingPrefix + ourRelease.certification
  607. : !string.IsNullOrEmpty(usRelease.certification)
  608. ? usRelease.certification
  609. : !string.IsNullOrEmpty(minimunRelease.certification)
  610. ? minimunRelease.iso_3166_1 + "-" + minimunRelease.certification
  611. : null;
  612. }
  613. if (ourRelease.release_date != default(DateTime))
  614. {
  615. if (ourRelease.release_date.Year != 1)
  616. {
  617. movie.PremiereDate = ourRelease.release_date.ToUniversalTime();
  618. movie.ProductionYear = ourRelease.release_date.Year;
  619. }
  620. }
  621. else if (usRelease.release_date != default(DateTime))
  622. {
  623. if (usRelease.release_date.Year != 1)
  624. {
  625. movie.PremiereDate = usRelease.release_date.ToUniversalTime();
  626. movie.ProductionYear = usRelease.release_date.Year;
  627. }
  628. }
  629. else if (minimunRelease.release_date != default(DateTime))
  630. {
  631. if (minimunRelease.release_date.Year != 1)
  632. {
  633. movie.PremiereDate = minimunRelease.release_date.ToUniversalTime();
  634. movie.ProductionYear = minimunRelease.release_date.Year;
  635. }
  636. }
  637. }
  638. else
  639. {
  640. if (movieData.release_date.Year != 1)
  641. {
  642. //no specific country release info at all
  643. movie.PremiereDate = movieData.release_date.ToUniversalTime();
  644. movie.ProductionYear = movieData.release_date.Year;
  645. }
  646. }
  647. //if that didn't find a rating and we are a boxset, use the one from our first child
  648. if (movie.OfficialRating == null && movie is BoxSet && !movie.LockedFields.Contains(MetadataFields.OfficialRating))
  649. {
  650. var boxset = movie as BoxSet;
  651. Logger.Info("MovieDbProvider - Using rating of first child of boxset...");
  652. var firstChild = boxset.Children.Concat(boxset.GetLinkedChildren()).FirstOrDefault();
  653. boxset.OfficialRating = firstChild != null ? firstChild.OfficialRating : null;
  654. }
  655. if (movieData.runtime > 0)
  656. movie.OriginalRunTimeTicks = TimeSpan.FromMinutes(movieData.runtime).Ticks;
  657. //studios
  658. if (movieData.production_companies != null && !movie.LockedFields.Contains(MetadataFields.Studios))
  659. {
  660. movie.Studios.Clear();
  661. foreach (var studio in movieData.production_companies.Select(c => c.name))
  662. {
  663. movie.AddStudio(studio);
  664. }
  665. }
  666. // genres
  667. // Movies get this from imdb
  668. if (movieData.genres != null && !movie.LockedFields.Contains(MetadataFields.Genres) && movie is BoxSet)
  669. {
  670. movie.Genres.Clear();
  671. foreach (var genre in movieData.genres.Select(g => g.name))
  672. {
  673. movie.AddGenre(genre);
  674. }
  675. }
  676. if (!movie.LockedFields.Contains(MetadataFields.Cast))
  677. {
  678. movie.People.Clear();
  679. //Actors, Directors, Writers - all in People
  680. //actors come from cast
  681. if (movieData.casts != null && movieData.casts.cast != null)
  682. {
  683. foreach (var actor in movieData.casts.cast.OrderBy(a => a.order)) movie.AddPerson(new PersonInfo { Name = actor.name.Trim(), Role = actor.character, Type = PersonType.Actor });
  684. }
  685. //and the rest from crew
  686. if (movieData.casts != null && movieData.casts.crew != null)
  687. {
  688. foreach (var person in movieData.casts.crew) movie.AddPerson(new PersonInfo { Name = person.name.Trim(), Role = person.job, Type = person.department });
  689. }
  690. }
  691. if (movieData.keywords != null && movieData.keywords.keywords != null && !movie.LockedFields.Contains(MetadataFields.Tags))
  692. {
  693. movie.Tags = movieData.keywords.keywords.Select(i => i.name).ToList();
  694. }
  695. if (movieData.trailers != null && movieData.trailers.youtube != null &&
  696. movieData.trailers.youtube.Count > 0)
  697. {
  698. movie.RemoteTrailers = movieData.trailers.youtube.Select(i => new MediaUrl
  699. {
  700. Url = string.Format("http://www.youtube.com/watch?v={0}", i.source),
  701. IsDirectLink = false,
  702. Name = i.name,
  703. VideoSize = string.Equals("hd", i.size, StringComparison.OrdinalIgnoreCase) ? VideoSize.HighDefinition : VideoSize.StandardDefinition
  704. }).ToList();
  705. }
  706. }
  707. }
  708. private DateTime _lastRequestDate = DateTime.MinValue;
  709. /// <summary>
  710. /// Gets the movie db response.
  711. /// </summary>
  712. internal async Task<Stream> GetMovieDbResponse(HttpRequestOptions options)
  713. {
  714. var cancellationToken = options.CancellationToken;
  715. await MovieDbResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  716. try
  717. {
  718. // Limit to three requests per second
  719. var diff = 340 - (DateTime.Now - _lastRequestDate).TotalMilliseconds;
  720. if (diff > 0)
  721. {
  722. await Task.Delay(Convert.ToInt32(diff), cancellationToken).ConfigureAwait(false);
  723. }
  724. _lastRequestDate = DateTime.Now;
  725. return await HttpClient.Get(options).ConfigureAwait(false);
  726. }
  727. finally
  728. {
  729. _lastRequestDate = DateTime.Now;
  730. MovieDbResourcePool.Release();
  731. }
  732. }
  733. public void Dispose()
  734. {
  735. Dispose(true);
  736. }
  737. /// <summary>
  738. /// Class TmdbTitle
  739. /// </summary>
  740. internal class TmdbTitle
  741. {
  742. /// <summary>
  743. /// Gets or sets the iso_3166_1.
  744. /// </summary>
  745. /// <value>The iso_3166_1.</value>
  746. public string iso_3166_1 { get; set; }
  747. /// <summary>
  748. /// Gets or sets the title.
  749. /// </summary>
  750. /// <value>The title.</value>
  751. public string title { get; set; }
  752. }
  753. /// <summary>
  754. /// Class TmdbAltTitleResults
  755. /// </summary>
  756. internal class TmdbAltTitleResults
  757. {
  758. /// <summary>
  759. /// Gets or sets the id.
  760. /// </summary>
  761. /// <value>The id.</value>
  762. public int id { get; set; }
  763. /// <summary>
  764. /// Gets or sets the titles.
  765. /// </summary>
  766. /// <value>The titles.</value>
  767. public List<TmdbTitle> titles { get; set; }
  768. }
  769. /// <summary>
  770. /// Class TmdbMovieSearchResult
  771. /// </summary>
  772. internal class TmdbMovieSearchResult
  773. {
  774. /// <summary>
  775. /// Gets or sets a value indicating whether this <see cref="TmdbMovieSearchResult" /> is adult.
  776. /// </summary>
  777. /// <value><c>true</c> if adult; otherwise, <c>false</c>.</value>
  778. public bool adult { get; set; }
  779. /// <summary>
  780. /// Gets or sets the backdrop_path.
  781. /// </summary>
  782. /// <value>The backdrop_path.</value>
  783. public string backdrop_path { get; set; }
  784. /// <summary>
  785. /// Gets or sets the id.
  786. /// </summary>
  787. /// <value>The id.</value>
  788. public int id { get; set; }
  789. /// <summary>
  790. /// Gets or sets the original_title.
  791. /// </summary>
  792. /// <value>The original_title.</value>
  793. public string original_title { get; set; }
  794. /// <summary>
  795. /// Gets or sets the release_date.
  796. /// </summary>
  797. /// <value>The release_date.</value>
  798. public string release_date { get; set; }
  799. /// <summary>
  800. /// Gets or sets the poster_path.
  801. /// </summary>
  802. /// <value>The poster_path.</value>
  803. public string poster_path { get; set; }
  804. /// <summary>
  805. /// Gets or sets the popularity.
  806. /// </summary>
  807. /// <value>The popularity.</value>
  808. public double popularity { get; set; }
  809. /// <summary>
  810. /// Gets or sets the title.
  811. /// </summary>
  812. /// <value>The title.</value>
  813. public string title { get; set; }
  814. /// <summary>
  815. /// Gets or sets the vote_average.
  816. /// </summary>
  817. /// <value>The vote_average.</value>
  818. public double vote_average { get; set; }
  819. /// <summary>
  820. /// For collection search results
  821. /// </summary>
  822. public string name { get; set; }
  823. /// <summary>
  824. /// Gets or sets the vote_count.
  825. /// </summary>
  826. /// <value>The vote_count.</value>
  827. public int vote_count { get; set; }
  828. }
  829. /// <summary>
  830. /// Class TmdbMovieSearchResults
  831. /// </summary>
  832. internal class TmdbMovieSearchResults
  833. {
  834. /// <summary>
  835. /// Gets or sets the page.
  836. /// </summary>
  837. /// <value>The page.</value>
  838. public int page { get; set; }
  839. /// <summary>
  840. /// Gets or sets the results.
  841. /// </summary>
  842. /// <value>The results.</value>
  843. public List<TmdbMovieSearchResult> results { get; set; }
  844. /// <summary>
  845. /// Gets or sets the total_pages.
  846. /// </summary>
  847. /// <value>The total_pages.</value>
  848. public int total_pages { get; set; }
  849. /// <summary>
  850. /// Gets or sets the total_results.
  851. /// </summary>
  852. /// <value>The total_results.</value>
  853. public int total_results { get; set; }
  854. }
  855. internal class BelongsToCollection
  856. {
  857. public int id { get; set; }
  858. public string name { get; set; }
  859. public string poster_path { get; set; }
  860. public string backdrop_path { get; set; }
  861. }
  862. internal class GenreItem
  863. {
  864. public int id { get; set; }
  865. public string name { get; set; }
  866. }
  867. internal class ProductionCompany
  868. {
  869. public string name { get; set; }
  870. public int id { get; set; }
  871. }
  872. internal class ProductionCountry
  873. {
  874. public string iso_3166_1 { get; set; }
  875. public string name { get; set; }
  876. }
  877. internal class SpokenLanguage
  878. {
  879. public string iso_639_1 { get; set; }
  880. public string name { get; set; }
  881. }
  882. internal class Cast
  883. {
  884. public int id { get; set; }
  885. public string name { get; set; }
  886. public string character { get; set; }
  887. public int order { get; set; }
  888. public int cast_id { get; set; }
  889. public string profile_path { get; set; }
  890. }
  891. internal class Crew
  892. {
  893. public int id { get; set; }
  894. public string name { get; set; }
  895. public string department { get; set; }
  896. public string job { get; set; }
  897. public string profile_path { get; set; }
  898. }
  899. internal class Casts
  900. {
  901. public List<Cast> cast { get; set; }
  902. public List<Crew> crew { get; set; }
  903. }
  904. internal class Country
  905. {
  906. public string iso_3166_1 { get; set; }
  907. public string certification { get; set; }
  908. public DateTime release_date { get; set; }
  909. }
  910. internal class Releases
  911. {
  912. public List<Country> countries { get; set; }
  913. }
  914. internal class Backdrop
  915. {
  916. public string file_path { get; set; }
  917. public int width { get; set; }
  918. public int height { get; set; }
  919. public object iso_639_1 { get; set; }
  920. public double aspect_ratio { get; set; }
  921. public double vote_average { get; set; }
  922. public int vote_count { get; set; }
  923. }
  924. internal class Poster
  925. {
  926. public string file_path { get; set; }
  927. public int width { get; set; }
  928. public int height { get; set; }
  929. public string iso_639_1 { get; set; }
  930. public double aspect_ratio { get; set; }
  931. public double vote_average { get; set; }
  932. public int vote_count { get; set; }
  933. }
  934. internal class Images
  935. {
  936. public List<Backdrop> backdrops { get; set; }
  937. public List<Poster> posters { get; set; }
  938. }
  939. internal class Keyword
  940. {
  941. public int id { get; set; }
  942. public string name { get; set; }
  943. }
  944. internal class Keywords
  945. {
  946. public List<Keyword> keywords { get; set; }
  947. }
  948. internal class Youtube
  949. {
  950. public string name { get; set; }
  951. public string size { get; set; }
  952. public string source { get; set; }
  953. }
  954. internal class Trailers
  955. {
  956. public List<object> quicktime { get; set; }
  957. public List<Youtube> youtube { get; set; }
  958. }
  959. internal class CompleteMovieData
  960. {
  961. public bool adult { get; set; }
  962. public string backdrop_path { get; set; }
  963. public BelongsToCollection belongs_to_collection { get; set; }
  964. public int budget { get; set; }
  965. public List<GenreItem> genres { get; set; }
  966. public string homepage { get; set; }
  967. public int id { get; set; }
  968. public string imdb_id { get; set; }
  969. public string original_title { get; set; }
  970. public string overview { get; set; }
  971. public double popularity { get; set; }
  972. public string poster_path { get; set; }
  973. public List<ProductionCompany> production_companies { get; set; }
  974. public List<ProductionCountry> production_countries { get; set; }
  975. public DateTime release_date { get; set; }
  976. public int revenue { get; set; }
  977. public int runtime { get; set; }
  978. public List<SpokenLanguage> spoken_languages { get; set; }
  979. public string status { get; set; }
  980. public string tagline { get; set; }
  981. public string title { get; set; }
  982. public string name { get; set; }
  983. public double vote_average { get; set; }
  984. public int vote_count { get; set; }
  985. public Casts casts { get; set; }
  986. public Releases releases { get; set; }
  987. public Images images { get; set; }
  988. public Keywords keywords { get; set; }
  989. public Trailers trailers { get; set; }
  990. }
  991. internal class TmdbImageSettings
  992. {
  993. public List<string> backdrop_sizes { get; set; }
  994. public string base_url { get; set; }
  995. public List<string> poster_sizes { get; set; }
  996. public List<string> profile_sizes { get; set; }
  997. }
  998. internal class TmdbSettingsResult
  999. {
  1000. public TmdbImageSettings images { get; set; }
  1001. }
  1002. }
  1003. }