TmdbPersonProvider.cs 16 KB

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