MovieDbPersonProvider.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Providers;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Providers;
  9. using MediaBrowser.Model.Serialization;
  10. using MediaBrowser.Providers.Movies;
  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.Threading;
  18. using System.Threading.Tasks;
  19. using MediaBrowser.Controller.IO;
  20. using MediaBrowser.Model.IO;
  21. using MediaBrowser.Model.Logging;
  22. using MediaBrowser.Model.Net;
  23. namespace MediaBrowser.Providers.People
  24. {
  25. public class MovieDbPersonProvider : IRemoteMetadataProvider<Person, PersonLookupInfo>
  26. {
  27. const string DataFileName = "info.json";
  28. internal static MovieDbPersonProvider Current { get; private set; }
  29. private readonly IJsonSerializer _jsonSerializer;
  30. private readonly IFileSystem _fileSystem;
  31. private readonly IServerConfigurationManager _configurationManager;
  32. private readonly IHttpClient _httpClient;
  33. private readonly ILogger _logger;
  34. public MovieDbPersonProvider(IFileSystem fileSystem, IServerConfigurationManager configurationManager, IJsonSerializer jsonSerializer, IHttpClient httpClient, ILogger logger)
  35. {
  36. _fileSystem = fileSystem;
  37. _configurationManager = configurationManager;
  38. _jsonSerializer = jsonSerializer;
  39. _httpClient = httpClient;
  40. _logger = logger;
  41. Current = this;
  42. }
  43. public string Name
  44. {
  45. get { return "TheMovieDb"; }
  46. }
  47. public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(PersonLookupInfo searchInfo, CancellationToken cancellationToken)
  48. {
  49. var tmdbId = searchInfo.GetProviderId(MetadataProviders.Tmdb);
  50. var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
  51. var tmdbImageUrl = tmdbSettings.images.secure_base_url + "original";
  52. if (!string.IsNullOrEmpty(tmdbId))
  53. {
  54. await EnsurePersonInfo(tmdbId, cancellationToken).ConfigureAwait(false);
  55. var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, tmdbId);
  56. var info = _jsonSerializer.DeserializeFromFile<PersonResult>(dataFilePath);
  57. var images = (info.images ?? new Images()).profiles ?? new List<Profile>();
  58. var result = new RemoteSearchResult
  59. {
  60. Name = info.name,
  61. SearchProviderName = Name,
  62. ImageUrl = images.Count == 0 ? null : (tmdbImageUrl + images[0].file_path)
  63. };
  64. result.SetProviderId(MetadataProviders.Tmdb, info.id.ToString(_usCulture));
  65. result.SetProviderId(MetadataProviders.Imdb, info.imdb_id);
  66. return new[] { result };
  67. }
  68. if (searchInfo.IsAutomated)
  69. {
  70. // Don't hammer moviedb searching by name
  71. return new List<RemoteSearchResult>();
  72. }
  73. var url = string.Format(@"https://api.themoviedb.org/3/search/person?api_key={1}&query={0}", WebUtility.UrlEncode(searchInfo.Name), MovieDbProvider.ApiKey);
  74. using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  75. {
  76. Url = url,
  77. CancellationToken = cancellationToken,
  78. AcceptHeader = MovieDbProvider.AcceptHeader
  79. }).ConfigureAwait(false))
  80. {
  81. var result = _jsonSerializer.DeserializeFromStream<PersonSearchResults>(json) ??
  82. new PersonSearchResults();
  83. return result.Results.Select(i => GetSearchResult(i, tmdbImageUrl));
  84. }
  85. }
  86. private RemoteSearchResult GetSearchResult(PersonSearchResult i, string baseImageUrl)
  87. {
  88. var result = new RemoteSearchResult
  89. {
  90. SearchProviderName = Name,
  91. Name = i.Name,
  92. ImageUrl = string.IsNullOrEmpty(i.Profile_Path) ? null : (baseImageUrl + i.Profile_Path)
  93. };
  94. result.SetProviderId(MetadataProviders.Tmdb, i.Id.ToString(_usCulture));
  95. return result;
  96. }
  97. public async Task<MetadataResult<Person>> GetMetadata(PersonLookupInfo id, CancellationToken cancellationToken)
  98. {
  99. var tmdbId = id.GetProviderId(MetadataProviders.Tmdb);
  100. // We don't already have an Id, need to fetch it
  101. if (string.IsNullOrEmpty(tmdbId))
  102. {
  103. tmdbId = await GetTmdbId(id, cancellationToken).ConfigureAwait(false);
  104. }
  105. var result = new MetadataResult<Person>();
  106. if (!string.IsNullOrEmpty(tmdbId))
  107. {
  108. try
  109. {
  110. await EnsurePersonInfo(tmdbId, cancellationToken).ConfigureAwait(false);
  111. }
  112. catch (HttpException ex)
  113. {
  114. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
  115. {
  116. return result;
  117. }
  118. throw;
  119. }
  120. var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, tmdbId);
  121. var info = _jsonSerializer.DeserializeFromFile<PersonResult>(dataFilePath);
  122. var item = new Person();
  123. result.HasMetadata = true;
  124. // Take name from incoming info, don't rename the person
  125. // TODO: This should go in PersonMetadataService, not each person provider
  126. item.Name = id.Name;
  127. item.HomePageUrl = info.homepage;
  128. if (!string.IsNullOrWhiteSpace(info.place_of_birth))
  129. {
  130. item.ProductionLocations = new string[] { info.place_of_birth };
  131. }
  132. item.Overview = info.biography;
  133. DateTime date;
  134. if (DateTime.TryParseExact(info.birthday, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
  135. {
  136. item.PremiereDate = date.ToUniversalTime();
  137. }
  138. if (DateTime.TryParseExact(info.deathday, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
  139. {
  140. item.EndDate = date.ToUniversalTime();
  141. }
  142. item.SetProviderId(MetadataProviders.Tmdb, info.id.ToString(_usCulture));
  143. if (!string.IsNullOrEmpty(info.imdb_id))
  144. {
  145. item.SetProviderId(MetadataProviders.Imdb, info.imdb_id);
  146. }
  147. result.HasMetadata = true;
  148. result.Item = item;
  149. }
  150. return result;
  151. }
  152. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  153. /// <summary>
  154. /// Gets the TMDB id.
  155. /// </summary>
  156. /// <param name="info">The information.</param>
  157. /// <param name="cancellationToken">The cancellation token.</param>
  158. /// <returns>Task{System.String}.</returns>
  159. private async Task<string> GetTmdbId(PersonLookupInfo info, CancellationToken cancellationToken)
  160. {
  161. var results = await GetSearchResults(info, cancellationToken).ConfigureAwait(false);
  162. return results.Select(i => i.GetProviderId(MetadataProviders.Tmdb)).FirstOrDefault();
  163. }
  164. internal async Task EnsurePersonInfo(string id, CancellationToken cancellationToken)
  165. {
  166. var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, id);
  167. var fileInfo = _fileSystem.GetFileSystemInfo(dataFilePath);
  168. if (fileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
  169. {
  170. return;
  171. }
  172. var url = string.Format(@"https://api.themoviedb.org/3/person/{1}?api_key={0}&append_to_response=credits,images,external_ids", MovieDbProvider.ApiKey, id);
  173. using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  174. {
  175. Url = url,
  176. CancellationToken = cancellationToken,
  177. AcceptHeader = MovieDbProvider.AcceptHeader
  178. }).ConfigureAwait(false))
  179. {
  180. _fileSystem.CreateDirectory(_fileSystem.GetDirectoryName(dataFilePath));
  181. using (var fs = _fileSystem.GetFileStream(dataFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true))
  182. {
  183. await json.CopyToAsync(fs).ConfigureAwait(false);
  184. }
  185. }
  186. }
  187. private static string GetPersonDataPath(IApplicationPaths appPaths, string tmdbId)
  188. {
  189. var letter = tmdbId.GetMD5().ToString().Substring(0, 1);
  190. return Path.Combine(GetPersonsDataPath(appPaths), letter, tmdbId);
  191. }
  192. internal static string GetPersonDataFilePath(IApplicationPaths appPaths, string tmdbId)
  193. {
  194. return Path.Combine(GetPersonDataPath(appPaths, tmdbId), DataFileName);
  195. }
  196. private static string GetPersonsDataPath(IApplicationPaths appPaths)
  197. {
  198. return Path.Combine(appPaths.CachePath, "tmdb-people");
  199. }
  200. #region Result Objects
  201. /// <summary>
  202. /// Class PersonSearchResult
  203. /// </summary>
  204. public class PersonSearchResult
  205. {
  206. /// <summary>
  207. /// Gets or sets a value indicating whether this <see cref="MovieDbPersonProvider.PersonSearchResult" /> is adult.
  208. /// </summary>
  209. /// <value><c>true</c> if adult; otherwise, <c>false</c>.</value>
  210. public bool Adult { get; set; }
  211. /// <summary>
  212. /// Gets or sets the id.
  213. /// </summary>
  214. /// <value>The id.</value>
  215. public int Id { get; set; }
  216. /// <summary>
  217. /// Gets or sets the name.
  218. /// </summary>
  219. /// <value>The name.</value>
  220. public string Name { get; set; }
  221. /// <summary>
  222. /// Gets or sets the profile_ path.
  223. /// </summary>
  224. /// <value>The profile_ path.</value>
  225. public string Profile_Path { get; set; }
  226. }
  227. /// <summary>
  228. /// Class PersonSearchResults
  229. /// </summary>
  230. public class PersonSearchResults
  231. {
  232. /// <summary>
  233. /// Gets or sets the page.
  234. /// </summary>
  235. /// <value>The page.</value>
  236. public int Page { get; set; }
  237. /// <summary>
  238. /// Gets or sets the results.
  239. /// </summary>
  240. /// <value>The results.</value>
  241. public List<MovieDbPersonProvider.PersonSearchResult> Results { get; set; }
  242. /// <summary>
  243. /// Gets or sets the total_ pages.
  244. /// </summary>
  245. /// <value>The total_ pages.</value>
  246. public int Total_Pages { get; set; }
  247. /// <summary>
  248. /// Gets or sets the total_ results.
  249. /// </summary>
  250. /// <value>The total_ results.</value>
  251. public int Total_Results { get; set; }
  252. }
  253. public class Cast
  254. {
  255. public int id { get; set; }
  256. public string title { get; set; }
  257. public string character { get; set; }
  258. public string original_title { get; set; }
  259. public string poster_path { get; set; }
  260. public string release_date { get; set; }
  261. public bool adult { get; set; }
  262. }
  263. public class Crew
  264. {
  265. public int id { get; set; }
  266. public string title { get; set; }
  267. public string original_title { get; set; }
  268. public string department { get; set; }
  269. public string job { get; set; }
  270. public string poster_path { get; set; }
  271. public string release_date { get; set; }
  272. public bool adult { get; set; }
  273. }
  274. public class Credits
  275. {
  276. public List<Cast> cast { get; set; }
  277. public List<Crew> crew { get; set; }
  278. }
  279. public class Profile
  280. {
  281. public string file_path { get; set; }
  282. public int width { get; set; }
  283. public int height { get; set; }
  284. public object iso_639_1 { get; set; }
  285. public double aspect_ratio { get; set; }
  286. }
  287. public class Images
  288. {
  289. public List<Profile> profiles { get; set; }
  290. }
  291. public class ExternalIds
  292. {
  293. public string imdb_id { get; set; }
  294. public string freebase_mid { get; set; }
  295. public string freebase_id { get; set; }
  296. public int tvrage_id { get; set; }
  297. }
  298. public class PersonResult
  299. {
  300. public bool adult { get; set; }
  301. public List<object> also_known_as { get; set; }
  302. public string biography { get; set; }
  303. public string birthday { get; set; }
  304. public string deathday { get; set; }
  305. public string homepage { get; set; }
  306. public int id { get; set; }
  307. public string imdb_id { get; set; }
  308. public string name { get; set; }
  309. public string place_of_birth { get; set; }
  310. public double popularity { get; set; }
  311. public string profile_path { get; set; }
  312. public Credits credits { get; set; }
  313. public Images images { get; set; }
  314. public ExternalIds external_ids { get; set; }
  315. }
  316. #endregion
  317. public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
  318. {
  319. return _httpClient.GetResponse(new HttpRequestOptions
  320. {
  321. CancellationToken = cancellationToken,
  322. Url = url
  323. });
  324. }
  325. }
  326. }