MovieDbPersonProvider.cs 15 KB

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