2
0

SearchEngine.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 = _libraryManager.GetAllArtists(items)
  85. .ToList();
  86. foreach (var item in artists)
  87. {
  88. var index = GetIndex(item, searchTerm, terms);
  89. if (index.Item2 != -1)
  90. {
  91. try
  92. {
  93. var artist = _libraryManager.GetArtist(item);
  94. hints.Add(new Tuple<BaseItem, string, int>(artist, index.Item1, index.Item2));
  95. }
  96. catch (Exception ex)
  97. {
  98. _logger.ErrorException("Error getting {0}", ex, item);
  99. }
  100. }
  101. }
  102. }
  103. if (query.IncludeGenres)
  104. {
  105. // Find genres, from non-audio items
  106. var genres = items.Where(i => !(i is IHasMusicGenres) && !(i is Game))
  107. .SelectMany(i => i.Genres)
  108. .Where(i => !string.IsNullOrEmpty(i))
  109. .Distinct(StringComparer.OrdinalIgnoreCase)
  110. .ToList();
  111. foreach (var item in genres)
  112. {
  113. var index = GetIndex(item, searchTerm, terms);
  114. if (index.Item2 != -1)
  115. {
  116. try
  117. {
  118. var genre = _libraryManager.GetGenre(item);
  119. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  120. }
  121. catch (Exception ex)
  122. {
  123. _logger.ErrorException("Error getting {0}", ex, item);
  124. }
  125. }
  126. }
  127. // Find music genres
  128. var musicGenres = items.Where(i => i is IHasMusicGenres)
  129. .SelectMany(i => i.Genres)
  130. .Where(i => !string.IsNullOrEmpty(i))
  131. .Distinct(StringComparer.OrdinalIgnoreCase)
  132. .ToList();
  133. foreach (var item in musicGenres)
  134. {
  135. var index = GetIndex(item, searchTerm, terms);
  136. if (index.Item2 != -1)
  137. {
  138. try
  139. {
  140. var genre = _libraryManager.GetMusicGenre(item);
  141. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  142. }
  143. catch (Exception ex)
  144. {
  145. _logger.ErrorException("Error getting {0}", ex, item);
  146. }
  147. }
  148. }
  149. // Find music genres
  150. var gameGenres = items.OfType<Game>()
  151. .SelectMany(i => i.Genres)
  152. .Where(i => !string.IsNullOrEmpty(i))
  153. .Distinct(StringComparer.OrdinalIgnoreCase)
  154. .ToList();
  155. foreach (var item in gameGenres)
  156. {
  157. var index = GetIndex(item, searchTerm, terms);
  158. if (index.Item2 != -1)
  159. {
  160. try
  161. {
  162. var genre = _libraryManager.GetGameGenre(item);
  163. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  164. }
  165. catch (Exception ex)
  166. {
  167. _logger.ErrorException("Error getting {0}", ex, item);
  168. }
  169. }
  170. }
  171. }
  172. if (query.IncludeStudios)
  173. {
  174. // Find studios
  175. var studios = items.SelectMany(i => i.Studios)
  176. .Where(i => !string.IsNullOrEmpty(i))
  177. .Distinct(StringComparer.OrdinalIgnoreCase)
  178. .ToList();
  179. foreach (var item in studios)
  180. {
  181. var index = GetIndex(item, searchTerm, terms);
  182. if (index.Item2 != -1)
  183. {
  184. try
  185. {
  186. var studio = _libraryManager.GetStudio(item);
  187. hints.Add(new Tuple<BaseItem, string, int>(studio, index.Item1, index.Item2));
  188. }
  189. catch (Exception ex)
  190. {
  191. _logger.ErrorException("Error getting {0}", ex, item);
  192. }
  193. }
  194. }
  195. }
  196. if (query.IncludePeople)
  197. {
  198. // Find persons
  199. var persons = items.SelectMany(i => i.People)
  200. .Select(i => i.Name)
  201. .Where(i => !string.IsNullOrEmpty(i))
  202. .Distinct(StringComparer.OrdinalIgnoreCase)
  203. .ToList();
  204. foreach (var item in persons)
  205. {
  206. var index = GetIndex(item, searchTerm, terms);
  207. if (index.Item2 != -1)
  208. {
  209. try
  210. {
  211. var person = _libraryManager.GetPerson(item);
  212. hints.Add(new Tuple<BaseItem, string, int>(person, index.Item1, index.Item2));
  213. }
  214. catch (Exception ex)
  215. {
  216. _logger.ErrorException("Error getting {0}", ex, item);
  217. }
  218. }
  219. }
  220. }
  221. var returnValue = hints.Where(i => i.Item3 >= 0).OrderBy(i => i.Item3).Select(i => new SearchHintInfo
  222. {
  223. Item = i.Item1,
  224. MatchedTerm = i.Item2
  225. });
  226. return Task.FromResult(returnValue);
  227. }
  228. /// <summary>
  229. /// Gets the index.
  230. /// </summary>
  231. /// <param name="input">The input.</param>
  232. /// <param name="searchInput">The search input.</param>
  233. /// <param name="searchWords">The search input.</param>
  234. /// <returns>System.Int32.</returns>
  235. private Tuple<string, int> GetIndex(string input, string searchInput, List<string> searchWords)
  236. {
  237. if (string.IsNullOrEmpty(input))
  238. {
  239. throw new ArgumentNullException("input");
  240. }
  241. if (string.Equals(input, searchInput, StringComparison.OrdinalIgnoreCase))
  242. {
  243. return new Tuple<string, int>(searchInput, 0);
  244. }
  245. var index = input.IndexOf(searchInput, StringComparison.OrdinalIgnoreCase);
  246. if (index == 0)
  247. {
  248. return new Tuple<string, int>(searchInput, 1);
  249. }
  250. if (index > 0)
  251. {
  252. return new Tuple<string, int>(searchInput, 2);
  253. }
  254. var items = GetWords(input);
  255. for (var i = 0; i < searchWords.Count; i++)
  256. {
  257. var searchTerm = searchWords[i];
  258. for (var j = 0; j < items.Count; j++)
  259. {
  260. var item = items[j];
  261. if (string.Equals(item, searchTerm, StringComparison.OrdinalIgnoreCase))
  262. {
  263. return new Tuple<string, int>(searchTerm, 3 + (i + 1) * (j + 1));
  264. }
  265. index = item.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase);
  266. if (index == 0)
  267. {
  268. return new Tuple<string, int>(searchTerm, 4 + (i + 1) * (j + 1));
  269. }
  270. if (index > 0)
  271. {
  272. return new Tuple<string, int>(searchTerm, 5 + (i + 1) * (j + 1));
  273. }
  274. }
  275. }
  276. return new Tuple<string, int>(null, -1);
  277. }
  278. /// <summary>
  279. /// Gets the words.
  280. /// </summary>
  281. /// <param name="term">The term.</param>
  282. /// <returns>System.String[][].</returns>
  283. private List<string> GetWords(string term)
  284. {
  285. return term.Split().Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  286. }
  287. }
  288. }