SearchEngine.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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. using MediaBrowser.Controller.Extensions;
  12. namespace Emby.Server.Implementations.Library
  13. {
  14. /// <summary>
  15. /// </summary>
  16. public class SearchEngine : ISearchEngine
  17. {
  18. private readonly ILibraryManager _libraryManager;
  19. private readonly IUserManager _userManager;
  20. private readonly ILogger _logger;
  21. public SearchEngine(ILogManager logManager, ILibraryManager libraryManager, IUserManager userManager)
  22. {
  23. _libraryManager = libraryManager;
  24. _userManager = userManager;
  25. _logger = logManager.GetLogger("Lucene");
  26. }
  27. public async Task<QueryResult<SearchHintInfo>> GetSearchHints(SearchQuery query)
  28. {
  29. User user = null;
  30. if (string.IsNullOrWhiteSpace(query.UserId))
  31. {
  32. }
  33. else
  34. {
  35. user = _userManager.GetUserById(query.UserId);
  36. }
  37. var results = await GetSearchHints(query, user).ConfigureAwait(false);
  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. private void AddIfMissing(List<string> list, string value)
  56. {
  57. if (!list.Contains(value, StringComparer.OrdinalIgnoreCase))
  58. {
  59. list.Add(value);
  60. }
  61. }
  62. /// <summary>
  63. /// Gets the search hints.
  64. /// </summary>
  65. /// <param name="query">The query.</param>
  66. /// <param name="user">The user.</param>
  67. /// <returns>IEnumerable{SearchHintResult}.</returns>
  68. /// <exception cref="System.ArgumentNullException">searchTerm</exception>
  69. private Task<IEnumerable<SearchHintInfo>> GetSearchHints(SearchQuery query, User user)
  70. {
  71. var searchTerm = query.SearchTerm;
  72. if (searchTerm != null)
  73. {
  74. searchTerm = searchTerm.Trim().RemoveDiacritics();
  75. }
  76. if (string.IsNullOrWhiteSpace(searchTerm))
  77. {
  78. throw new ArgumentNullException("searchTerm");
  79. }
  80. var terms = GetWords(searchTerm);
  81. var hints = new List<Tuple<BaseItem, string, int>>();
  82. var excludeItemTypes = new List<string>();
  83. var includeItemTypes = (query.IncludeItemTypes ?? new string[] { }).ToList();
  84. excludeItemTypes.Add(typeof(Year).Name);
  85. excludeItemTypes.Add(typeof(Folder).Name);
  86. if (query.IncludeGenres && (includeItemTypes.Count == 0 || includeItemTypes.Contains("Genre", StringComparer.OrdinalIgnoreCase)))
  87. {
  88. if (!query.IncludeMedia)
  89. {
  90. AddIfMissing(includeItemTypes, typeof(Genre).Name);
  91. AddIfMissing(includeItemTypes, typeof(GameGenre).Name);
  92. AddIfMissing(includeItemTypes, typeof(MusicGenre).Name);
  93. }
  94. }
  95. else
  96. {
  97. AddIfMissing(excludeItemTypes, typeof(Genre).Name);
  98. AddIfMissing(excludeItemTypes, typeof(GameGenre).Name);
  99. AddIfMissing(excludeItemTypes, typeof(MusicGenre).Name);
  100. }
  101. if (query.IncludePeople && (includeItemTypes.Count == 0 || includeItemTypes.Contains("People", StringComparer.OrdinalIgnoreCase) || includeItemTypes.Contains("Person", StringComparer.OrdinalIgnoreCase)))
  102. {
  103. if (!query.IncludeMedia)
  104. {
  105. AddIfMissing(includeItemTypes, typeof(Person).Name);
  106. }
  107. }
  108. else
  109. {
  110. AddIfMissing(excludeItemTypes, typeof(Person).Name);
  111. }
  112. if (query.IncludeStudios && (includeItemTypes.Count == 0 || includeItemTypes.Contains("Studio", StringComparer.OrdinalIgnoreCase)))
  113. {
  114. if (!query.IncludeMedia)
  115. {
  116. AddIfMissing(includeItemTypes, typeof(Studio).Name);
  117. }
  118. }
  119. else
  120. {
  121. AddIfMissing(excludeItemTypes, typeof(Studio).Name);
  122. }
  123. if (query.IncludeArtists && (includeItemTypes.Count == 0 || includeItemTypes.Contains("MusicArtist", StringComparer.OrdinalIgnoreCase)))
  124. {
  125. if (!query.IncludeMedia)
  126. {
  127. AddIfMissing(includeItemTypes, typeof(MusicArtist).Name);
  128. }
  129. }
  130. else
  131. {
  132. AddIfMissing(excludeItemTypes, typeof(MusicArtist).Name);
  133. }
  134. AddIfMissing(excludeItemTypes, typeof(CollectionFolder).Name);
  135. AddIfMissing(excludeItemTypes, typeof(Folder).Name);
  136. var mediaItems = _libraryManager.GetItemList(new InternalItemsQuery(user)
  137. {
  138. NameContains = searchTerm,
  139. ExcludeItemTypes = excludeItemTypes.ToArray(),
  140. IncludeItemTypes = includeItemTypes.ToArray(),
  141. Limit = query.Limit,
  142. IncludeItemsByName = string.IsNullOrWhiteSpace(query.ParentId),
  143. ParentId = string.IsNullOrWhiteSpace(query.ParentId) ? (Guid?)null : new Guid(query.ParentId),
  144. SortBy = new[] { ItemSortBy.SortName },
  145. Recursive = true,
  146. IsKids = query.IsKids,
  147. IsMovie = query.IsMovie,
  148. IsNews = query.IsNews,
  149. IsSeries = query.IsSeries,
  150. IsSports = query.IsSports
  151. });
  152. // Add search hints based on item name
  153. hints.AddRange(mediaItems.Select(item =>
  154. {
  155. var index = GetIndex(item.Name, searchTerm, terms);
  156. return new Tuple<BaseItem, string, int>(item, index.Item1, index.Item2);
  157. }));
  158. var returnValue = hints.Where(i => i.Item3 >= 0).OrderBy(i => i.Item3).ThenBy(i => i.Item1.SortName).Select(i => new SearchHintInfo
  159. {
  160. Item = i.Item1,
  161. MatchedTerm = i.Item2
  162. });
  163. return Task.FromResult(returnValue);
  164. }
  165. /// <summary>
  166. /// Gets the index.
  167. /// </summary>
  168. /// <param name="input">The input.</param>
  169. /// <param name="searchInput">The search input.</param>
  170. /// <param name="searchWords">The search input.</param>
  171. /// <returns>System.Int32.</returns>
  172. private Tuple<string, int> GetIndex(string input, string searchInput, List<string> searchWords)
  173. {
  174. if (string.IsNullOrWhiteSpace(input))
  175. {
  176. throw new ArgumentNullException("input");
  177. }
  178. input = input.RemoveDiacritics();
  179. if (string.Equals(input, searchInput, StringComparison.OrdinalIgnoreCase))
  180. {
  181. return new Tuple<string, int>(searchInput, 0);
  182. }
  183. var index = input.IndexOf(searchInput, StringComparison.OrdinalIgnoreCase);
  184. if (index == 0)
  185. {
  186. return new Tuple<string, int>(searchInput, 1);
  187. }
  188. if (index > 0)
  189. {
  190. return new Tuple<string, int>(searchInput, 2);
  191. }
  192. var items = GetWords(input);
  193. for (var i = 0; i < searchWords.Count; i++)
  194. {
  195. var searchTerm = searchWords[i];
  196. for (var j = 0; j < items.Count; j++)
  197. {
  198. var item = items[j];
  199. if (string.Equals(item, searchTerm, StringComparison.OrdinalIgnoreCase))
  200. {
  201. return new Tuple<string, int>(searchTerm, 3 + (i + 1) * (j + 1));
  202. }
  203. index = item.IndexOf(searchTerm, StringComparison.OrdinalIgnoreCase);
  204. if (index == 0)
  205. {
  206. return new Tuple<string, int>(searchTerm, 4 + (i + 1) * (j + 1));
  207. }
  208. if (index > 0)
  209. {
  210. return new Tuple<string, int>(searchTerm, 5 + (i + 1) * (j + 1));
  211. }
  212. }
  213. }
  214. return new Tuple<string, int>(null, -1);
  215. }
  216. /// <summary>
  217. /// Gets the words.
  218. /// </summary>
  219. /// <param name="term">The term.</param>
  220. /// <returns>System.String[][].</returns>
  221. private List<string> GetWords(string term)
  222. {
  223. var stoplist = GetStopList().ToList();
  224. return term.Split()
  225. .Where(i => !string.IsNullOrWhiteSpace(i) && !stoplist.Contains(i, StringComparer.OrdinalIgnoreCase))
  226. .ToList();
  227. }
  228. private IEnumerable<string> GetStopList()
  229. {
  230. return new[]
  231. {
  232. "the",
  233. "a",
  234. "of",
  235. "an"
  236. };
  237. }
  238. }
  239. }