MovieDbPersonProvider.cs 13 KB

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