MovieDbPersonProvider.cs 14 KB

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