TmdbPersonProvider.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller.Configuration;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Providers;
  6. using MediaBrowser.Model.Entities;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.Serialization;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Globalization;
  12. using System.IO;
  13. using System.Linq;
  14. using System.Net;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. namespace MediaBrowser.Providers.Movies
  18. {
  19. /// <summary>
  20. /// Class TmdbPersonProvider
  21. /// </summary>
  22. public class TmdbPersonProvider : BaseMetadataProvider
  23. {
  24. protected readonly IProviderManager ProviderManager;
  25. public TmdbPersonProvider(IJsonSerializer jsonSerializer, ILogManager logManager, IServerConfigurationManager configurationManager, IProviderManager providerManager)
  26. : base(logManager, configurationManager)
  27. {
  28. if (jsonSerializer == null)
  29. {
  30. throw new ArgumentNullException("jsonSerializer");
  31. }
  32. JsonSerializer = jsonSerializer;
  33. ProviderManager = providerManager;
  34. }
  35. /// <summary>
  36. /// Gets the json serializer.
  37. /// </summary>
  38. /// <value>The json serializer.</value>
  39. protected IJsonSerializer JsonSerializer { get; private set; }
  40. /// <summary>
  41. /// Supportses the specified item.
  42. /// </summary>
  43. /// <param name="item">The item.</param>
  44. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
  45. public override bool Supports(BaseItem item)
  46. {
  47. return item is Person;
  48. }
  49. protected override bool RefreshOnVersionChange
  50. {
  51. get
  52. {
  53. return true;
  54. }
  55. }
  56. protected override string ProviderVersion
  57. {
  58. get
  59. {
  60. return "2";
  61. }
  62. }
  63. public override ItemUpdateType ItemUpdateType
  64. {
  65. get
  66. {
  67. return ItemUpdateType.ImageUpdate | ItemUpdateType.MetadataDownload;
  68. }
  69. }
  70. protected override bool NeedsRefreshInternal(BaseItem item, BaseProviderInfo providerInfo)
  71. {
  72. if (HasAltMeta(item))
  73. return false;
  74. return base.NeedsRefreshInternal(item, providerInfo);
  75. }
  76. private bool HasAltMeta(BaseItem item)
  77. {
  78. return item.LocationType == LocationType.FileSystem && item.ResolveArgs.ContainsMetaFileByName("person.xml");
  79. }
  80. /// <summary>
  81. /// Fetches metadata and returns true or false indicating if any work that requires persistence was done
  82. /// </summary>
  83. /// <param name="item">The item.</param>
  84. /// <param name="force">if set to <c>true</c> [force].</param>
  85. /// <param name="cancellationToken">The cancellation token.</param>
  86. /// <returns>Task{System.Boolean}.</returns>
  87. public override async Task<bool> FetchAsync(BaseItem item, bool force, CancellationToken cancellationToken)
  88. {
  89. cancellationToken.ThrowIfCancellationRequested();
  90. var person = (Person)item;
  91. var id = person.GetProviderId(MetadataProviders.Tmdb);
  92. // We don't already have an Id, need to fetch it
  93. if (string.IsNullOrEmpty(id))
  94. {
  95. id = await GetTmdbId(item, cancellationToken).ConfigureAwait(false);
  96. }
  97. cancellationToken.ThrowIfCancellationRequested();
  98. if (!string.IsNullOrEmpty(id))
  99. {
  100. await FetchInfo(person, id, cancellationToken).ConfigureAwait(false);
  101. }
  102. else
  103. {
  104. Logger.Debug("TmdbPersonProvider Unable to obtain id for " + item.Name);
  105. }
  106. SetLastRefreshed(item, DateTime.UtcNow);
  107. return true;
  108. }
  109. /// <summary>
  110. /// Gets the priority.
  111. /// </summary>
  112. /// <value>The priority.</value>
  113. public override MetadataProviderPriority Priority
  114. {
  115. get { return MetadataProviderPriority.Second; }
  116. }
  117. /// <summary>
  118. /// Gets a value indicating whether [requires internet].
  119. /// </summary>
  120. /// <value><c>true</c> if [requires internet]; otherwise, <c>false</c>.</value>
  121. public override bool RequiresInternet
  122. {
  123. get
  124. {
  125. return true;
  126. }
  127. }
  128. protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
  129. /// <summary>
  130. /// Gets the TMDB id.
  131. /// </summary>
  132. /// <param name="person">The person.</param>
  133. /// <param name="cancellationToken">The cancellation token.</param>
  134. /// <returns>Task{System.String}.</returns>
  135. private async Task<string> GetTmdbId(BaseItem person, CancellationToken cancellationToken)
  136. {
  137. string url = string.Format(@"http://api.themoviedb.org/3/search/person?api_key={1}&query={0}", WebUtility.UrlEncode(person.Name), MovieDbProvider.ApiKey);
  138. PersonSearchResults searchResult = null;
  139. using (Stream json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  140. {
  141. Url = url,
  142. CancellationToken = cancellationToken,
  143. AcceptHeader = MovieDbProvider.AcceptHeader
  144. }).ConfigureAwait(false))
  145. {
  146. searchResult = JsonSerializer.DeserializeFromStream<PersonSearchResults>(json);
  147. }
  148. return searchResult != null && searchResult.Total_Results > 0 ? searchResult.Results[0].Id.ToString(UsCulture) : null;
  149. }
  150. /// <summary>
  151. /// Fetches the info.
  152. /// </summary>
  153. /// <param name="person">The person.</param>
  154. /// <param name="id">The id.</param>
  155. /// <param name="cancellationToken">The cancellation token.</param>
  156. /// <returns>Task.</returns>
  157. private async Task FetchInfo(Person person, string id, CancellationToken cancellationToken)
  158. {
  159. string url = string.Format(@"http://api.themoviedb.org/3/person/{1}?api_key={0}&append_to_response=credits,images", MovieDbProvider.ApiKey, id);
  160. PersonResult searchResult = null;
  161. using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  162. {
  163. Url = url,
  164. CancellationToken = cancellationToken,
  165. AcceptHeader = MovieDbProvider.AcceptHeader
  166. }).ConfigureAwait(false))
  167. {
  168. searchResult = JsonSerializer.DeserializeFromStream<PersonResult>(json);
  169. }
  170. cancellationToken.ThrowIfCancellationRequested();
  171. if (searchResult != null)
  172. {
  173. ProcessInfo(person, searchResult);
  174. Logger.Debug("TmdbPersonProvider downloaded and saved information for {0}", person.Name);
  175. await FetchImages(person, searchResult.images, cancellationToken).ConfigureAwait(false);
  176. }
  177. }
  178. /// <summary>
  179. /// Processes the info.
  180. /// </summary>
  181. /// <param name="person">The person.</param>
  182. /// <param name="searchResult">The search result.</param>
  183. protected void ProcessInfo(Person person, PersonResult searchResult)
  184. {
  185. if (!person.LockedFields.Contains(MetadataFields.Overview))
  186. {
  187. person.Overview = searchResult.biography;
  188. }
  189. DateTime date;
  190. if (DateTime.TryParseExact(searchResult.birthday, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
  191. {
  192. person.PremiereDate = date.ToUniversalTime();
  193. }
  194. if (DateTime.TryParseExact(searchResult.deathday, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
  195. {
  196. person.EndDate = date.ToUniversalTime();
  197. }
  198. if (!string.IsNullOrEmpty(searchResult.homepage))
  199. {
  200. person.HomePageUrl = searchResult.homepage;
  201. }
  202. if (!person.LockedFields.Contains(MetadataFields.ProductionLocations))
  203. {
  204. if (!string.IsNullOrEmpty(searchResult.place_of_birth))
  205. {
  206. person.ProductionLocations = new List<string> { searchResult.place_of_birth };
  207. }
  208. }
  209. person.SetProviderId(MetadataProviders.Tmdb, searchResult.id.ToString(UsCulture));
  210. }
  211. /// <summary>
  212. /// Fetches the images.
  213. /// </summary>
  214. /// <param name="person">The person.</param>
  215. /// <param name="searchResult">The search result.</param>
  216. /// <param name="cancellationToken">The cancellation token.</param>
  217. /// <returns>Task.</returns>
  218. private async Task FetchImages(Person person, Images searchResult, CancellationToken cancellationToken)
  219. {
  220. if (searchResult != null && searchResult.profiles.Count > 0)
  221. {
  222. //get our language
  223. var profile =
  224. searchResult.profiles.FirstOrDefault(
  225. p =>
  226. !string.IsNullOrEmpty(GetIso639(p)) &&
  227. GetIso639(p).Equals(ConfigurationManager.Configuration.PreferredMetadataLanguage,
  228. StringComparison.OrdinalIgnoreCase));
  229. if (profile == null)
  230. {
  231. //didn't find our language - try first null one
  232. profile =
  233. searchResult.profiles.FirstOrDefault(
  234. p =>
  235. !string.IsNullOrEmpty(GetIso639(p)) &&
  236. GetIso639(p).Equals(ConfigurationManager.Configuration.PreferredMetadataLanguage,
  237. StringComparison.OrdinalIgnoreCase));
  238. }
  239. if (profile == null)
  240. {
  241. //still nothing - just get first one
  242. profile = searchResult.profiles[0];
  243. }
  244. if (profile != null && !person.HasImage(ImageType.Primary))
  245. {
  246. var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
  247. await DownloadAndSaveImage(person, tmdbSettings.images.base_url + ConfigurationManager.Configuration.TmdbFetchedProfileSize + profile.file_path,
  248. MimeTypes.GetMimeType(profile.file_path), cancellationToken).ConfigureAwait(false);
  249. }
  250. }
  251. }
  252. private string GetIso639(Profile p)
  253. {
  254. return p.iso_639_1 == null ? string.Empty : p.iso_639_1.ToString();
  255. }
  256. /// <summary>
  257. /// Downloads the and save image.
  258. /// </summary>
  259. /// <param name="item">The item.</param>
  260. /// <param name="source">The source.</param>
  261. /// <param name="mimeType">Type of the MIME.</param>
  262. /// <param name="cancellationToken">The cancellation token.</param>
  263. /// <returns>Task{System.String}.</returns>
  264. private async Task DownloadAndSaveImage(BaseItem item, string source, string mimeType, CancellationToken cancellationToken)
  265. {
  266. if (source == null) return;
  267. using (var sourceStream = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  268. {
  269. Url = source,
  270. CancellationToken = cancellationToken
  271. }).ConfigureAwait(false))
  272. {
  273. await ProviderManager.SaveImage(item, sourceStream, mimeType, ImageType.Primary, null, cancellationToken)
  274. .ConfigureAwait(false);
  275. Logger.Debug("TmdbPersonProvider downloaded and saved image for {0}", item.Name);
  276. }
  277. }
  278. #region Result Objects
  279. /// <summary>
  280. /// Class PersonSearchResult
  281. /// </summary>
  282. protected class PersonSearchResult
  283. {
  284. /// <summary>
  285. /// Gets or sets a value indicating whether this <see cref="PersonSearchResult" /> is adult.
  286. /// </summary>
  287. /// <value><c>true</c> if adult; otherwise, <c>false</c>.</value>
  288. public bool Adult { get; set; }
  289. /// <summary>
  290. /// Gets or sets the id.
  291. /// </summary>
  292. /// <value>The id.</value>
  293. public int Id { get; set; }
  294. /// <summary>
  295. /// Gets or sets the name.
  296. /// </summary>
  297. /// <value>The name.</value>
  298. public string Name { get; set; }
  299. /// <summary>
  300. /// Gets or sets the profile_ path.
  301. /// </summary>
  302. /// <value>The profile_ path.</value>
  303. public string Profile_Path { get; set; }
  304. }
  305. /// <summary>
  306. /// Class PersonSearchResults
  307. /// </summary>
  308. protected class PersonSearchResults
  309. {
  310. /// <summary>
  311. /// Gets or sets the page.
  312. /// </summary>
  313. /// <value>The page.</value>
  314. public int Page { get; set; }
  315. /// <summary>
  316. /// Gets or sets the results.
  317. /// </summary>
  318. /// <value>The results.</value>
  319. public List<PersonSearchResult> Results { get; set; }
  320. /// <summary>
  321. /// Gets or sets the total_ pages.
  322. /// </summary>
  323. /// <value>The total_ pages.</value>
  324. public int Total_Pages { get; set; }
  325. /// <summary>
  326. /// Gets or sets the total_ results.
  327. /// </summary>
  328. /// <value>The total_ results.</value>
  329. public int Total_Results { get; set; }
  330. }
  331. protected class Cast
  332. {
  333. public int id { get; set; }
  334. public string title { get; set; }
  335. public string character { get; set; }
  336. public string original_title { get; set; }
  337. public string poster_path { get; set; }
  338. public string release_date { get; set; }
  339. public bool adult { get; set; }
  340. }
  341. protected class Crew
  342. {
  343. public int id { get; set; }
  344. public string title { get; set; }
  345. public string original_title { get; set; }
  346. public string department { get; set; }
  347. public string job { get; set; }
  348. public string poster_path { get; set; }
  349. public string release_date { get; set; }
  350. public bool adult { get; set; }
  351. }
  352. protected class Credits
  353. {
  354. public List<Cast> cast { get; set; }
  355. public List<Crew> crew { get; set; }
  356. }
  357. protected class Profile
  358. {
  359. public string file_path { get; set; }
  360. public int width { get; set; }
  361. public int height { get; set; }
  362. public object iso_639_1 { get; set; }
  363. public double aspect_ratio { get; set; }
  364. }
  365. protected class Images
  366. {
  367. public List<Profile> profiles { get; set; }
  368. }
  369. protected class PersonResult
  370. {
  371. public bool adult { get; set; }
  372. public List<object> also_known_as { get; set; }
  373. public string biography { get; set; }
  374. public string birthday { get; set; }
  375. public string deathday { get; set; }
  376. public string homepage { get; set; }
  377. public int id { get; set; }
  378. public string imdb_id { get; set; }
  379. public string name { get; set; }
  380. public string place_of_birth { get; set; }
  381. public double popularity { get; set; }
  382. public string profile_path { get; set; }
  383. public Credits credits { get; set; }
  384. public Images images { get; set; }
  385. }
  386. #endregion
  387. }
  388. }