MovieDbPersonProvider.cs 14 KB

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