SearchEngine.cs 12 KB

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