MovieDbPersonProvider.cs 13 KB

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