MovieDbPersonProvider.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. item.PlaceOfBirth = info.place_of_birth;
  143. item.Overview = info.biography;
  144. DateTime date;
  145. if (DateTime.TryParseExact(info.birthday, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
  146. {
  147. item.PremiereDate = date.ToUniversalTime();
  148. }
  149. if (DateTime.TryParseExact(info.deathday, "yyyy-MM-dd", new CultureInfo("en-US"), DateTimeStyles.None, out date))
  150. {
  151. item.EndDate = date.ToUniversalTime();
  152. }
  153. item.SetProviderId(MetadataProviders.Tmdb, info.id.ToString(_usCulture));
  154. if (!string.IsNullOrEmpty(info.imdb_id))
  155. {
  156. item.SetProviderId(MetadataProviders.Imdb, info.imdb_id);
  157. }
  158. result.HasMetadata = true;
  159. result.Item = item;
  160. }
  161. return result;
  162. }
  163. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  164. /// <summary>
  165. /// Gets the TMDB id.
  166. /// </summary>
  167. /// <param name="info">The information.</param>
  168. /// <param name="cancellationToken">The cancellation token.</param>
  169. /// <returns>Task{System.String}.</returns>
  170. private async Task<string> GetTmdbId(PersonLookupInfo info, CancellationToken cancellationToken)
  171. {
  172. var results = await GetSearchResults(info, cancellationToken).ConfigureAwait(false);
  173. return results.Select(i => i.GetProviderId(MetadataProviders.Tmdb)).FirstOrDefault();
  174. }
  175. internal async Task EnsurePersonInfo(string id, CancellationToken cancellationToken)
  176. {
  177. var dataFilePath = GetPersonDataFilePath(_configurationManager.ApplicationPaths, id);
  178. var fileInfo = _fileSystem.GetFileSystemInfo(dataFilePath);
  179. if (fileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 3)
  180. {
  181. return;
  182. }
  183. var url = string.Format(@"https://api.themoviedb.org/3/person/{1}?api_key={0}&append_to_response=credits,images,external_ids", MovieDbProvider.ApiKey, id);
  184. using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  185. {
  186. Url = url,
  187. CancellationToken = cancellationToken,
  188. AcceptHeader = MovieDbProvider.AcceptHeader
  189. }).ConfigureAwait(false))
  190. {
  191. _fileSystem.CreateDirectory(Path.GetDirectoryName(dataFilePath));
  192. using (var fs = _fileSystem.GetFileStream(dataFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true))
  193. {
  194. await json.CopyToAsync(fs).ConfigureAwait(false);
  195. }
  196. }
  197. }
  198. private static string GetPersonDataPath(IApplicationPaths appPaths, string tmdbId)
  199. {
  200. var letter = tmdbId.GetMD5().ToString().Substring(0, 1);
  201. return Path.Combine(GetPersonsDataPath(appPaths), letter, tmdbId);
  202. }
  203. internal static string GetPersonDataFilePath(IApplicationPaths appPaths, string tmdbId)
  204. {
  205. return Path.Combine(GetPersonDataPath(appPaths, tmdbId), DataFileName);
  206. }
  207. private static string GetPersonsDataPath(IApplicationPaths appPaths)
  208. {
  209. return Path.Combine(appPaths.CachePath, "tmdb-people");
  210. }
  211. #region Result Objects
  212. /// <summary>
  213. /// Class PersonSearchResult
  214. /// </summary>
  215. public class PersonSearchResult
  216. {
  217. /// <summary>
  218. /// Gets or sets a value indicating whether this <see cref="MovieDbPersonProvider.PersonSearchResult" /> is adult.
  219. /// </summary>
  220. /// <value><c>true</c> if adult; otherwise, <c>false</c>.</value>
  221. public bool Adult { get; set; }
  222. /// <summary>
  223. /// Gets or sets the id.
  224. /// </summary>
  225. /// <value>The id.</value>
  226. public int Id { get; set; }
  227. /// <summary>
  228. /// Gets or sets the name.
  229. /// </summary>
  230. /// <value>The name.</value>
  231. public string Name { get; set; }
  232. /// <summary>
  233. /// Gets or sets the profile_ path.
  234. /// </summary>
  235. /// <value>The profile_ path.</value>
  236. public string Profile_Path { get; set; }
  237. }
  238. /// <summary>
  239. /// Class PersonSearchResults
  240. /// </summary>
  241. public class PersonSearchResults
  242. {
  243. /// <summary>
  244. /// Gets or sets the page.
  245. /// </summary>
  246. /// <value>The page.</value>
  247. public int Page { get; set; }
  248. /// <summary>
  249. /// Gets or sets the results.
  250. /// </summary>
  251. /// <value>The results.</value>
  252. public List<MovieDbPersonProvider.PersonSearchResult> Results { get; set; }
  253. /// <summary>
  254. /// Gets or sets the total_ pages.
  255. /// </summary>
  256. /// <value>The total_ pages.</value>
  257. public int Total_Pages { get; set; }
  258. /// <summary>
  259. /// Gets or sets the total_ results.
  260. /// </summary>
  261. /// <value>The total_ results.</value>
  262. public int Total_Results { get; set; }
  263. }
  264. public class Cast
  265. {
  266. public int id { get; set; }
  267. public string title { get; set; }
  268. public string character { get; set; }
  269. public string original_title { get; set; }
  270. public string poster_path { get; set; }
  271. public string release_date { get; set; }
  272. public bool adult { get; set; }
  273. }
  274. public class Crew
  275. {
  276. public int id { get; set; }
  277. public string title { get; set; }
  278. public string original_title { get; set; }
  279. public string department { get; set; }
  280. public string job { get; set; }
  281. public string poster_path { get; set; }
  282. public string release_date { get; set; }
  283. public bool adult { get; set; }
  284. }
  285. public class Credits
  286. {
  287. public List<Cast> cast { get; set; }
  288. public List<Crew> crew { get; set; }
  289. }
  290. public class Profile
  291. {
  292. public string file_path { get; set; }
  293. public int width { get; set; }
  294. public int height { get; set; }
  295. public object iso_639_1 { get; set; }
  296. public double aspect_ratio { get; set; }
  297. }
  298. public class Images
  299. {
  300. public List<Profile> profiles { get; set; }
  301. }
  302. public class ExternalIds
  303. {
  304. public string imdb_id { get; set; }
  305. public string freebase_mid { get; set; }
  306. public string freebase_id { get; set; }
  307. public int tvrage_id { get; set; }
  308. }
  309. public class PersonResult
  310. {
  311. public bool adult { get; set; }
  312. public List<object> also_known_as { get; set; }
  313. public string biography { get; set; }
  314. public string birthday { get; set; }
  315. public string deathday { get; set; }
  316. public string homepage { get; set; }
  317. public int id { get; set; }
  318. public string imdb_id { get; set; }
  319. public string name { get; set; }
  320. public string place_of_birth { get; set; }
  321. public double popularity { get; set; }
  322. public string profile_path { get; set; }
  323. public Credits credits { get; set; }
  324. public Images images { get; set; }
  325. public ExternalIds external_ids { get; set; }
  326. }
  327. #endregion
  328. public Task<HttpResponseInfo> GetImageResponse(string url, CancellationToken cancellationToken)
  329. {
  330. return _httpClient.GetResponse(new HttpRequestOptions
  331. {
  332. CancellationToken = cancellationToken,
  333. Url = url,
  334. ResourcePool = MovieDbProvider.Current.MovieDbResourcePool
  335. });
  336. }
  337. }
  338. }