SearchEngine.cs 12 KB

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