MovieDbPersonProvider.cs 14 KB

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