SearchEngine.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. var user = _userManager.GetUserById(new Guid(query.UserId));
  31. var inputItems = user.RootFolder.GetRecursiveChildren(user, null).Where(i => !(i is ICollectionFolder));
  32. var results = await GetSearchHints(inputItems, query).ConfigureAwait(false);
  33. var searchResultArray = results.ToArray();
  34. results = searchResultArray;
  35. var count = searchResultArray.Length;
  36. if (query.StartIndex.HasValue)
  37. {
  38. results = results.Skip(query.StartIndex.Value);
  39. }
  40. if (query.Limit.HasValue)
  41. {
  42. results = results.Take(query.Limit.Value);
  43. }
  44. return new QueryResult<SearchHintInfo>
  45. {
  46. TotalRecordCount = count,
  47. Items = results.ToArray()
  48. };
  49. }
  50. /// <summary>
  51. /// Gets the search hints.
  52. /// </summary>
  53. /// <param name="inputItems">The input items.</param>
  54. /// <param name="query">The query.</param>
  55. /// <returns>IEnumerable{SearchHintResult}.</returns>
  56. /// <exception cref="System.ArgumentNullException">searchTerm</exception>
  57. private Task<IEnumerable<SearchHintInfo>> GetSearchHints(IEnumerable<BaseItem> inputItems, SearchQuery query)
  58. {
  59. var searchTerm = query.SearchTerm;
  60. if (string.IsNullOrEmpty(searchTerm))
  61. {
  62. throw new ArgumentNullException("searchTerm");
  63. }
  64. var terms = GetWords(searchTerm);
  65. var hints = new List<Tuple<BaseItem, string, int>>();
  66. var items = inputItems.Where(i => !(i is MusicArtist)).ToList();
  67. if (query.IncludeMedia)
  68. {
  69. // Add search hints based on item name
  70. hints.AddRange(items.Where(i => !string.IsNullOrEmpty(i.Name)).Select(item =>
  71. {
  72. var index = GetIndex(item.Name, searchTerm, terms);
  73. return new Tuple<BaseItem, string, int>(item, index.Item1, index.Item2);
  74. }));
  75. }
  76. if (query.IncludeArtists)
  77. {
  78. // Find artists
  79. var artists = _libraryManager.GetAllArtists(items)
  80. .ToList();
  81. foreach (var item in artists)
  82. {
  83. var index = GetIndex(item, searchTerm, terms);
  84. if (index.Item2 != -1)
  85. {
  86. try
  87. {
  88. var artist = _libraryManager.GetArtist(item);
  89. hints.Add(new Tuple<BaseItem, string, int>(artist, index.Item1, index.Item2));
  90. }
  91. catch (Exception ex)
  92. {
  93. _logger.ErrorException("Error getting {0}", ex, item);
  94. }
  95. }
  96. }
  97. }
  98. if (query.IncludeGenres)
  99. {
  100. // Find genres, from non-audio items
  101. var genres = items.Where(i => !(i is IHasMusicGenres) && !(i is Game))
  102. .SelectMany(i => i.Genres)
  103. .Where(i => !string.IsNullOrEmpty(i))
  104. .Distinct(StringComparer.OrdinalIgnoreCase)
  105. .ToList();
  106. foreach (var item in genres)
  107. {
  108. var index = GetIndex(item, searchTerm, terms);
  109. if (index.Item2 != -1)
  110. {
  111. try
  112. {
  113. var genre = _libraryManager.GetGenre(item);
  114. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  115. }
  116. catch (Exception ex)
  117. {
  118. _logger.ErrorException("Error getting {0}", ex, item);
  119. }
  120. }
  121. }
  122. // Find music genres
  123. var musicGenres = items.Where(i => i is IHasMusicGenres)
  124. .SelectMany(i => i.Genres)
  125. .Where(i => !string.IsNullOrEmpty(i))
  126. .Distinct(StringComparer.OrdinalIgnoreCase)
  127. .ToList();
  128. foreach (var item in musicGenres)
  129. {
  130. var index = GetIndex(item, searchTerm, terms);
  131. if (index.Item2 != -1)
  132. {
  133. try
  134. {
  135. var genre = _libraryManager.GetMusicGenre(item);
  136. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  137. }
  138. catch (Exception ex)
  139. {
  140. _logger.ErrorException("Error getting {0}", ex, item);
  141. }
  142. }
  143. }
  144. // Find music genres
  145. var gameGenres = items.OfType<Game>()
  146. .SelectMany(i => i.Genres)
  147. .Where(i => !string.IsNullOrEmpty(i))
  148. .Distinct(StringComparer.OrdinalIgnoreCase)
  149. .ToList();
  150. foreach (var item in gameGenres)
  151. {
  152. var index = GetIndex(item, searchTerm, terms);
  153. if (index.Item2 != -1)
  154. {
  155. try
  156. {
  157. var genre = _libraryManager.GetGameGenre(item);
  158. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  159. }
  160. catch (Exception ex)
  161. {
  162. _logger.ErrorException("Error getting {0}", ex, item);
  163. }
  164. }
  165. }
  166. }
  167. if (query.IncludeStudios)
  168. {
  169. // Find studios
  170. var studios = items.SelectMany(i => i.Studios)
  171. .Where(i => !string.IsNullOrEmpty(i))
  172. .Distinct(StringComparer.OrdinalIgnoreCase)
  173. .ToList();
  174. foreach (var item in studios)
  175. {
  176. var index = GetIndex(item, searchTerm, terms);
  177. if (index.Item2 != -1)
  178. {
  179. try
  180. {
  181. var studio = _libraryManager.GetStudio(item);
  182. hints.Add(new Tuple<BaseItem, string, int>(studio, index.Item1, index.Item2));
  183. }
  184. catch (Exception ex)
  185. {
  186. _logger.ErrorException("Error getting {0}", ex, item);
  187. }
  188. }
  189. }
  190. }
  191. if (query.IncludePeople)
  192. {
  193. // Find persons
  194. var persons = items.SelectMany(i => i.People)
  195. .Select(i => i.Name)
  196. .Where(i => !string.IsNullOrEmpty(i))
  197. .Distinct(StringComparer.OrdinalIgnoreCase)
  198. .ToList();
  199. foreach (var item in persons)
  200. {
  201. var index = GetIndex(item, searchTerm, terms);
  202. if (index.Item2 != -1)
  203. {
  204. try
  205. {
  206. var person = _libraryManager.GetPerson(item);
  207. hints.Add(new Tuple<BaseItem, string, int>(person, index.Item1, index.Item2));
  208. }
  209. catch (Exception ex)
  210. {
  211. _logger.ErrorException("Error getting {0}", ex, item);
  212. }
  213. }
  214. }
  215. }
  216. var returnValue = hints.Where(i => i.Item3 >= 0).OrderBy(i => i.Item3).Select(i => new SearchHintInfo
  217. {
  218. Item = i.Item1,
  219. MatchedTerm = i.Item2
  220. });
  221. return Task.FromResult(returnValue);
  222. }
  223. /// <summary>
  224. /// Gets the index.
  225. /// </summary>
  226. /// <param name="input">The input.</param>
  227. /// <param name="searchInput">The search input.</param>
  228. /// <param name="searchWords">The search input.</param>
  229. /// <returns>System.Int32.</returns>
  230. private Tuple<string, int> GetIndex(string input, string searchInput, List<string> searchWords)
  231. {
  232. if (string.IsNullOrEmpty(input))
  233. {
  234. throw new ArgumentNullException("input");
  235. }
  236. if (string.Equals(input, searchInput, StringComparison.OrdinalIgnoreCase))
  237. {
  238. return new Tuple<string, int>(searchInput, 0);
  239. }
  240. var index = input.IndexOf(searchInput, StringComparison.OrdinalIgnoreCase);
  241. if (index == 0)
  242. {
  243. return new Tuple<string, int>(searchInput, 1);
  244. }
  245. if (index > 0)
  246. {
  247. return new Tuple<string, int>(searchInput, 2);
  248. }
  249. var items = GetWords(input);
  250. for (var i = 0; i < searchWords.Count; i++)
  251. {
  252. var searchTerm = searchWords[i];
  253. for (var j = 0; j < items.Count; j++)
  254. {
  255. var item = items[j];
  256. if (string.Equals(item, searchTerm, StringComparison.OrdinalIgnoreCase))
  257. {
  258. return new Tuple<string, int>(searchTerm, 3 + (i + 1) * (j + 1));
  259. }
  260. index = item.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase);
  261. if (index == 0)
  262. {
  263. return new Tuple<string, int>(searchTerm, 4 + (i + 1) * (j + 1));
  264. }
  265. if (index > 0)
  266. {
  267. return new Tuple<string, int>(searchTerm, 5 + (i + 1) * (j + 1));
  268. }
  269. }
  270. }
  271. return new Tuple<string, int>(null, -1);
  272. }
  273. /// <summary>
  274. /// Gets the words.
  275. /// </summary>
  276. /// <param name="term">The term.</param>
  277. /// <returns>System.String[][].</returns>
  278. private List<string> GetWords(string term)
  279. {
  280. return term.Split().Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  281. }
  282. }
  283. }