TmdbPersonProvider.cs 16 KB

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