MovieDbPersonProvider.cs 13 KB

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