MovieDbSearch.cs 12 KB

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