MovieDbPersonProvider.cs 15 KB

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