MovieDbSearch.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. switch (type)
  105. {
  106. case "tv":
  107. return await GetSearchResultsTv(name, year, language, baseImageUrl, cancellationToken);
  108. default:
  109. return await GetSearchResultsGeneric(name, type, year, language, baseImageUrl, cancellationToken);
  110. }
  111. }
  112. private async Task<List<RemoteSearchResult>> GetSearchResultsGeneric(string name, string type, int? year, string language, string baseImageUrl, CancellationToken cancellationToken)
  113. {
  114. var url3 = string.Format(Search3, WebUtility.UrlEncode(name), ApiKey, language, type);
  115. using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  116. {
  117. Url = url3,
  118. CancellationToken = cancellationToken,
  119. AcceptHeader = AcceptHeader
  120. }).ConfigureAwait(false))
  121. {
  122. var searchResults = _json.DeserializeFromStream<TmdbMovieSearchResults>(json);
  123. var results = searchResults.results ?? new List<TmdbMovieSearchResult>();
  124. var index = 0;
  125. var resultTuples = results.Select(result => new Tuple<TmdbMovieSearchResult, int>(result, index++)).ToList();
  126. return resultTuples.OrderBy(i => GetSearchResultOrder(i.Item1, year))
  127. .ThenBy(i => i.Item2)
  128. .Select(i => i.Item1)
  129. .Select(i =>
  130. {
  131. var remoteResult = new RemoteSearchResult
  132. {
  133. SearchProviderName = MovieDbProvider.Current.Name,
  134. Name = i.title ?? i.name ?? i.original_title,
  135. ImageUrl = string.IsNullOrWhiteSpace(i.poster_path) ? null : baseImageUrl + i.poster_path
  136. };
  137. if (!string.IsNullOrWhiteSpace(i.release_date))
  138. {
  139. DateTime r;
  140. // These dates are always in this exact format
  141. if (DateTime.TryParseExact(i.release_date, "yyyy-MM-dd", EnUs, DateTimeStyles.None, out r))
  142. {
  143. remoteResult.PremiereDate = r.ToUniversalTime();
  144. remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year;
  145. }
  146. }
  147. remoteResult.SetProviderId(MetadataProviders.Tmdb, i.id.ToString(EnUs));
  148. return remoteResult;
  149. })
  150. .ToList();
  151. }
  152. }
  153. private async Task<List<RemoteSearchResult>> GetSearchResultsTv(string name, int? year, string language, string baseImageUrl, CancellationToken cancellationToken)
  154. {
  155. var url3 = string.Format(Search3, WebUtility.UrlEncode(name), ApiKey, language, "tv");
  156. using (var json = await MovieDbProvider.Current.GetMovieDbResponse(new HttpRequestOptions
  157. {
  158. Url = url3,
  159. CancellationToken = cancellationToken,
  160. AcceptHeader = AcceptHeader
  161. }).ConfigureAwait(false))
  162. {
  163. var searchResults = _json.DeserializeFromStream<TmdbTvSearchResults>(json);
  164. var results = searchResults.results ?? new List<TvResult>();
  165. var index = 0;
  166. var resultTuples = results.Select(result => new Tuple<TvResult, int>(result, index++)).ToList();
  167. return resultTuples.OrderBy(i => GetSearchResultOrder(i.Item1, year))
  168. .ThenBy(i => i.Item2)
  169. .Select(i => i.Item1)
  170. .Select(i =>
  171. {
  172. var remoteResult = new RemoteSearchResult
  173. {
  174. SearchProviderName = MovieDbProvider.Current.Name,
  175. Name = i.name ?? i.original_name,
  176. ImageUrl = string.IsNullOrWhiteSpace(i.poster_path) ? null : baseImageUrl + i.poster_path
  177. };
  178. if (!string.IsNullOrWhiteSpace(i.first_air_date))
  179. {
  180. DateTime r;
  181. // These dates are always in this exact format
  182. if (DateTime.TryParseExact(i.first_air_date, "yyyy-MM-dd", EnUs, DateTimeStyles.None, out r))
  183. {
  184. remoteResult.PremiereDate = r.ToUniversalTime();
  185. remoteResult.ProductionYear = remoteResult.PremiereDate.Value.Year;
  186. }
  187. }
  188. remoteResult.SetProviderId(MetadataProviders.Tmdb, i.id.ToString(EnUs));
  189. return remoteResult;
  190. })
  191. .ToList();
  192. }
  193. }
  194. private int GetSearchResultOrder(TmdbMovieSearchResult result, int? year)
  195. {
  196. if (year.HasValue)
  197. {
  198. DateTime r;
  199. // These dates are always in this exact format
  200. if (DateTime.TryParseExact(result.release_date, "yyyy-MM-dd", EnUs, DateTimeStyles.None, out r))
  201. {
  202. // Allow one year tolernace, preserve order from Tmdb
  203. return Math.Abs(r.Year - year.Value);
  204. }
  205. }
  206. return int.MaxValue;
  207. }
  208. private int GetSearchResultOrder(TvResult result, int? year)
  209. {
  210. if (year.HasValue)
  211. {
  212. DateTime r;
  213. // These dates are always in this exact format
  214. if (DateTime.TryParseExact(result.first_air_date, "yyyy-MM-dd", EnUs, DateTimeStyles.None, out r))
  215. {
  216. // Allow one year tolernace, preserve order from Tmdb
  217. return Math.Abs(r.Year - year.Value);
  218. }
  219. }
  220. return int.MaxValue;
  221. }
  222. /// <summary>
  223. /// Class TmdbMovieSearchResult
  224. /// </summary>
  225. public class TmdbMovieSearchResult
  226. {
  227. /// <summary>
  228. /// Gets or sets a value indicating whether this <see cref="TmdbMovieSearchResult" /> is adult.
  229. /// </summary>
  230. /// <value><c>true</c> if adult; otherwise, <c>false</c>.</value>
  231. public bool adult { get; set; }
  232. /// <summary>
  233. /// Gets or sets the backdrop_path.
  234. /// </summary>
  235. /// <value>The backdrop_path.</value>
  236. public string backdrop_path { get; set; }
  237. /// <summary>
  238. /// Gets or sets the id.
  239. /// </summary>
  240. /// <value>The id.</value>
  241. public int id { get; set; }
  242. /// <summary>
  243. /// Gets or sets the original_title.
  244. /// </summary>
  245. /// <value>The original_title.</value>
  246. public string original_title { get; set; }
  247. /// <summary>
  248. /// Gets or sets the original_name.
  249. /// </summary>
  250. /// <value>The original_name.</value>
  251. public string original_name { get; set; }
  252. /// <summary>
  253. /// Gets or sets the release_date.
  254. /// </summary>
  255. /// <value>The release_date.</value>
  256. public string release_date { get; set; }
  257. /// <summary>
  258. /// Gets or sets the poster_path.
  259. /// </summary>
  260. /// <value>The poster_path.</value>
  261. public string poster_path { get; set; }
  262. /// <summary>
  263. /// Gets or sets the popularity.
  264. /// </summary>
  265. /// <value>The popularity.</value>
  266. public double popularity { get; set; }
  267. /// <summary>
  268. /// Gets or sets the title.
  269. /// </summary>
  270. /// <value>The title.</value>
  271. public string title { get; set; }
  272. /// <summary>
  273. /// Gets or sets the vote_average.
  274. /// </summary>
  275. /// <value>The vote_average.</value>
  276. public double vote_average { get; set; }
  277. /// <summary>
  278. /// For collection search results
  279. /// </summary>
  280. public string name { get; set; }
  281. /// <summary>
  282. /// Gets or sets the vote_count.
  283. /// </summary>
  284. /// <value>The vote_count.</value>
  285. public int vote_count { get; set; }
  286. }
  287. /// <summary>
  288. /// Class TmdbMovieSearchResults
  289. /// </summary>
  290. private class TmdbMovieSearchResults
  291. {
  292. /// <summary>
  293. /// Gets or sets the page.
  294. /// </summary>
  295. /// <value>The page.</value>
  296. public int page { get; set; }
  297. /// <summary>
  298. /// Gets or sets the results.
  299. /// </summary>
  300. /// <value>The results.</value>
  301. public List<TmdbMovieSearchResult> results { get; set; }
  302. /// <summary>
  303. /// Gets or sets the total_pages.
  304. /// </summary>
  305. /// <value>The total_pages.</value>
  306. public int total_pages { get; set; }
  307. /// <summary>
  308. /// Gets or sets the total_results.
  309. /// </summary>
  310. /// <value>The total_results.</value>
  311. public int total_results { get; set; }
  312. }
  313. public class TvResult
  314. {
  315. public string backdrop_path { get; set; }
  316. public string first_air_date { get; set; }
  317. public int id { get; set; }
  318. public string original_name { get; set; }
  319. public string poster_path { get; set; }
  320. public double popularity { get; set; }
  321. public string name { get; set; }
  322. public double vote_average { get; set; }
  323. public int vote_count { get; set; }
  324. }
  325. /// <summary>
  326. /// Class TmdbTvSearchResults
  327. /// </summary>
  328. private class TmdbTvSearchResults
  329. {
  330. /// <summary>
  331. /// Gets or sets the page.
  332. /// </summary>
  333. /// <value>The page.</value>
  334. public int page { get; set; }
  335. /// <summary>
  336. /// Gets or sets the results.
  337. /// </summary>
  338. /// <value>The results.</value>
  339. public List<TvResult> results { get; set; }
  340. /// <summary>
  341. /// Gets or sets the total_pages.
  342. /// </summary>
  343. /// <value>The total_pages.</value>
  344. public int total_pages { get; set; }
  345. /// <summary>
  346. /// Gets or sets the total_results.
  347. /// </summary>
  348. /// <value>The total_results.</value>
  349. public int total_results { get; set; }
  350. }
  351. public class ExternalIdLookupResult
  352. {
  353. public List<object> movie_results { get; set; }
  354. public List<object> person_results { get; set; }
  355. public List<TvResult> tv_results { get; set; }
  356. }
  357. }
  358. }