MovieDbProvider.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  1. using MediaBrowser.Common.Extensions;
  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 System;
  11. using System.Collections.Generic;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Net;
  16. using System.Text;
  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. private 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 "2";
  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. // Check again in case it got populated while we were waiting.
  136. if (_tmdbSettings != null)
  137. {
  138. _tmdbSettingsSemaphore.Release();
  139. return _tmdbSettings;
  140. }
  141. try
  142. {
  143. using (var json = await GetMovieDbResponse(new HttpRequestOptions
  144. {
  145. Url = string.Format(TmdbConfigUrl, ApiKey),
  146. CancellationToken = cancellationToken,
  147. AcceptHeader = AcceptHeader
  148. }).ConfigureAwait(false))
  149. {
  150. _tmdbSettings = JsonSerializer.DeserializeFromStream<TmdbSettingsResult>(json);
  151. return _tmdbSettings;
  152. }
  153. }
  154. finally
  155. {
  156. _tmdbSettingsSemaphore.Release();
  157. }
  158. }
  159. private const string TmdbConfigUrl = "http://api.themoviedb.org/3/configuration?api_key={0}";
  160. private const string Search3 = @"http://api.themoviedb.org/3/search/movie?api_key={1}&query={0}&language={2}";
  161. private const string AltTitleSearch = @"http://api.themoviedb.org/3/movie/{0}/alternative_titles?api_key={1}&country={2}";
  162. private const string GetMovieInfo3 = @"http://api.themoviedb.org/3/movie/{0}?api_key={1}&language={2}&append_to_response=casts,releases,images,keywords";
  163. private const string GetBoxSetInfo3 = @"http://api.themoviedb.org/3/collection/{0}?api_key={1}&language={2}&append_to_response=images";
  164. internal static string ApiKey = "f6bd687ffa63cd282b6ff2c6877f2669";
  165. internal static string AcceptHeader = "application/json,image/*";
  166. static readonly Regex[] NameMatches = new[] {
  167. new Regex(@"(?<name>.*)\((?<year>\d{4})\)"), // matches "My Movie (2001)" and gives us the name and the year
  168. new Regex(@"(?<name>.*)") // last resort matches the whole string as the name
  169. };
  170. public const string AltMetaFileName = "movie.xml";
  171. protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  172. {
  173. if (HasAltMeta(item))
  174. return false; //never refresh if has meta from other source
  175. return base.NeedsRefreshInternal(item, providerInfo);
  176. }
  177. /// <summary>
  178. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  179. /// </summary>
  180. /// <param name="item">The item.</param>
  181. /// <param name="force">if set to <c>true</c> [force].</param>
  182. /// <param name="cancellationToken">The cancellation token</param>
  183. /// <returns>Task{System.Boolean}.</returns>
  184. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  185. {
  186. cancellationToken.ThrowIfCancellationRequested();
  187. await FetchMovieData(item, cancellationToken).ConfigureAwait(false);
  188. SetLastRefreshed(item, DateTime.UtcNow);
  189. return true;
  190. }
  191. /// <summary>
  192. /// Determines whether [has alt meta] [the specified item].
  193. /// </summary>
  194. /// <param name="item">The item.</param>
  195. /// <returns><c>true</c> if [has alt meta] [the specified item]; otherwise, <c>false</c>.</returns>
  196. private bool HasAltMeta(BaseItem item)
  197. {
  198. return item.LocationType == LocationType.FileSystem && item.ResolveArgs.ContainsMetaFileByName(AltMetaFileName);
  199. }
  200. /// <summary>
  201. /// Fetches the movie data.
  202. /// </summary>
  203. /// <param name="item">The item.</param>
  204. /// <param name="cancellationToken"></param>
  205. /// <returns>Task.</returns>
  206. private async Task FetchMovieData(BaseItem item, CancellationToken cancellationToken)
  207. {
  208. string id = item.GetProviderId(MetadataProviders.Tmdb) ?? await FindId(item, item.ProductionYear, cancellationToken).ConfigureAwait(false);
  209. if (id != null)
  210. {
  211. Logger.Debug("MovieDbProvider - getting movie info with id: " + id);
  212. cancellationToken.ThrowIfCancellationRequested();
  213. await FetchMovieData(item, id, cancellationToken).ConfigureAwait(false);
  214. }
  215. else
  216. {
  217. Logger.Info("MovieDBProvider could not find " + item.Name + ". Check name on themoviedb.org.");
  218. }
  219. }
  220. /// <summary>
  221. /// Parses the name.
  222. /// </summary>
  223. /// <param name="name">The name.</param>
  224. /// <param name="justName">Name of the just.</param>
  225. /// <param name="year">The year.</param>
  226. protected void ParseName(string name, out string justName, out int? year)
  227. {
  228. justName = null;
  229. year = null;
  230. foreach (var re in NameMatches)
  231. {
  232. Match m = re.Match(name);
  233. if (m.Success)
  234. {
  235. justName = m.Groups["name"].Value.Trim();
  236. string y = m.Groups["year"] != null ? m.Groups["year"].Value : null;
  237. int temp;
  238. year = Int32.TryParse(y, out temp) ? temp : (int?)null;
  239. break;
  240. }
  241. }
  242. }
  243. /// <summary>
  244. /// Finds the id.
  245. /// </summary>
  246. /// <param name="item">The item.</param>
  247. /// <param name="productionYear">The production year.</param>
  248. /// <param name="cancellationToken">The cancellation token</param>
  249. /// <returns>Task{System.String}.</returns>
  250. public async Task<string> FindId(BaseItem item, int? productionYear, CancellationToken cancellationToken)
  251. {
  252. string id = null;
  253. if (item.LocationType == LocationType.FileSystem)
  254. {
  255. string justName = item.Path != null ? item.Path.Substring(item.Path.LastIndexOf(Path.DirectorySeparatorChar)) : string.Empty;
  256. id = justName.GetAttributeValue("tmdbid");
  257. if (id != null)
  258. {
  259. Logger.Debug("Using tmdb id specified in path.");
  260. return id;
  261. }
  262. }
  263. int? year;
  264. string name = item.Name;
  265. ParseName(name, out name, out year);
  266. if (year == null && productionYear != null)
  267. {
  268. year = productionYear;
  269. }
  270. Logger.Info("MovieDbProvider: Finding id for movie: " + name);
  271. string language = ConfigurationManager.Configuration.PreferredMetadataLanguage.ToLower();
  272. //if we are a boxset - look at our first child
  273. var boxset = item as BoxSet;
  274. if (boxset != null)
  275. {
  276. var firstChild = boxset.Children.FirstOrDefault();
  277. if (firstChild != null)
  278. {
  279. Logger.Debug("MovieDbProvider - Attempting to find boxset ID from: " + firstChild.Name);
  280. string childName;
  281. int? childYear;
  282. ParseName(firstChild.Name, out childName, out childYear);
  283. id = await GetBoxsetIdFromMovie(childName, childYear, language, cancellationToken).ConfigureAwait(false);
  284. if (id != null)
  285. {
  286. Logger.Info("MovieDbProvider - Found Boxset ID: " + id);
  287. }
  288. }
  289. return id;
  290. }
  291. //nope - search for it
  292. id = await AttemptFindId(name, year, language, cancellationToken).ConfigureAwait(false);
  293. if (id == null)
  294. {
  295. //try in english if wasn't before
  296. if (language != "en")
  297. {
  298. id = await AttemptFindId(name, year, "en", cancellationToken).ConfigureAwait(false);
  299. }
  300. else
  301. {
  302. // try with dot and _ turned to space
  303. var originalName = name;
  304. name = name.Replace(",", " ");
  305. name = name.Replace(".", " ");
  306. name = name.Replace("_", " ");
  307. name = name.Replace("-", "");
  308. // Search again if the new name is different
  309. if (!string.Equals(name, originalName))
  310. {
  311. id = await AttemptFindId(name, year, language, cancellationToken).ConfigureAwait(false);
  312. if (id == null && language != "en")
  313. {
  314. //one more time, in english
  315. id = await AttemptFindId(name, year, "en", cancellationToken).ConfigureAwait(false);
  316. }
  317. }
  318. if (id == null && item.LocationType == LocationType.FileSystem)
  319. {
  320. //last resort - try using the actual folder name
  321. var pathName = Path.GetFileName(item.ResolveArgs.Path);
  322. // Only search if it's a name we haven't already tried.
  323. if (!string.Equals(pathName, name, StringComparison.OrdinalIgnoreCase)
  324. && !string.Equals(pathName, originalName, StringComparison.OrdinalIgnoreCase))
  325. {
  326. id = await AttemptFindId(pathName, year, "en", cancellationToken).ConfigureAwait(false);
  327. }
  328. }
  329. }
  330. }
  331. return id;
  332. }
  333. /// <summary>
  334. /// Attempts the find id.
  335. /// </summary>
  336. /// <param name="name">The name.</param>
  337. /// <param name="year">The year.</param>
  338. /// <param name="language">The language.</param>
  339. /// <param name="cancellationToken">The cancellation token</param>
  340. /// <returns>Task{System.String}.</returns>
  341. public virtual async Task<string> AttemptFindId(string name, int? year, string language, CancellationToken cancellationToken)
  342. {
  343. string url3 = string.Format(Search3, UrlEncode(name), ApiKey, language);
  344. TmdbMovieSearchResults searchResult = null;
  345. using (Stream json = await GetMovieDbResponse(new HttpRequestOptions
  346. {
  347. Url = url3,
  348. CancellationToken = cancellationToken,
  349. AcceptHeader = AcceptHeader
  350. }).ConfigureAwait(false))
  351. {
  352. searchResult = JsonSerializer.DeserializeFromStream<TmdbMovieSearchResults>(json);
  353. }
  354. if (searchResult == null || searchResult.results.Count == 0)
  355. {
  356. //try replacing numbers
  357. foreach (var pair in ReplaceStartNumbers)
  358. {
  359. if (name.StartsWith(pair.Key))
  360. {
  361. name = name.Remove(0, pair.Key.Length);
  362. name = pair.Value + name;
  363. }
  364. }
  365. foreach (var pair in ReplaceEndNumbers)
  366. {
  367. if (name.EndsWith(pair.Key))
  368. {
  369. name = name.Remove(name.IndexOf(pair.Key), pair.Key.Length);
  370. name = name + pair.Value;
  371. }
  372. }
  373. Logger.Info("MovieDBProvider - No results. Trying replacement numbers: " + name);
  374. url3 = string.Format(Search3, UrlEncode(name), ApiKey, language);
  375. using (var json = await GetMovieDbResponse(new HttpRequestOptions
  376. {
  377. Url = url3,
  378. CancellationToken = cancellationToken,
  379. AcceptHeader = AcceptHeader
  380. }).ConfigureAwait(false))
  381. {
  382. searchResult = JsonSerializer.DeserializeFromStream<TmdbMovieSearchResults>(json);
  383. }
  384. }
  385. if (searchResult != null)
  386. {
  387. string compName = GetComparableName(name, Logger);
  388. foreach (var possible in searchResult.results)
  389. {
  390. string matchedName = null;
  391. string id = possible.id.ToString(CultureInfo.InvariantCulture);
  392. string n = possible.title;
  393. if (GetComparableName(n, Logger) == compName)
  394. {
  395. matchedName = n;
  396. }
  397. else
  398. {
  399. n = possible.original_title;
  400. if (GetComparableName(n, Logger) == compName)
  401. {
  402. matchedName = n;
  403. }
  404. }
  405. Logger.Debug("MovieDbProvider - " + compName + " didn't match " + n);
  406. //if main title matches we don't have to look for alternatives
  407. if (matchedName == null)
  408. {
  409. //that title didn't match - look for alternatives
  410. url3 = string.Format(AltTitleSearch, id, ApiKey, ConfigurationManager.Configuration.MetadataCountryCode);
  411. using (var json = await GetMovieDbResponse(new HttpRequestOptions
  412. {
  413. Url = url3,
  414. CancellationToken = cancellationToken,
  415. AcceptHeader = AcceptHeader
  416. }).ConfigureAwait(false))
  417. {
  418. var response = JsonSerializer.DeserializeFromStream<TmdbAltTitleResults>(json);
  419. if (response != null && response.titles != null)
  420. {
  421. foreach (var title in response.titles)
  422. {
  423. var t = GetComparableName(title.title, Logger);
  424. if (t == compName)
  425. {
  426. Logger.Debug("MovieDbProvider - " + compName +
  427. " matched " + t);
  428. matchedName = t;
  429. break;
  430. }
  431. Logger.Debug("MovieDbProvider - " + compName +
  432. " did not match " + t);
  433. }
  434. }
  435. }
  436. }
  437. if (matchedName != null)
  438. {
  439. Logger.Debug("Match " + matchedName + " for " + name);
  440. if (year != null)
  441. {
  442. DateTime r;
  443. //These dates are always in this exact format
  444. if (DateTime.TryParseExact(possible.release_date, "yyyy-MM-dd", EnUs, DateTimeStyles.None, out r))
  445. {
  446. if (Math.Abs(r.Year - year.Value) > 1) // allow a 1 year tolerance on release date
  447. {
  448. Logger.Debug("Result " + matchedName + " released on " + r + " did not match year " + year);
  449. continue;
  450. }
  451. }
  452. }
  453. //matched name and year
  454. return id;
  455. }
  456. }
  457. }
  458. return null;
  459. }
  460. /// <summary>
  461. /// URLs the encode.
  462. /// </summary>
  463. /// <param name="name">The name.</param>
  464. /// <returns>System.String.</returns>
  465. private static string UrlEncode(string name)
  466. {
  467. return WebUtility.UrlEncode(name);
  468. }
  469. /// <summary>
  470. /// Gets the boxset id from movie.
  471. /// </summary>
  472. /// <param name="name">The name.</param>
  473. /// <param name="year">The year.</param>
  474. /// <param name="language">The language.</param>
  475. /// <param name="cancellationToken">The cancellation token</param>
  476. /// <returns>Task{System.String}.</returns>
  477. protected async Task<string> GetBoxsetIdFromMovie(string name, int? year, string language, CancellationToken cancellationToken)
  478. {
  479. string id = null;
  480. string childId = await AttemptFindId(name, year, language, cancellationToken).ConfigureAwait(false);
  481. if (childId != null)
  482. {
  483. string url = string.Format(GetMovieInfo3, childId, ApiKey, language);
  484. using (Stream json = await GetMovieDbResponse(new HttpRequestOptions
  485. {
  486. Url = url,
  487. CancellationToken = cancellationToken,
  488. AcceptHeader = AcceptHeader
  489. }).ConfigureAwait(false))
  490. {
  491. var movieResult = JsonSerializer.DeserializeFromStream<CompleteMovieData>(json);
  492. if (movieResult != null && movieResult.belongs_to_collection != null)
  493. {
  494. id = movieResult.belongs_to_collection.id.ToString(CultureInfo.InvariantCulture);
  495. }
  496. else
  497. {
  498. Logger.Error("Unable to obtain boxset id.");
  499. }
  500. }
  501. }
  502. return id;
  503. }
  504. /// <summary>
  505. /// Fetches the movie data.
  506. /// </summary>
  507. /// <param name="item">The item.</param>
  508. /// <param name="id">The id.</param>
  509. /// <param name="cancellationToken">The cancellation token</param>
  510. /// <returns>Task.</returns>
  511. protected async Task FetchMovieData(BaseItem item, string id, CancellationToken cancellationToken)
  512. {
  513. cancellationToken.ThrowIfCancellationRequested();
  514. if (String.IsNullOrEmpty(id))
  515. {
  516. Logger.Info("MoviedbProvider: Ignoring " + item.Name + " because ID forced blank.");
  517. return;
  518. }
  519. if (item.GetProviderId(MetadataProviders.Tmdb) == null) item.SetProviderId(MetadataProviders.Tmdb, id);
  520. var mainResult = await FetchMainResult(item, id, cancellationToken).ConfigureAwait(false);
  521. if (mainResult == null) return;
  522. ProcessMainInfo(item, mainResult);
  523. }
  524. /// <summary>
  525. /// Fetches the main result.
  526. /// </summary>
  527. /// <param name="item">The item.</param>
  528. /// <param name="id">The id.</param>
  529. /// <param name="cancellationToken">The cancellation token</param>
  530. /// <returns>Task{CompleteMovieData}.</returns>
  531. protected async Task<CompleteMovieData> FetchMainResult(BaseItem item, string id, CancellationToken cancellationToken)
  532. {
  533. var baseUrl = item is BoxSet ? GetBoxSetInfo3 : GetMovieInfo3;
  534. string url = string.Format(baseUrl, id, ApiKey, ConfigurationManager.Configuration.PreferredMetadataLanguage);
  535. CompleteMovieData mainResult;
  536. cancellationToken.ThrowIfCancellationRequested();
  537. using (var json = await GetMovieDbResponse(new HttpRequestOptions
  538. {
  539. Url = url,
  540. CancellationToken = cancellationToken,
  541. AcceptHeader = AcceptHeader
  542. }).ConfigureAwait(false))
  543. {
  544. mainResult = JsonSerializer.DeserializeFromStream<CompleteMovieData>(json);
  545. }
  546. cancellationToken.ThrowIfCancellationRequested();
  547. if (mainResult != null && string.IsNullOrEmpty(mainResult.overview))
  548. {
  549. if (ConfigurationManager.Configuration.PreferredMetadataLanguage.ToLower() != "en")
  550. {
  551. Logger.Info("MovieDbProvider couldn't find meta for language " + ConfigurationManager.Configuration.PreferredMetadataLanguage + ". Trying English...");
  552. url = string.Format(baseUrl, id, ApiKey, "en");
  553. using (Stream json = await GetMovieDbResponse(new HttpRequestOptions
  554. {
  555. Url = url,
  556. CancellationToken = cancellationToken,
  557. AcceptHeader = AcceptHeader
  558. }).ConfigureAwait(false))
  559. {
  560. mainResult = JsonSerializer.DeserializeFromStream<CompleteMovieData>(json);
  561. }
  562. if (String.IsNullOrEmpty(mainResult.overview))
  563. {
  564. Logger.Error("MovieDbProvider - Unable to find information for " + item.Name + " (id:" + id + ")");
  565. return null;
  566. }
  567. }
  568. }
  569. return mainResult;
  570. }
  571. /// <summary>
  572. /// Processes the main info.
  573. /// </summary>
  574. /// <param name="movie">The movie.</param>
  575. /// <param name="movieData">The movie data.</param>
  576. protected virtual void ProcessMainInfo(BaseItem movie, CompleteMovieData movieData)
  577. {
  578. if (movie != null && movieData != null)
  579. {
  580. if (!movie.LockedFields.Contains(MetadataFields.Name))
  581. {
  582. movie.Name = movieData.title ?? movieData.original_title ?? movie.Name;
  583. }
  584. if (!movie.LockedFields.Contains(MetadataFields.Overview))
  585. {
  586. movie.Overview = movieData.overview;
  587. }
  588. movie.Overview = movie.Overview != null ? movie.Overview.Replace("\n\n", "\n") : null;
  589. movie.HomePageUrl = movieData.homepage;
  590. movie.Budget = movieData.budget;
  591. movie.Revenue = movieData.revenue;
  592. if (!string.IsNullOrEmpty(movieData.tagline))
  593. {
  594. movie.Taglines.Clear();
  595. movie.AddTagline(movieData.tagline);
  596. }
  597. movie.SetProviderId(MetadataProviders.Imdb, movieData.imdb_id);
  598. if (movieData.belongs_to_collection != null)
  599. {
  600. movie.SetProviderId(MetadataProviders.TmdbCollection, movieData.belongs_to_collection.id.ToString(CultureInfo.InvariantCulture));
  601. }
  602. float rating;
  603. string voteAvg = movieData.vote_average.ToString(CultureInfo.InvariantCulture);
  604. //tmdb appears to have unified their numbers to always report "7.3" regardless of country
  605. // so I removed the culture-specific processing here because it was not working for other countries -ebr
  606. if (float.TryParse(voteAvg, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out rating))
  607. movie.CommunityRating = rating;
  608. //release date and certification are retrieved based on configured country and we fall back on US if not there
  609. if (movieData.releases != null && movieData.releases.countries != null)
  610. {
  611. var ourRelease = movieData.releases.countries.FirstOrDefault(c => c.iso_3166_1.Equals(ConfigurationManager.Configuration.MetadataCountryCode, StringComparison.OrdinalIgnoreCase)) ?? new Country();
  612. var usRelease = movieData.releases.countries.FirstOrDefault(c => c.iso_3166_1.Equals("US", StringComparison.OrdinalIgnoreCase)) ?? new Country();
  613. var ratingPrefix = ConfigurationManager.Configuration.MetadataCountryCode.Equals("us", StringComparison.OrdinalIgnoreCase) ? "" : ConfigurationManager.Configuration.MetadataCountryCode +"-";
  614. movie.OfficialRating = !string.IsNullOrEmpty(ourRelease.certification) ? ratingPrefix + ourRelease.certification : !string.IsNullOrEmpty(usRelease.certification) ? usRelease.certification : null;
  615. if (ourRelease.release_date > new DateTime(1900, 1, 1))
  616. {
  617. if (ourRelease.release_date.Year != 1)
  618. {
  619. movie.PremiereDate = ourRelease.release_date.ToUniversalTime();
  620. movie.ProductionYear = ourRelease.release_date.Year;
  621. }
  622. }
  623. else
  624. {
  625. if (usRelease.release_date.Year != 1)
  626. {
  627. movie.PremiereDate = usRelease.release_date.ToUniversalTime();
  628. movie.ProductionYear = usRelease.release_date.Year;
  629. }
  630. }
  631. }
  632. else
  633. {
  634. if (movieData.release_date.Year != 1)
  635. {
  636. //no specific country release info at all
  637. movie.PremiereDate = movieData.release_date.ToUniversalTime();
  638. movie.ProductionYear = movieData.release_date.Year;
  639. }
  640. }
  641. //if that didn't find a rating and we are a boxset, use the one from our first child
  642. if (movie.OfficialRating == null && movie is BoxSet)
  643. {
  644. var boxset = movie as BoxSet;
  645. Logger.Info("MovieDbProvider - Using rating of first child of boxset...");
  646. var firstChild = boxset.Children.FirstOrDefault();
  647. boxset.OfficialRating = firstChild != null ? firstChild.OfficialRating : null;
  648. }
  649. if (movieData.runtime > 0)
  650. movie.OriginalRunTimeTicks = TimeSpan.FromMinutes(movieData.runtime).Ticks;
  651. //studios
  652. if (movieData.production_companies != null && !movie.LockedFields.Contains(MetadataFields.Studios))
  653. {
  654. movie.Studios.Clear();
  655. foreach (var studio in movieData.production_companies.Select(c => c.name))
  656. {
  657. movie.AddStudio(studio);
  658. }
  659. }
  660. //genres
  661. if (movieData.genres != null && !movie.LockedFields.Contains(MetadataFields.Genres))
  662. {
  663. movie.Genres.Clear();
  664. foreach (var genre in movieData.genres.Select(g => g.name))
  665. {
  666. movie.AddGenre(genre);
  667. }
  668. }
  669. movie.People.Clear();
  670. movie.Tags.Clear();
  671. //Actors, Directors, Writers - all in People
  672. //actors come from cast
  673. if (movieData.casts != null && movieData.casts.cast != null && !movie.LockedFields.Contains(MetadataFields.Cast))
  674. {
  675. foreach (var actor in movieData.casts.cast.OrderBy(a => a.order)) movie.AddPerson(new PersonInfo { Name = actor.name, Role = actor.character, Type = PersonType.Actor });
  676. }
  677. //and the rest from crew
  678. if (movieData.casts != null && movieData.casts.crew != null)
  679. {
  680. foreach (var person in movieData.casts.crew) movie.AddPerson(new PersonInfo { Name = person.name, Role = person.job, Type = person.department });
  681. }
  682. if (movieData.keywords != null && movieData.keywords.keywords != null && !movie.LockedFields.Contains(MetadataFields.Tags))
  683. {
  684. movie.Tags = movieData.keywords.keywords.Select(i => i.name).ToList();
  685. }
  686. }
  687. }
  688. private DateTime _lastRequestDate = DateTime.MinValue;
  689. /// <summary>
  690. /// Gets the movie db response.
  691. /// </summary>
  692. internal async Task<Stream> GetMovieDbResponse(HttpRequestOptions options)
  693. {
  694. var cancellationToken = options.CancellationToken;
  695. await _movieDbResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
  696. try
  697. {
  698. // Limit to three requests per second
  699. var diff = 340 - (DateTime.Now - _lastRequestDate).TotalMilliseconds;
  700. if (diff > 0)
  701. {
  702. await Task.Delay(Convert.ToInt32(diff), cancellationToken).ConfigureAwait(false);
  703. }
  704. _lastRequestDate = DateTime.Now;
  705. return await HttpClient.Get(options).ConfigureAwait(false);
  706. }
  707. finally
  708. {
  709. _lastRequestDate = DateTime.Now;
  710. _movieDbResourcePool.Release();
  711. }
  712. }
  713. /// <summary>
  714. /// The remove
  715. /// </summary>
  716. const string Remove = "\"'!`?";
  717. // "Face/Off" support.
  718. /// <summary>
  719. /// The spacers
  720. /// </summary>
  721. const string Spacers = "/,.:;\\(){}[]+-_=–*"; // (there are not actually two - in the they are different char codes)
  722. /// <summary>
  723. /// The replace start numbers
  724. /// </summary>
  725. static readonly Dictionary<string, string> ReplaceStartNumbers = new Dictionary<string, string> {
  726. {"1 ","one "},
  727. {"2 ","two "},
  728. {"3 ","three "},
  729. {"4 ","four "},
  730. {"5 ","five "},
  731. {"6 ","six "},
  732. {"7 ","seven "},
  733. {"8 ","eight "},
  734. {"9 ","nine "},
  735. {"10 ","ten "},
  736. {"11 ","eleven "},
  737. {"12 ","twelve "},
  738. {"13 ","thirteen "},
  739. {"100 ","one hundred "},
  740. {"101 ","one hundred one "}
  741. };
  742. /// <summary>
  743. /// The replace end numbers
  744. /// </summary>
  745. static readonly Dictionary<string, string> ReplaceEndNumbers = new Dictionary<string, string> {
  746. {" 1"," i"},
  747. {" 2"," ii"},
  748. {" 3"," iii"},
  749. {" 4"," iv"},
  750. {" 5"," v"},
  751. {" 6"," vi"},
  752. {" 7"," vii"},
  753. {" 8"," viii"},
  754. {" 9"," ix"},
  755. {" 10"," x"}
  756. };
  757. /// <summary>
  758. /// Gets the name of the comparable.
  759. /// </summary>
  760. /// <param name="name">The name.</param>
  761. /// <param name="logger">The logger.</param>
  762. /// <returns>System.String.</returns>
  763. internal static string GetComparableName(string name, ILogger logger)
  764. {
  765. name = name.ToLower();
  766. name = name.Replace("á", "a");
  767. name = name.Replace("é", "e");
  768. name = name.Replace("í", "i");
  769. name = name.Replace("ó", "o");
  770. name = name.Replace("ú", "u");
  771. name = name.Replace("ü", "u");
  772. name = name.Replace("ñ", "n");
  773. foreach (var pair in ReplaceStartNumbers)
  774. {
  775. if (name.StartsWith(pair.Key))
  776. {
  777. name = name.Remove(0, pair.Key.Length);
  778. name = pair.Value + name;
  779. logger.Info("MovieDbProvider - Replaced Start Numbers: " + name);
  780. }
  781. }
  782. foreach (var pair in ReplaceEndNumbers)
  783. {
  784. if (name.EndsWith(pair.Key))
  785. {
  786. name = name.Remove(name.IndexOf(pair.Key), pair.Key.Length);
  787. name = name + pair.Value;
  788. logger.Info("MovieDbProvider - Replaced End Numbers: " + name);
  789. }
  790. }
  791. name = name.Normalize(NormalizationForm.FormKD);
  792. var sb = new StringBuilder();
  793. foreach (var c in name)
  794. {
  795. if (c >= 0x2B0 && c <= 0x0333)
  796. {
  797. // skip char modifier and diacritics
  798. }
  799. else if (Remove.IndexOf(c) > -1)
  800. {
  801. // skip chars we are removing
  802. }
  803. else if (Spacers.IndexOf(c) > -1)
  804. {
  805. sb.Append(" ");
  806. }
  807. else if (c == '&')
  808. {
  809. sb.Append(" and ");
  810. }
  811. else
  812. {
  813. sb.Append(c);
  814. }
  815. }
  816. name = sb.ToString();
  817. name = name.Replace(", the", "");
  818. name = name.Replace(" the ", " ");
  819. name = name.Replace("the ", "");
  820. string prev_name;
  821. do
  822. {
  823. prev_name = name;
  824. name = name.Replace(" ", " ");
  825. } while (name.Length != prev_name.Length);
  826. return name.Trim();
  827. }
  828. #region Result Objects
  829. /// <summary>
  830. /// Class TmdbTitle
  831. /// </summary>
  832. protected class TmdbTitle
  833. {
  834. /// <summary>
  835. /// Gets or sets the iso_3166_1.
  836. /// </summary>
  837. /// <value>The iso_3166_1.</value>
  838. public string iso_3166_1 { get; set; }
  839. /// <summary>
  840. /// Gets or sets the title.
  841. /// </summary>
  842. /// <value>The title.</value>
  843. public string title { get; set; }
  844. }
  845. /// <summary>
  846. /// Class TmdbAltTitleResults
  847. /// </summary>
  848. protected class TmdbAltTitleResults
  849. {
  850. /// <summary>
  851. /// Gets or sets the id.
  852. /// </summary>
  853. /// <value>The id.</value>
  854. public int id { get; set; }
  855. /// <summary>
  856. /// Gets or sets the titles.
  857. /// </summary>
  858. /// <value>The titles.</value>
  859. public List<TmdbTitle> titles { get; set; }
  860. }
  861. /// <summary>
  862. /// Class TmdbMovieSearchResult
  863. /// </summary>
  864. protected class TmdbMovieSearchResult
  865. {
  866. /// <summary>
  867. /// Gets or sets a value indicating whether this <see cref="TmdbMovieSearchResult" /> is adult.
  868. /// </summary>
  869. /// <value><c>true</c> if adult; otherwise, <c>false</c>.</value>
  870. public bool adult { get; set; }
  871. /// <summary>
  872. /// Gets or sets the backdrop_path.
  873. /// </summary>
  874. /// <value>The backdrop_path.</value>
  875. public string backdrop_path { get; set; }
  876. /// <summary>
  877. /// Gets or sets the id.
  878. /// </summary>
  879. /// <value>The id.</value>
  880. public int id { get; set; }
  881. /// <summary>
  882. /// Gets or sets the original_title.
  883. /// </summary>
  884. /// <value>The original_title.</value>
  885. public string original_title { get; set; }
  886. /// <summary>
  887. /// Gets or sets the release_date.
  888. /// </summary>
  889. /// <value>The release_date.</value>
  890. public string release_date { get; set; }
  891. /// <summary>
  892. /// Gets or sets the poster_path.
  893. /// </summary>
  894. /// <value>The poster_path.</value>
  895. public string poster_path { get; set; }
  896. /// <summary>
  897. /// Gets or sets the popularity.
  898. /// </summary>
  899. /// <value>The popularity.</value>
  900. public double popularity { get; set; }
  901. /// <summary>
  902. /// Gets or sets the title.
  903. /// </summary>
  904. /// <value>The title.</value>
  905. public string title { get; set; }
  906. /// <summary>
  907. /// Gets or sets the vote_average.
  908. /// </summary>
  909. /// <value>The vote_average.</value>
  910. public double vote_average { get; set; }
  911. /// <summary>
  912. /// Gets or sets the vote_count.
  913. /// </summary>
  914. /// <value>The vote_count.</value>
  915. public int vote_count { get; set; }
  916. }
  917. /// <summary>
  918. /// Class TmdbMovieSearchResults
  919. /// </summary>
  920. protected class TmdbMovieSearchResults
  921. {
  922. /// <summary>
  923. /// Gets or sets the page.
  924. /// </summary>
  925. /// <value>The page.</value>
  926. public int page { get; set; }
  927. /// <summary>
  928. /// Gets or sets the results.
  929. /// </summary>
  930. /// <value>The results.</value>
  931. public List<TmdbMovieSearchResult> results { get; set; }
  932. /// <summary>
  933. /// Gets or sets the total_pages.
  934. /// </summary>
  935. /// <value>The total_pages.</value>
  936. public int total_pages { get; set; }
  937. /// <summary>
  938. /// Gets or sets the total_results.
  939. /// </summary>
  940. /// <value>The total_results.</value>
  941. public int total_results { get; set; }
  942. }
  943. protected class BelongsToCollection
  944. {
  945. public int id { get; set; }
  946. public string name { get; set; }
  947. public string poster_path { get; set; }
  948. public string backdrop_path { get; set; }
  949. }
  950. protected class GenreItem
  951. {
  952. public int id { get; set; }
  953. public string name { get; set; }
  954. }
  955. protected class ProductionCompany
  956. {
  957. public string name { get; set; }
  958. public int id { get; set; }
  959. }
  960. protected class ProductionCountry
  961. {
  962. public string iso_3166_1 { get; set; }
  963. public string name { get; set; }
  964. }
  965. protected class SpokenLanguage
  966. {
  967. public string iso_639_1 { get; set; }
  968. public string name { get; set; }
  969. }
  970. protected class Cast
  971. {
  972. public int id { get; set; }
  973. public string name { get; set; }
  974. public string character { get; set; }
  975. public int order { get; set; }
  976. public int cast_id { get; set; }
  977. public string profile_path { get; set; }
  978. }
  979. protected class Crew
  980. {
  981. public int id { get; set; }
  982. public string name { get; set; }
  983. public string department { get; set; }
  984. public string job { get; set; }
  985. public string profile_path { get; set; }
  986. }
  987. protected class Casts
  988. {
  989. public List<Cast> cast { get; set; }
  990. public List<Crew> crew { get; set; }
  991. }
  992. protected class Country
  993. {
  994. public string iso_3166_1 { get; set; }
  995. public string certification { get; set; }
  996. public DateTime release_date { get; set; }
  997. }
  998. protected class Releases
  999. {
  1000. public List<Country> countries { get; set; }
  1001. }
  1002. protected class Keyword
  1003. {
  1004. public int id { get; set; }
  1005. public string name { get; set; }
  1006. }
  1007. protected class Keywords
  1008. {
  1009. public List<Keyword> keywords { get; set; }
  1010. }
  1011. protected class CompleteMovieData
  1012. {
  1013. public bool adult { get; set; }
  1014. public string backdrop_path { get; set; }
  1015. public BelongsToCollection belongs_to_collection { get; set; }
  1016. public int budget { get; set; }
  1017. public List<GenreItem> genres { get; set; }
  1018. public string homepage { get; set; }
  1019. public int id { get; set; }
  1020. public string imdb_id { get; set; }
  1021. public string original_title { get; set; }
  1022. public string overview { get; set; }
  1023. public double popularity { get; set; }
  1024. public string poster_path { get; set; }
  1025. public List<ProductionCompany> production_companies { get; set; }
  1026. public List<ProductionCountry> production_countries { get; set; }
  1027. public DateTime release_date { get; set; }
  1028. public int revenue { get; set; }
  1029. public int runtime { get; set; }
  1030. public List<SpokenLanguage> spoken_languages { get; set; }
  1031. public string status { get; set; }
  1032. public string tagline { get; set; }
  1033. public string title { get; set; }
  1034. public double vote_average { get; set; }
  1035. public int vote_count { get; set; }
  1036. public Casts casts { get; set; }
  1037. public Releases releases { get; set; }
  1038. public Keywords keywords { get; set; }
  1039. }
  1040. public class TmdbImageSettings
  1041. {
  1042. public List<string> backdrop_sizes { get; set; }
  1043. public string base_url { get; set; }
  1044. public List<string> poster_sizes { get; set; }
  1045. public List<string> profile_sizes { get; set; }
  1046. }
  1047. public class TmdbSettingsResult
  1048. {
  1049. public TmdbImageSettings images { get; set; }
  1050. }
  1051. #endregion
  1052. public void Dispose()
  1053. {
  1054. Dispose(true);
  1055. }
  1056. }
  1057. }