MovieDbPersonProvider.cs 15 KB

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