SearchEngine.cs 12 KB

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