TmdbPersonProvider.cs 10 KB

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