SearchEngine.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Entities.Audio;
  4. using MediaBrowser.Controller.Entities.TV;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Querying;
  8. using MediaBrowser.Model.Search;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Threading.Tasks;
  13. namespace MediaBrowser.Server.Implementations.Library
  14. {
  15. /// <summary>
  16. /// Class LuceneSearchEngine
  17. /// http://www.codeproject.com/Articles/320219/Lucene-Net-ultra-fast-search-for-MVC-or-WebForms
  18. /// </summary>
  19. public class SearchEngine : ISearchEngine
  20. {
  21. private readonly ILibraryManager _libraryManager;
  22. private readonly IUserManager _userManager;
  23. private readonly ILogger _logger;
  24. public SearchEngine(ILogManager logManager, ILibraryManager libraryManager, IUserManager userManager)
  25. {
  26. _libraryManager = libraryManager;
  27. _userManager = userManager;
  28. _logger = logManager.GetLogger("Lucene");
  29. }
  30. public async Task<QueryResult<SearchHintInfo>> GetSearchHints(SearchQuery query)
  31. {
  32. IEnumerable<BaseItem> inputItems;
  33. if (string.IsNullOrWhiteSpace(query.UserId))
  34. {
  35. inputItems = _libraryManager.RootFolder.RecursiveChildren;
  36. }
  37. else
  38. {
  39. var user = _userManager.GetUserById(query.UserId);
  40. inputItems = user.RootFolder.GetRecursiveChildren(user, true);
  41. }
  42. inputItems = inputItems.Where(i => !(i is ICollectionFolder));
  43. inputItems = _libraryManager.ReplaceVideosWithPrimaryVersions(inputItems);
  44. var results = await GetSearchHints(inputItems, query).ConfigureAwait(false);
  45. // Include item types
  46. if (query.IncludeItemTypes.Length > 0)
  47. {
  48. results = results.Where(f => query.IncludeItemTypes.Contains(f.Item.GetType().Name, StringComparer.OrdinalIgnoreCase));
  49. }
  50. var searchResultArray = results.ToArray();
  51. results = searchResultArray;
  52. var count = searchResultArray.Length;
  53. if (query.StartIndex.HasValue)
  54. {
  55. results = results.Skip(query.StartIndex.Value);
  56. }
  57. if (query.Limit.HasValue)
  58. {
  59. results = results.Take(query.Limit.Value);
  60. }
  61. return new QueryResult<SearchHintInfo>
  62. {
  63. TotalRecordCount = count,
  64. Items = results.ToArray()
  65. };
  66. }
  67. /// <summary>
  68. /// Gets the search hints.
  69. /// </summary>
  70. /// <param name="inputItems">The input items.</param>
  71. /// <param name="query">The query.</param>
  72. /// <returns>IEnumerable{SearchHintResult}.</returns>
  73. /// <exception cref="System.ArgumentNullException">searchTerm</exception>
  74. private Task<IEnumerable<SearchHintInfo>> GetSearchHints(IEnumerable<BaseItem> inputItems, SearchQuery query)
  75. {
  76. var searchTerm = query.SearchTerm;
  77. if (string.IsNullOrWhiteSpace(searchTerm))
  78. {
  79. throw new ArgumentNullException("searchTerm");
  80. }
  81. searchTerm = searchTerm.RemoveDiacritics();
  82. var terms = GetWords(searchTerm);
  83. var hints = new List<Tuple<BaseItem, string, int>>();
  84. var items = inputItems.Where(i => !(i is MusicArtist)).ToList();
  85. if (query.IncludeMedia)
  86. {
  87. // Add search hints based on item name
  88. hints.AddRange(items.Where(i => !string.IsNullOrWhiteSpace(i.Name) && IncludeInSearch(i)).Select(item =>
  89. {
  90. var index = GetIndex(item.Name, searchTerm, terms);
  91. return new Tuple<BaseItem, string, int>(item, index.Item1, index.Item2);
  92. }));
  93. }
  94. if (query.IncludeArtists)
  95. {
  96. // Find artists
  97. var artists = items.OfType<Audio>()
  98. .SelectMany(i => i.AllArtists)
  99. .Where(i => !string.IsNullOrWhiteSpace(i))
  100. .Distinct(StringComparer.OrdinalIgnoreCase)
  101. .ToList();
  102. foreach (var item in artists)
  103. {
  104. var index = GetIndex(item, searchTerm, terms);
  105. if (index.Item2 != -1)
  106. {
  107. try
  108. {
  109. var artist = _libraryManager.GetArtist(item);
  110. hints.Add(new Tuple<BaseItem, string, int>(artist, index.Item1, index.Item2));
  111. }
  112. catch (Exception ex)
  113. {
  114. _logger.ErrorException("Error getting {0}", ex, item);
  115. }
  116. }
  117. }
  118. }
  119. if (query.IncludeGenres)
  120. {
  121. // Find genres, from non-audio items
  122. var genres = items.Where(i => !(i is IHasMusicGenres) && !(i is Game))
  123. .SelectMany(i => i.Genres)
  124. .Where(i => !string.IsNullOrWhiteSpace(i))
  125. .Distinct(StringComparer.OrdinalIgnoreCase)
  126. .ToList();
  127. foreach (var item in genres)
  128. {
  129. var index = GetIndex(item, searchTerm, terms);
  130. if (index.Item2 != -1)
  131. {
  132. try
  133. {
  134. var genre = _libraryManager.GetGenre(item);
  135. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  136. }
  137. catch (Exception ex)
  138. {
  139. _logger.ErrorException("Error getting {0}", ex, item);
  140. }
  141. }
  142. }
  143. // Find music genres
  144. var musicGenres = items.Where(i => i is IHasMusicGenres)
  145. .SelectMany(i => i.Genres)
  146. .Where(i => !string.IsNullOrWhiteSpace(i))
  147. .Distinct(StringComparer.OrdinalIgnoreCase)
  148. .ToList();
  149. foreach (var item in musicGenres)
  150. {
  151. var index = GetIndex(item, searchTerm, terms);
  152. if (index.Item2 != -1)
  153. {
  154. try
  155. {
  156. var genre = _libraryManager.GetMusicGenre(item);
  157. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  158. }
  159. catch (Exception ex)
  160. {
  161. _logger.ErrorException("Error getting {0}", ex, item);
  162. }
  163. }
  164. }
  165. // Find music genres
  166. var gameGenres = items.OfType<Game>()
  167. .SelectMany(i => i.Genres)
  168. .Where(i => !string.IsNullOrWhiteSpace(i))
  169. .Distinct(StringComparer.OrdinalIgnoreCase)
  170. .ToList();
  171. foreach (var item in gameGenres)
  172. {
  173. var index = GetIndex(item, searchTerm, terms);
  174. if (index.Item2 != -1)
  175. {
  176. try
  177. {
  178. var genre = _libraryManager.GetGameGenre(item);
  179. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  180. }
  181. catch (Exception ex)
  182. {
  183. _logger.ErrorException("Error getting {0}", ex, item);
  184. }
  185. }
  186. }
  187. }
  188. if (query.IncludeStudios)
  189. {
  190. // Find studios
  191. var studios = items.SelectMany(i => i.Studios)
  192. .Where(i => !string.IsNullOrWhiteSpace(i))
  193. .Distinct(StringComparer.OrdinalIgnoreCase)
  194. .ToList();
  195. foreach (var item in studios)
  196. {
  197. var index = GetIndex(item, searchTerm, terms);
  198. if (index.Item2 != -1)
  199. {
  200. try
  201. {
  202. var studio = _libraryManager.GetStudio(item);
  203. hints.Add(new Tuple<BaseItem, string, int>(studio, index.Item1, index.Item2));
  204. }
  205. catch (Exception ex)
  206. {
  207. _logger.ErrorException("Error getting {0}", ex, item);
  208. }
  209. }
  210. }
  211. }
  212. if (query.IncludePeople)
  213. {
  214. // Find persons
  215. var persons = items.SelectMany(i => i.People)
  216. .Select(i => i.Name)
  217. .Where(i => !string.IsNullOrWhiteSpace(i))
  218. .Distinct(StringComparer.OrdinalIgnoreCase)
  219. .ToList();
  220. foreach (var item in persons)
  221. {
  222. var index = GetIndex(item, searchTerm, terms);
  223. if (index.Item2 != -1)
  224. {
  225. try
  226. {
  227. var person = _libraryManager.GetPerson(item);
  228. hints.Add(new Tuple<BaseItem, string, int>(person, index.Item1, index.Item2));
  229. }
  230. catch (Exception ex)
  231. {
  232. _logger.ErrorException("Error getting {0}", ex, item);
  233. }
  234. }
  235. }
  236. }
  237. var returnValue = hints.Where(i => i.Item3 >= 0).OrderBy(i => i.Item3).Select(i => new SearchHintInfo
  238. {
  239. Item = i.Item1,
  240. MatchedTerm = i.Item2
  241. });
  242. return Task.FromResult(returnValue);
  243. }
  244. private bool IncludeInSearch(BaseItem item)
  245. {
  246. var episode = item as Episode;
  247. if (episode != null)
  248. {
  249. if (episode.IsVirtualUnaired || episode.IsMissingEpisode)
  250. {
  251. return false;
  252. }
  253. }
  254. return true;
  255. }
  256. /// <summary>
  257. /// Gets the index.
  258. /// </summary>
  259. /// <param name="input">The input.</param>
  260. /// <param name="searchInput">The search input.</param>
  261. /// <param name="searchWords">The search input.</param>
  262. /// <returns>System.Int32.</returns>
  263. private Tuple<string, int> GetIndex(string input, string searchInput, List<string> searchWords)
  264. {
  265. if (string.IsNullOrWhiteSpace(input))
  266. {
  267. throw new ArgumentNullException("input");
  268. }
  269. input = input.RemoveDiacritics();
  270. if (string.Equals(input, searchInput, StringComparison.OrdinalIgnoreCase))
  271. {
  272. return new Tuple<string, int>(searchInput, 0);
  273. }
  274. var index = input.IndexOf(searchInput, StringComparison.OrdinalIgnoreCase);
  275. if (index == 0)
  276. {
  277. return new Tuple<string, int>(searchInput, 1);
  278. }
  279. if (index > 0)
  280. {
  281. return new Tuple<string, int>(searchInput, 2);
  282. }
  283. var items = GetWords(input);
  284. for (var i = 0; i < searchWords.Count; i++)
  285. {
  286. var searchTerm = searchWords[i];
  287. for (var j = 0; j < items.Count; j++)
  288. {
  289. var item = items[j];
  290. if (string.Equals(item, searchTerm, StringComparison.OrdinalIgnoreCase))
  291. {
  292. return new Tuple<string, int>(searchTerm, 3 + (i + 1) * (j + 1));
  293. }
  294. index = item.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase);
  295. if (index == 0)
  296. {
  297. return new Tuple<string, int>(searchTerm, 4 + (i + 1) * (j + 1));
  298. }
  299. if (index > 0)
  300. {
  301. return new Tuple<string, int>(searchTerm, 5 + (i + 1) * (j + 1));
  302. }
  303. }
  304. }
  305. return new Tuple<string, int>(null, -1);
  306. }
  307. /// <summary>
  308. /// Gets the words.
  309. /// </summary>
  310. /// <param name="term">The term.</param>
  311. /// <returns>System.String[][].</returns>
  312. private List<string> GetWords(string term)
  313. {
  314. var stoplist = GetStopList().ToList();
  315. return term.Split()
  316. .Where(i => !string.IsNullOrWhiteSpace(i) && !stoplist.Contains(i, StringComparer.OrdinalIgnoreCase))
  317. .ToList();
  318. }
  319. private IEnumerable<string> GetStopList()
  320. {
  321. return new[]
  322. {
  323. "the",
  324. "a",
  325. "of",
  326. "an"
  327. };
  328. }
  329. }
  330. }