SearchEngine.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Entities.Audio;
  4. using MediaBrowser.Controller.Entities.TV;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Querying;
  8. using MediaBrowser.Model.Search;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Threading.Tasks;
  13. namespace MediaBrowser.Server.Implementations.Library
  14. {
  15. /// <summary>
  16. /// Class LuceneSearchEngine
  17. /// http://www.codeproject.com/Articles/320219/Lucene-Net-ultra-fast-search-for-MVC-or-WebForms
  18. /// </summary>
  19. public class SearchEngine : ISearchEngine
  20. {
  21. private readonly ILibraryManager _libraryManager;
  22. private readonly IUserManager _userManager;
  23. private readonly ILogger _logger;
  24. public SearchEngine(ILogManager logManager, ILibraryManager libraryManager, IUserManager userManager)
  25. {
  26. _libraryManager = libraryManager;
  27. _userManager = userManager;
  28. _logger = logManager.GetLogger("Lucene");
  29. }
  30. public async Task<QueryResult<SearchHintInfo>> GetSearchHints(SearchQuery query)
  31. {
  32. IEnumerable<BaseItem> inputItems;
  33. Func<BaseItem, bool> filter = i => !(i is ICollectionFolder);
  34. if (string.IsNullOrWhiteSpace(query.UserId))
  35. {
  36. inputItems = _libraryManager.RootFolder.GetRecursiveChildren(filter);
  37. }
  38. else
  39. {
  40. var user = _userManager.GetUserById(query.UserId);
  41. inputItems = user.RootFolder.GetRecursiveChildren(user, filter);
  42. }
  43. inputItems = _libraryManager.ReplaceVideosWithPrimaryVersions(inputItems);
  44. var results = await GetSearchHints(inputItems, query).ConfigureAwait(false);
  45. // Include item types
  46. if (query.IncludeItemTypes.Length > 0)
  47. {
  48. results = results.Where(f => query.IncludeItemTypes.Contains(f.Item.GetType().Name, StringComparer.OrdinalIgnoreCase));
  49. }
  50. var searchResultArray = results.ToArray();
  51. results = searchResultArray;
  52. var count = searchResultArray.Length;
  53. if (query.StartIndex.HasValue)
  54. {
  55. results = results.Skip(query.StartIndex.Value);
  56. }
  57. if (query.Limit.HasValue)
  58. {
  59. results = results.Take(query.Limit.Value);
  60. }
  61. return new QueryResult<SearchHintInfo>
  62. {
  63. TotalRecordCount = count,
  64. Items = results.ToArray()
  65. };
  66. }
  67. /// <summary>
  68. /// Gets the search hints.
  69. /// </summary>
  70. /// <param name="inputItems">The input items.</param>
  71. /// <param name="query">The query.</param>
  72. /// <returns>IEnumerable{SearchHintResult}.</returns>
  73. /// <exception cref="System.ArgumentNullException">searchTerm</exception>
  74. private Task<IEnumerable<SearchHintInfo>> GetSearchHints(IEnumerable<BaseItem> inputItems, SearchQuery query)
  75. {
  76. var searchTerm = query.SearchTerm;
  77. if (string.IsNullOrWhiteSpace(searchTerm))
  78. {
  79. throw new ArgumentNullException("searchTerm");
  80. }
  81. searchTerm = searchTerm.RemoveDiacritics();
  82. var terms = GetWords(searchTerm);
  83. var hints = new List<Tuple<BaseItem, string, int>>();
  84. var items = inputItems.Where(i => !(i is MusicArtist)).ToList();
  85. if (query.IncludeMedia)
  86. {
  87. // Add search hints based on item name
  88. hints.AddRange(items.Where(i => !string.IsNullOrWhiteSpace(i.Name) && IncludeInSearch(i)).Select(item =>
  89. {
  90. var index = GetIndex(item.Name, searchTerm, terms);
  91. return new Tuple<BaseItem, string, int>(item, index.Item1, index.Item2);
  92. }));
  93. }
  94. if (query.IncludeArtists)
  95. {
  96. // Find artists
  97. var artists = items.OfType<Audio>()
  98. .SelectMany(i => i.AllArtists)
  99. .Where(i => !string.IsNullOrWhiteSpace(i))
  100. .DistinctNames()
  101. .ToList();
  102. foreach (var item in artists)
  103. {
  104. var index = GetIndex(item, searchTerm, terms);
  105. if (index.Item2 != -1)
  106. {
  107. try
  108. {
  109. var artist = _libraryManager.GetArtist(item);
  110. hints.Add(new Tuple<BaseItem, string, int>(artist, index.Item1, index.Item2));
  111. }
  112. catch (Exception ex)
  113. {
  114. _logger.ErrorException("Error getting {0}", ex, item);
  115. }
  116. }
  117. }
  118. }
  119. if (query.IncludeGenres)
  120. {
  121. // Find genres, from non-audio items
  122. var genres = items.Where(i => !(i is IHasMusicGenres) && !(i is Game))
  123. .SelectMany(i => i.Genres)
  124. .Where(i => !string.IsNullOrWhiteSpace(i))
  125. .Distinct(StringComparer.OrdinalIgnoreCase)
  126. .ToList();
  127. foreach (var item in genres)
  128. {
  129. var index = GetIndex(item, searchTerm, terms);
  130. if (index.Item2 != -1)
  131. {
  132. try
  133. {
  134. var genre = _libraryManager.GetGenre(item);
  135. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  136. }
  137. catch (Exception ex)
  138. {
  139. _logger.ErrorException("Error getting {0}", ex, item);
  140. }
  141. }
  142. }
  143. // Find music genres
  144. var musicGenres = items.Where(i => i is IHasMusicGenres)
  145. .SelectMany(i => i.Genres)
  146. .Where(i => !string.IsNullOrWhiteSpace(i))
  147. .Distinct(StringComparer.OrdinalIgnoreCase)
  148. .ToList();
  149. foreach (var item in musicGenres)
  150. {
  151. var index = GetIndex(item, searchTerm, terms);
  152. if (index.Item2 != -1)
  153. {
  154. try
  155. {
  156. var genre = _libraryManager.GetMusicGenre(item);
  157. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  158. }
  159. catch (Exception ex)
  160. {
  161. _logger.ErrorException("Error getting {0}", ex, item);
  162. }
  163. }
  164. }
  165. // Find music genres
  166. var gameGenres = items.OfType<Game>()
  167. .SelectMany(i => i.Genres)
  168. .Where(i => !string.IsNullOrWhiteSpace(i))
  169. .Distinct(StringComparer.OrdinalIgnoreCase)
  170. .ToList();
  171. foreach (var item in gameGenres)
  172. {
  173. var index = GetIndex(item, searchTerm, terms);
  174. if (index.Item2 != -1)
  175. {
  176. try
  177. {
  178. var genre = _libraryManager.GetGameGenre(item);
  179. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  180. }
  181. catch (Exception ex)
  182. {
  183. _logger.ErrorException("Error getting {0}", ex, item);
  184. }
  185. }
  186. }
  187. }
  188. if (query.IncludeStudios)
  189. {
  190. // Find studios
  191. var studios = items.SelectMany(i => i.Studios)
  192. .Where(i => !string.IsNullOrWhiteSpace(i))
  193. .Distinct(StringComparer.OrdinalIgnoreCase)
  194. .ToList();
  195. foreach (var item in studios)
  196. {
  197. var index = GetIndex(item, searchTerm, terms);
  198. if (index.Item2 != -1)
  199. {
  200. try
  201. {
  202. var studio = _libraryManager.GetStudio(item);
  203. hints.Add(new Tuple<BaseItem, string, int>(studio, index.Item1, index.Item2));
  204. }
  205. catch (Exception ex)
  206. {
  207. _logger.ErrorException("Error getting {0}", ex, item);
  208. }
  209. }
  210. }
  211. }
  212. if (query.IncludePeople)
  213. {
  214. var itemIds = items.Select(i => i.Id).ToList();
  215. // Find persons
  216. var persons = _libraryManager.GetPeople(new InternalPeopleQuery
  217. {
  218. NameContains = searchTerm
  219. })
  220. .Where(i => itemIds.Contains(i.ItemId))
  221. .Select(i => i.Name)
  222. .Distinct(StringComparer.OrdinalIgnoreCase)
  223. .ToList();
  224. foreach (var item in persons)
  225. {
  226. var index = GetIndex(item, searchTerm, terms);
  227. if (index.Item2 != -1)
  228. {
  229. try
  230. {
  231. var person = _libraryManager.GetPerson(item);
  232. hints.Add(new Tuple<BaseItem, string, int>(person, index.Item1, index.Item2));
  233. }
  234. catch (Exception ex)
  235. {
  236. _logger.ErrorException("Error getting {0}", ex, item);
  237. }
  238. }
  239. }
  240. }
  241. var returnValue = hints.Where(i => i.Item3 >= 0).OrderBy(i => i.Item3).Select(i => new SearchHintInfo
  242. {
  243. Item = i.Item1,
  244. MatchedTerm = i.Item2
  245. });
  246. return Task.FromResult(returnValue);
  247. }
  248. private bool IncludeInSearch(BaseItem item)
  249. {
  250. var episode = item as Episode;
  251. if (episode != null)
  252. {
  253. if (episode.IsVirtualUnaired || episode.IsMissingEpisode)
  254. {
  255. return false;
  256. }
  257. }
  258. return true;
  259. }
  260. /// <summary>
  261. /// Gets the index.
  262. /// </summary>
  263. /// <param name="input">The input.</param>
  264. /// <param name="searchInput">The search input.</param>
  265. /// <param name="searchWords">The search input.</param>
  266. /// <returns>System.Int32.</returns>
  267. private Tuple<string, int> GetIndex(string input, string searchInput, List<string> searchWords)
  268. {
  269. if (string.IsNullOrWhiteSpace(input))
  270. {
  271. throw new ArgumentNullException("input");
  272. }
  273. input = input.RemoveDiacritics();
  274. if (string.Equals(input, searchInput, StringComparison.OrdinalIgnoreCase))
  275. {
  276. return new Tuple<string, int>(searchInput, 0);
  277. }
  278. var index = input.IndexOf(searchInput, StringComparison.OrdinalIgnoreCase);
  279. if (index == 0)
  280. {
  281. return new Tuple<string, int>(searchInput, 1);
  282. }
  283. if (index > 0)
  284. {
  285. return new Tuple<string, int>(searchInput, 2);
  286. }
  287. var items = GetWords(input);
  288. for (var i = 0; i < searchWords.Count; i++)
  289. {
  290. var searchTerm = searchWords[i];
  291. for (var j = 0; j < items.Count; j++)
  292. {
  293. var item = items[j];
  294. if (string.Equals(item, searchTerm, StringComparison.OrdinalIgnoreCase))
  295. {
  296. return new Tuple<string, int>(searchTerm, 3 + (i + 1) * (j + 1));
  297. }
  298. index = item.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase);
  299. if (index == 0)
  300. {
  301. return new Tuple<string, int>(searchTerm, 4 + (i + 1) * (j + 1));
  302. }
  303. if (index > 0)
  304. {
  305. return new Tuple<string, int>(searchTerm, 5 + (i + 1) * (j + 1));
  306. }
  307. }
  308. }
  309. return new Tuple<string, int>(null, -1);
  310. }
  311. /// <summary>
  312. /// Gets the words.
  313. /// </summary>
  314. /// <param name="term">The term.</param>
  315. /// <returns>System.String[][].</returns>
  316. private List<string> GetWords(string term)
  317. {
  318. var stoplist = GetStopList().ToList();
  319. return term.Split()
  320. .Where(i => !string.IsNullOrWhiteSpace(i) && !stoplist.Contains(i, StringComparer.OrdinalIgnoreCase))
  321. .ToList();
  322. }
  323. private IEnumerable<string> GetStopList()
  324. {
  325. return new[]
  326. {
  327. "the",
  328. "a",
  329. "of",
  330. "an"
  331. };
  332. }
  333. }
  334. }