SearchEngine.cs 13 KB

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