TmdbPersonProvider.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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.Plugins.Tmdb.Models.General;
  21. using MediaBrowser.Providers.Plugins.Tmdb.Models.People;
  22. using MediaBrowser.Providers.Plugins.Tmdb.Models.Search;
  23. using MediaBrowser.Providers.Plugins.Tmdb.Movies;
  24. using Microsoft.Extensions.Logging;
  25. namespace MediaBrowser.Providers.Plugins.Tmdb.People
  26. {
  27. public class TmdbPersonProvider : IRemoteMetadataProvider<Person, PersonLookupInfo>
  28. {
  29. const string DataFileName = "info.json";
  30. internal static TmdbPersonProvider Current { get; private set; }
  31. private readonly IJsonSerializer _jsonSerializer;
  32. private readonly IFileSystem _fileSystem;
  33. private readonly IServerConfigurationManager _configurationManager;
  34. private readonly IHttpClient _httpClient;
  35. private readonly ILogger<TmdbPersonProvider> _logger;
  36. public TmdbPersonProvider(
  37. IFileSystem fileSystem,
  38. IServerConfigurationManager configurationManager,
  39. IJsonSerializer jsonSerializer,
  40. IHttpClient httpClient,
  41. ILogger<TmdbPersonProvider> logger)
  42. {
  43. _fileSystem = fileSystem;
  44. _configurationManager = configurationManager;
  45. _jsonSerializer = jsonSerializer;
  46. _httpClient = httpClient;
  47. _logger = logger;
  48. Current = this;
  49. }
  50. public string Name => TmdbUtils.ProviderName;
  51. public async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(PersonLookupInfo searchInfo, CancellationToken cancellationToken)
  52. {
  53. var tmdbId = searchInfo.GetProviderId(MetadataProvider.Tmdb);
  54. var tmdbSettings = await TmdbMovieProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
  55. var tmdbImageUrl = tmdbSettings.images.GetImageUrl("original");
  56. if (!string.IsNullOrEmpty(tmdbId))
  57. {
  58. await EnsurePersonInfo(tmdbId, cancellationToken).ConfigureAwait(false);
  59. var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, tmdbId);
  60. var info = _jsonSerializer.DeserializeFromFile<PersonResult>(dataFilePath);
  61. var images = (info.Images ?? new PersonImages()).Profiles ?? new List<Profile>();
  62. var result = new RemoteSearchResult
  63. {
  64. Name = info.Name,
  65. SearchProviderName = Name,
  66. ImageUrl = images.Count == 0 ? null : (tmdbImageUrl + images[0].File_Path)
  67. };
  68. result.SetProviderId(MetadataProvider.Tmdb, info.Id.ToString(_usCulture));
  69. result.SetProviderId(MetadataProvider.Imdb, info.Imdb_Id);
  70. return new[] { result };
  71. }
  72. if (searchInfo.IsAutomated)
  73. {
  74. // Don't hammer moviedb searching by name
  75. return new List<RemoteSearchResult>();
  76. }
  77. var url = string.Format(TmdbUtils.BaseTmdbApiUrl + @"3/search/person?api_key={1}&query={0}", WebUtility.UrlEncode(searchInfo.Name), TmdbUtils.ApiKey);
  78. using (var response = await TmdbMovieProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  79. {
  80. Url = url,
  81. CancellationToken = cancellationToken,
  82. AcceptHeader = TmdbUtils.AcceptHeader
  83. }).ConfigureAwait(false))
  84. {
  85. using (var json = response.Content)
  86. {
  87. var result = await _jsonSerializer.DeserializeFromStreamAsync<TmdbSearchResult<PersonSearchResult>>(json).ConfigureAwait(false) ??
  88. new TmdbSearchResult<PersonSearchResult>();
  89. return result.Results.Select(i => GetSearchResult(i, tmdbImageUrl));
  90. }
  91. }
  92. }
  93. private RemoteSearchResult GetSearchResult(PersonSearchResult i, string baseImageUrl)
  94. {
  95. var result = new RemoteSearchResult
  96. {
  97. SearchProviderName = Name,
  98. Name = i.Name,
  99. ImageUrl = string.IsNullOrEmpty(i.Profile_Path) ? null : baseImageUrl + i.Profile_Path
  100. };
  101. result.SetProviderId(MetadataProvider.Tmdb, i.Id.ToString(_usCulture));
  102. return result;
  103. }
  104. public async Task<MetadataResult<Person>> GetMetadata(PersonLookupInfo id, CancellationToken cancellationToken)
  105. {
  106. var tmdbId = id.GetProviderId(MetadataProvider.Tmdb);
  107. // We don't already have an Id, need to fetch it
  108. if (string.IsNullOrEmpty(tmdbId))
  109. {
  110. tmdbId = await GetTmdbId(id, cancellationToken).ConfigureAwait(false);
  111. }
  112. var result = new MetadataResult<Person>();
  113. if (!string.IsNullOrEmpty(tmdbId))
  114. {
  115. try
  116. {
  117. await EnsurePersonInfo(tmdbId, cancellationToken).ConfigureAwait(false);
  118. }
  119. catch (HttpException ex)
  120. {
  121. if (ex.StatusCode.HasValue && ex.StatusCode.Value == HttpStatusCode.NotFound)
  122. {
  123. return result;
  124. }
  125. throw;
  126. }
  127. var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, tmdbId);
  128. var info = _jsonSerializer.DeserializeFromFile<PersonResult>(dataFilePath);
  129. var item = new Person();
  130. result.HasMetadata = true;
  131. // Take name from incoming info, don't rename the person
  132. // TODO: This should go in PersonMetadataService, not each person provider
  133. item.Name = id.Name;
  134. //item.HomePageUrl = info.homepage;
  135. if (!string.IsNullOrWhiteSpace(info.Place_Of_Birth))
  136. {
  137. item.ProductionLocations = new string[] { info.Place_Of_Birth };
  138. }
  139. item.Overview = info.Biography;
  140. if (DateTime.TryParseExact(info.Birthday, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out var date))
  141. {
  142. item.PremiereDate = date.ToUniversalTime();
  143. }
  144. if (DateTime.TryParseExact(info.Deathday, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
  145. {
  146. item.EndDate = date.ToUniversalTime();
  147. }
  148. item.SetProviderId(MetadataProvider.Tmdb, info.Id.ToString(_usCulture));
  149. if (!string.IsNullOrEmpty(info.Imdb_Id))
  150. {
  151. item.SetProviderId(MetadataProvider.Imdb, info.Imdb_Id);
  152. }
  153. result.HasMetadata = true;
  154. result.Item = item;
  155. }
  156. return result;
  157. }
  158. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  159. /// <summary>
  160. /// Gets the TMDB id.
  161. /// </summary>
  162. /// <param name="info">The information.</param>
  163. /// <param name="cancellationToken">The cancellation token.</param>
  164. /// <returns>Task{System.String}.</returns>
  165. private async Task<string> GetTmdbId(PersonLookupInfo info, CancellationToken cancellationToken)
  166. {
  167. var results = await GetSearchResults(info, cancellationToken).ConfigureAwait(false);
  168. return results.Select(i => i.GetProviderId(MetadataProvider.Tmdb)).FirstOrDefault();
  169. }
  170. internal async Task EnsurePersonInfo(string id, CancellationToken cancellationToken)
  171. {
  172. var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, id);
  173. var fileInfo = _fileSystem.GetFileSystemInfo(dataFilePath);
  174. if (fileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
  175. {
  176. return;
  177. }
  178. var url = string.Format(TmdbUtils.BaseTmdbApiUrl + @"3/person/{1}?api_key={0}&append_to_response=credits,images,external_ids", TmdbUtils.ApiKey, id);
  179. using (var response = await TmdbMovieProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  180. {
  181. Url = url,
  182. CancellationToken = cancellationToken,
  183. AcceptHeader = TmdbUtils.AcceptHeader
  184. }).ConfigureAwait(false))
  185. {
  186. using (var json = response.Content)
  187. {
  188. Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
  189. using (var fs = new FileStream(dataFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true))
  190. {
  191. await json.CopyToAsync(fs).ConfigureAwait(false);
  192. }
  193. }
  194. }
  195. }
  196. private static string GetPersonDataPath(IApplicationPaths appPaths, string tmdbId)
  197. {
  198. var letter = tmdbId.GetMD5().ToString().Substring(0, 1);
  199. return Path.Combine(GetPersonsDataPath(appPaths), letter, tmdbId);
  200. }
  201. internal static string GetPersonDataFilePath(IApplicationPaths appPaths, string tmdbId)
  202. {
  203. return Path.Combine(GetPersonDataPath(appPaths, tmdbId), DataFileName);
  204. }
  205. private static string GetPersonsDataPath(IApplicationPaths appPaths)
  206. {
  207. return Path.Combine(appPaths.CachePath, "tmdb-people");
  208. }
  209. public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
  210. {
  211. return _httpClient.GetResponse(new HttpRequestOptions
  212. {
  213. CancellationToken = cancellationToken,
  214. Url = url
  215. });
  216. }
  217. }
  218. }