SearchEngine.cs 13 KB

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