MovieDbSearch.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. using MediaBrowser.Common.Net;
  2. using MediaBrowser.Controller.Providers;
  3. using MediaBrowser.Model.Entities;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Providers;
  6. using MediaBrowser.Model.Serialization;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Globalization;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. namespace MediaBrowser.Providers.Movies
  15. {
  16. public class MovieDbSearch
  17. {
  18. private static readonly CultureInfo EnUs = new CultureInfo("en-US");
  19. private const string Search3 = @"http://api.themoviedb.org/3/search/{3}?api_key={1}&query={0}&language={2}";
  20. internal static string ApiKey = "f6bd687ffa63cd282b6ff2c6877f2669";
  21. internal static string AcceptHeader = "application/json,image/*";
  22. private readonly ILogger _logger;
  23. private readonly IJsonSerializer _json;
  24. public MovieDbSearch(ILogger logger, IJsonSerializer json)
  25. {
  26. _logger = logger;
  27. _json = json;
  28. }
  29. public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(SeriesInfo idInfo, CancellationToken cancellationToken)
  30. {
  31. return GetSearchResults(idInfo, "tv", cancellationToken);
  32. }
  33. public Task<IEnumerable<RemoteSearchResult>> GetMovieSearchResults(ItemLookupInfo idInfo, CancellationToken cancellationToken)
  34. {
  35. return GetSearchResults(idInfo, "movie", cancellationToken);
  36. }
  37. public Task<IEnumerable<RemoteSearchResult>> GetSearchResults(BoxSetInfo idInfo, CancellationToken cancellationToken)
  38. {
  39. return GetSearchResults(idInfo, "collection", cancellationToken);
  40. }
  41. private async Task<IEnumerable<RemoteSearchResult>> GetSearchResults(ItemLookupInfo idInfo, string searchType, CancellationToken cancellationToken)
  42. {
  43. var name = idInfo.Name;
  44. var year = idInfo.Year;
  45. int? yearInName = null;
  46. var tmdbSettings = await MovieDbProvider.Current.GetTmdbSettings(cancellationToken).ConfigureAwait(false);
  47. var tmdbImageUrl = tmdbSettings.images.base_url + "original";
  48. NameParser.ParseName(name, out name, out yearInName);
  49. year = year ?? yearInName;
  50. _logger.Info("MovieDbProvider: Finding id for item: " + name);
  51. var language = idInfo.MetadataLanguage.ToLower();
  52. //nope - search for it
  53. //var searchType = item is BoxSet ? "collection" : "movie";
  54. var results = await GetSearchResults(name, searchType, year, language, tmdbImageUrl, cancellationToken).ConfigureAwait(false);
  55. if (results.Count == 0)
  56. {
  57. //try in english if wasn't before
  58. if (!string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
  59. {
  60. results = await GetSearchResults(name, searchType, year, "en", tmdbImageUrl, cancellationToken).ConfigureAwait(false);
  61. }
  62. }
  63. if (results.Count == 0)
  64. {
  65. // try with dot and _ turned to space
  66. var originalName = name;
  67. name = name.Replace(",", " ");
  68. name = name.Replace(".", " ");
  69. name = name.Replace("_", " ");
  70. name = name.Replace("-", " ");
  71. name = name.Replace("!", " ");
  72. name = name.Replace("?", " ");
  73. name = name.Trim();
  74. // Search again if the new name is different
  75. if (!string.Equals(name, originalName))
  76. {
  77. results = await GetSearchResults(name, searchType, year, language, tmdbImageUrl, cancellationToken).ConfigureAwait(false);
  78. if (results.Count == 0 && !string.Equals(language, "en", StringComparison.OrdinalIgnoreCase))
  79. {
  80. //one more time, in english
  81. results = await GetSearchResults(name, searchType, year, "en", tmdbImageUrl, cancellationToken).ConfigureAwait(false);
  82. }
  83. }
  84. }
  85. return results.Where(i =>
  86. {
  87. if (year.HasValue && i.ProductionYear.HasValue)
  88. {
  89. return year.Value == i.ProductionYear.Value;
  90. }
  91. return true;
  92. });
  93. }
  94. private async Task<List<RemoteSearchResult>> GetSearchResults(string name, string type, int? year, string language, string baseImageUrl, CancellationToken cancellationToken)
  95. {
  96. var url3 = string.Format(Search3, WebUtility.UrlEncode(name), ApiKey, language, type);
  97. using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  98. {
  99. Url = url3,
  100. CancellationToken = cancellationToken,
  101. AcceptHeader = AcceptHeader
  102. }).ConfigureAwait(false))
  103. {
  104. var searchResults = _json.DeserializeFromStream<TmdbMovieSearchResults>(json);
  105. var results = searchResults.results ?? new List<TmdbMovieSearchResult>();
  106. var index = 0;
  107. var resultTuples = results.Select(result => new Tuple<TmdbMovieSearchResult, int>(result, index++)).ToList();
  108. return resultTuples.OrderBy(i => GetSearchResultOrder(i.Item1, year))
  109. .ThenBy(i => i.Item2)
  110. .Select(i => i.Item1)
  111. .Select(i =>
  112. {
  113. var remoteResult = new RemoteSearchResult
  114. {
  115. SearchProviderName = MovieDbProvider.Current.Name,
  116. Name = i.title ?? i.original_title ?? i.name,
  117. ImageUrl = string.IsNullOrWhiteSpace(i.poster_path) ? null : baseImageUrl + i.poster_path
  118. };
  119. if (!string.IsNullOrWhiteSpace(i.release_date))
  120. {
  121. DateTime r;
  122. // These dates are always in this exact format
  123. if (DateTime.TryParseExact(i.release_date, "yyyy-MM-dd", EnUs, DateTimeStyles.None, out r))
  124. {
  125. remoteResult.PremiereDate = r.ToUniversalTime();
  126. remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year;
  127. }
  128. }
  129. remoteResult.SetProviderId(MetadataProviders.Tmdb, i.id.ToString(EnUs));
  130. return remoteResult;
  131. })
  132. .ToList();
  133. }
  134. }
  135. private int GetSearchResultOrder(TmdbMovieSearchResult result, int? year)
  136. {
  137. if (year.HasValue)
  138. {
  139. DateTime r;
  140. // These dates are always in this exact format
  141. if (DateTime.TryParseExact(result.release_date, "yyyy-MM-dd", EnUs, DateTimeStyles.None, out r))
  142. {
  143. return Math.Abs(r.Year - year.Value);
  144. }
  145. }
  146. return 0;
  147. }
  148. /// <summary>
  149. /// Class TmdbMovieSearchResult
  150. /// </summary>
  151. public class TmdbMovieSearchResult
  152. {
  153. /// <summary>
  154. /// Gets or sets a value indicating whether this <see cref="TmdbMovieSearchResult" /> is adult.
  155. /// </summary>
  156. /// <value><c>true</c> if adult; otherwise, <c>false</c>.</value>
  157. public bool adult { get; set; }
  158. /// <summary>
  159. /// Gets or sets the backdrop_path.
  160. /// </summary>
  161. /// <value>The backdrop_path.</value>
  162. public string backdrop_path { get; set; }
  163. /// <summary>
  164. /// Gets or sets the id.
  165. /// </summary>
  166. /// <value>The id.</value>
  167. public int id { get; set; }
  168. /// <summary>
  169. /// Gets or sets the original_title.
  170. /// </summary>
  171. /// <value>The original_title.</value>
  172. public string original_title { get; set; }
  173. /// <summary>
  174. /// Gets or sets the release_date.
  175. /// </summary>
  176. /// <value>The release_date.</value>
  177. public string release_date { get; set; }
  178. /// <summary>
  179. /// Gets or sets the poster_path.
  180. /// </summary>
  181. /// <value>The poster_path.</value>
  182. public string poster_path { get; set; }
  183. /// <summary>
  184. /// Gets or sets the popularity.
  185. /// </summary>
  186. /// <value>The popularity.</value>
  187. public double popularity { get; set; }
  188. /// <summary>
  189. /// Gets or sets the title.
  190. /// </summary>
  191. /// <value>The title.</value>
  192. public string title { get; set; }
  193. /// <summary>
  194. /// Gets or sets the vote_average.
  195. /// </summary>
  196. /// <value>The vote_average.</value>
  197. public double vote_average { get; set; }
  198. /// <summary>
  199. /// For collection search results
  200. /// </summary>
  201. public string name { get; set; }
  202. /// <summary>
  203. /// Gets or sets the vote_count.
  204. /// </summary>
  205. /// <value>The vote_count.</value>
  206. public int vote_count { get; set; }
  207. }
  208. /// <summary>
  209. /// Class TmdbMovieSearchResults
  210. /// </summary>
  211. private class TmdbMovieSearchResults
  212. {
  213. /// <summary>
  214. /// Gets or sets the page.
  215. /// </summary>
  216. /// <value>The page.</value>
  217. public int page { get; set; }
  218. /// <summary>
  219. /// Gets or sets the results.
  220. /// </summary>
  221. /// <value>The results.</value>
  222. public List<TmdbMovieSearchResult> results { get; set; }
  223. /// <summary>
  224. /// Gets or sets the total_pages.
  225. /// </summary>
  226. /// <value>The total_pages.</value>
  227. public int total_pages { get; set; }
  228. /// <summary>
  229. /// Gets or sets the total_results.
  230. /// </summary>
  231. /// <value>The total_results.</value>
  232. public int total_results { get; set; }
  233. }
  234. public class TvResult
  235. {
  236. public string backdrop_path { get; set; }
  237. public int id { get; set; }
  238. public string original_name { get; set; }
  239. public string first_air_date { get; set; }
  240. public string poster_path { get; set; }
  241. public double popularity { get; set; }
  242. public string name { get; set; }
  243. public double vote_average { get; set; }
  244. public int vote_count { get; set; }
  245. }
  246. public class ExternalIdLookupResult
  247. {
  248. public List<object> movie_results { get; set; }
  249. public List<object> person_results { get; set; }
  250. public List<TvResult> tv_results { get; set; }
  251. }
  252. }
  253. }