MovieDbPersonProvider.cs 15 KB

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