SearchEngine.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. Func<BaseItem, bool> filter = i => !(i is ICollectionFolder);
  34. User user = null;
  35. if (string.IsNullOrWhiteSpace(query.UserId))
  36. {
  37. inputItems = _libraryManager.RootFolder.GetRecursiveChildren(filter);
  38. }
  39. else
  40. {
  41. user = _userManager.GetUserById(query.UserId);
  42. inputItems = user.RootFolder.GetRecursiveChildren(user, filter);
  43. }
  44. inputItems = _libraryManager.ReplaceVideosWithPrimaryVersions(inputItems);
  45. var results = await GetSearchHints(inputItems, query, user).ConfigureAwait(false);
  46. var searchResultArray = results.ToArray();
  47. results = searchResultArray;
  48. var count = searchResultArray.Length;
  49. if (query.StartIndex.HasValue)
  50. {
  51. results = results.Skip(query.StartIndex.Value);
  52. }
  53. if (query.Limit.HasValue)
  54. {
  55. results = results.Take(query.Limit.Value);
  56. }
  57. return new QueryResult<SearchHintInfo>
  58. {
  59. TotalRecordCount = count,
  60. Items = results.ToArray()
  61. };
  62. }
  63. /// <summary>
  64. /// Gets the search hints.
  65. /// </summary>
  66. /// <param name="inputItems">The input items.</param>
  67. /// <param name="query">The query.</param>
  68. /// <param name="user">The user.</param>
  69. /// <returns>IEnumerable{SearchHintResult}.</returns>
  70. /// <exception cref="System.ArgumentNullException">searchTerm</exception>
  71. private Task<IEnumerable<SearchHintInfo>> GetSearchHints(IEnumerable<BaseItem> inputItems, SearchQuery query, User user)
  72. {
  73. var searchTerm = query.SearchTerm;
  74. if (string.IsNullOrWhiteSpace(searchTerm))
  75. {
  76. throw new ArgumentNullException("searchTerm");
  77. }
  78. searchTerm = searchTerm.RemoveDiacritics();
  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. var mediaItems = _libraryManager.GetItems(new InternalItemsQuery
  85. {
  86. NameContains = searchTerm,
  87. ExcludeItemTypes = new[]
  88. {
  89. typeof (Person).Name,
  90. typeof (Genre).Name,
  91. typeof (MusicArtist).Name,
  92. typeof (GameGenre).Name,
  93. typeof (MusicGenre).Name,
  94. typeof (Year).Name,
  95. typeof (Studio).Name
  96. },
  97. IncludeItemTypes = query.IncludeItemTypes
  98. }).Items;
  99. // Add search hints based on item name
  100. hints.AddRange(mediaItems.Where(i => IncludeInSearch(i) && (user == null || i.IsVisibleStandalone(user)) && !(i is CollectionFolder)).Select(item =>
  101. {
  102. var index = GetIndex(item.Name, searchTerm, terms);
  103. return new Tuple<BaseItem, string, int>(item, index.Item1, index.Item2);
  104. }));
  105. }
  106. if (query.IncludeArtists && (query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains("MusicArtist", StringComparer.OrdinalIgnoreCase)))
  107. {
  108. // Find artists
  109. var artists = items.OfType<Audio>()
  110. .SelectMany(i => i.AllArtists)
  111. .Where(i => !string.IsNullOrWhiteSpace(i))
  112. .DistinctNames()
  113. .ToList();
  114. foreach (var item in artists)
  115. {
  116. var index = GetIndex(item, searchTerm, terms);
  117. if (index.Item2 != -1)
  118. {
  119. try
  120. {
  121. var artist = _libraryManager.GetArtist(item);
  122. hints.Add(new Tuple<BaseItem, string, int>(artist, index.Item1, index.Item2));
  123. }
  124. catch (Exception ex)
  125. {
  126. _logger.ErrorException("Error getting {0}", ex, item);
  127. }
  128. }
  129. }
  130. }
  131. if (query.IncludeGenres && (query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains("Genre", StringComparer.OrdinalIgnoreCase)))
  132. {
  133. // Find genres, from non-audio items
  134. var genres = items.Where(i => !(i is IHasMusicGenres) && !(i is Game))
  135. .SelectMany(i => i.Genres)
  136. .Where(i => !string.IsNullOrWhiteSpace(i))
  137. .Distinct(StringComparer.OrdinalIgnoreCase)
  138. .ToList();
  139. foreach (var item in genres)
  140. {
  141. var index = GetIndex(item, searchTerm, terms);
  142. if (index.Item2 != -1)
  143. {
  144. try
  145. {
  146. var genre = _libraryManager.GetGenre(item);
  147. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  148. }
  149. catch (Exception ex)
  150. {
  151. _logger.ErrorException("Error getting {0}", ex, item);
  152. }
  153. }
  154. }
  155. // Find music genres
  156. var musicGenres = items.Where(i => i is IHasMusicGenres)
  157. .SelectMany(i => i.Genres)
  158. .Where(i => !string.IsNullOrWhiteSpace(i))
  159. .Distinct(StringComparer.OrdinalIgnoreCase)
  160. .ToList();
  161. foreach (var item in musicGenres)
  162. {
  163. var index = GetIndex(item, searchTerm, terms);
  164. if (index.Item2 != -1)
  165. {
  166. try
  167. {
  168. var genre = _libraryManager.GetMusicGenre(item);
  169. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  170. }
  171. catch (Exception ex)
  172. {
  173. _logger.ErrorException("Error getting {0}", ex, item);
  174. }
  175. }
  176. }
  177. // Find music genres
  178. var gameGenres = items.OfType<Game>()
  179. .SelectMany(i => i.Genres)
  180. .Where(i => !string.IsNullOrWhiteSpace(i))
  181. .Distinct(StringComparer.OrdinalIgnoreCase)
  182. .ToList();
  183. foreach (var item in gameGenres)
  184. {
  185. var index = GetIndex(item, searchTerm, terms);
  186. if (index.Item2 != -1)
  187. {
  188. try
  189. {
  190. var genre = _libraryManager.GetGameGenre(item);
  191. hints.Add(new Tuple<BaseItem, string, int>(genre, index.Item1, index.Item2));
  192. }
  193. catch (Exception ex)
  194. {
  195. _logger.ErrorException("Error getting {0}", ex, item);
  196. }
  197. }
  198. }
  199. }
  200. if (query.IncludeStudios && (query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains("Studio", StringComparer.OrdinalIgnoreCase)))
  201. {
  202. // Find studios
  203. var studios = items.SelectMany(i => i.Studios)
  204. .Where(i => !string.IsNullOrWhiteSpace(i))
  205. .Distinct(StringComparer.OrdinalIgnoreCase)
  206. .ToList();
  207. foreach (var item in studios)
  208. {
  209. var index = GetIndex(item, searchTerm, terms);
  210. if (index.Item2 != -1)
  211. {
  212. try
  213. {
  214. var studio = _libraryManager.GetStudio(item);
  215. hints.Add(new Tuple<BaseItem, string, int>(studio, index.Item1, index.Item2));
  216. }
  217. catch (Exception ex)
  218. {
  219. _logger.ErrorException("Error getting {0}", ex, item);
  220. }
  221. }
  222. }
  223. }
  224. if (query.IncludePeople && (query.IncludeItemTypes.Length == 0 || query.IncludeItemTypes.Contains("Person", StringComparer.OrdinalIgnoreCase)))
  225. {
  226. var itemIds = items.Select(i => i.Id).ToList();
  227. // Find persons
  228. var persons = _libraryManager.GetPeople(new InternalPeopleQuery
  229. {
  230. NameContains = searchTerm
  231. })
  232. .Where(i => itemIds.Contains(i.ItemId))
  233. .Select(i => i.Name)
  234. .Distinct(StringComparer.OrdinalIgnoreCase)
  235. .ToList();
  236. foreach (var item in persons)
  237. {
  238. var index = GetIndex(item, searchTerm, terms);
  239. if (index.Item2 != -1)
  240. {
  241. try
  242. {
  243. var person = _libraryManager.GetPerson(item);
  244. hints.Add(new Tuple<BaseItem, string, int>(person, index.Item1, index.Item2));
  245. }
  246. catch (Exception ex)
  247. {
  248. _logger.ErrorException("Error getting {0}", ex, item);
  249. }
  250. }
  251. }
  252. }
  253. var returnValue = hints.Where(i => i.Item3 >= 0).OrderBy(i => i.Item3).Select(i => new SearchHintInfo
  254. {
  255. Item = i.Item1,
  256. MatchedTerm = i.Item2
  257. });
  258. return Task.FromResult(returnValue);
  259. }
  260. private bool IncludeInSearch(BaseItem item)
  261. {
  262. var episode = item as Episode;
  263. if (episode != null)
  264. {
  265. if (episode.IsVirtualUnaired || episode.IsMissingEpisode)
  266. {
  267. return false;
  268. }
  269. }
  270. return true;
  271. }
  272. /// <summary>
  273. /// Gets the index.
  274. /// </summary>
  275. /// <param name="input">The input.</param>
  276. /// <param name="searchInput">The search input.</param>
  277. /// <param name="searchWords">The search input.</param>
  278. /// <returns>System.Int32.</returns>
  279. private Tuple<string, int> GetIndex(string input, string searchInput, List<string> searchWords)
  280. {
  281. if (string.IsNullOrWhiteSpace(input))
  282. {
  283. throw new ArgumentNullException("input");
  284. }
  285. input = input.RemoveDiacritics();
  286. if (string.Equals(input, searchInput, StringComparison.OrdinalIgnoreCase))
  287. {
  288. return new Tuple<string, int>(searchInput, 0);
  289. }
  290. var index = input.IndexOf(searchInput, StringComparison.OrdinalIgnoreCase);
  291. if (index == 0)
  292. {
  293. return new Tuple<string, int>(searchInput, 1);
  294. }
  295. if (index > 0)
  296. {
  297. return new Tuple<string, int>(searchInput, 2);
  298. }
  299. var items = GetWords(input);
  300. for (var i = 0; i < searchWords.Count; i++)
  301. {
  302. var searchTerm = searchWords[i];
  303. for (var j = 0; j < items.Count; j++)
  304. {
  305. var item = items[j];
  306. if (string.Equals(item, searchTerm, StringComparison.OrdinalIgnoreCase))
  307. {
  308. return new Tuple<string, int>(searchTerm, 3 + (i + 1) * (j + 1));
  309. }
  310. index = item.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase);
  311. if (index == 0)
  312. {
  313. return new Tuple<string, int>(searchTerm, 4 + (i + 1) * (j + 1));
  314. }
  315. if (index > 0)
  316. {
  317. return new Tuple<string, int>(searchTerm, 5 + (i + 1) * (j + 1));
  318. }
  319. }
  320. }
  321. return new Tuple<string, int>(null, -1);
  322. }
  323. /// <summary>
  324. /// Gets the words.
  325. /// </summary>
  326. /// <param name="term">The term.</param>
  327. /// <returns>System.String[][].</returns>
  328. private List<string> GetWords(string term)
  329. {
  330. var stoplist = GetStopList().ToList();
  331. return term.Split()
  332. .Where(i => !string.IsNullOrWhiteSpace(i) && !stoplist.Contains(i, StringComparer.OrdinalIgnoreCase))
  333. .ToList();
  334. }
  335. private IEnumerable<string> GetStopList()
  336. {
  337. return new[]
  338. {
  339. "the",
  340. "a",
  341. "of",
  342. "an"
  343. };
  344. }
  345. }
  346. }