SearchService.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. using MediaBrowser.Controller;
  2. using MediaBrowser.Controller.Dto;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Entities.Audio;
  5. using MediaBrowser.Controller.Entities.TV;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Search;
  9. using ServiceStack.ServiceHost;
  10. using System;
  11. using System.Collections;
  12. using System.Collections.Generic;
  13. using System.Linq;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Api
  16. {
  17. /// <summary>
  18. /// Class GetSearchHints
  19. /// </summary>
  20. [Route("/Search/Hints", "GET")]
  21. [Api(Description = "Gets search hints based on a search term")]
  22. public class GetSearchHints : IReturn<SearchHintResult>
  23. {
  24. /// <summary>
  25. /// Skips over a given number of items within the results. Use for paging.
  26. /// </summary>
  27. /// <value>The start index.</value>
  28. [ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
  29. public int? StartIndex { get; set; }
  30. /// <summary>
  31. /// The maximum number of items to return
  32. /// </summary>
  33. /// <value>The limit.</value>
  34. [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
  35. public int? Limit { get; set; }
  36. /// <summary>
  37. /// Gets or sets the user id.
  38. /// </summary>
  39. /// <value>The user id.</value>
  40. [ApiMember(Name = "UserId", Description = "Optional. Supply a user id to search within a user's library or omit to search all.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
  41. public Guid? UserId { get; set; }
  42. /// <summary>
  43. /// Search characters used to find items
  44. /// </summary>
  45. /// <value>The index by.</value>
  46. [ApiMember(Name = "SearchTerm", Description = "The search term to filter on", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
  47. public string SearchTerm { get; set; }
  48. }
  49. /// <summary>
  50. /// Class SearchService
  51. /// </summary>
  52. public class SearchService : BaseApiService
  53. {
  54. /// <summary>
  55. /// The _user manager
  56. /// </summary>
  57. private readonly IUserManager _userManager;
  58. /// <summary>
  59. /// The _search engine
  60. /// </summary>
  61. private readonly ILibrarySearchEngine _searchEngine;
  62. private readonly ILibraryManager _libraryManager;
  63. /// <summary>
  64. /// Initializes a new instance of the <see cref="SearchService" /> class.
  65. /// </summary>
  66. /// <param name="userManager">The user manager.</param>
  67. /// <param name="searchEngine">The search engine.</param>
  68. /// <param name="libraryManager">The library manager.</param>
  69. public SearchService(IUserManager userManager, ILibrarySearchEngine searchEngine, ILibraryManager libraryManager)
  70. {
  71. _userManager = userManager;
  72. _searchEngine = searchEngine;
  73. _libraryManager = libraryManager;
  74. }
  75. /// <summary>
  76. /// Gets the specified request.
  77. /// </summary>
  78. /// <param name="request">The request.</param>
  79. /// <returns>System.Object.</returns>
  80. public object Get(GetSearchHints request)
  81. {
  82. var result = GetSearchHintsAsync(request).Result;
  83. return ToOptimizedResult(result);
  84. }
  85. /// <summary>
  86. /// Gets the search hints async.
  87. /// </summary>
  88. /// <param name="request">The request.</param>
  89. /// <returns>Task{IEnumerable{SearchHintResult}}.</returns>
  90. private async Task<SearchHintResult> GetSearchHintsAsync(GetSearchHints request)
  91. {
  92. IEnumerable<BaseItem> inputItems;
  93. if (request.UserId.HasValue)
  94. {
  95. var user = _userManager.GetUserById(request.UserId.Value);
  96. inputItems = user.RootFolder.GetRecursiveChildren(user);
  97. }
  98. else
  99. {
  100. inputItems = _libraryManager.RootFolder.RecursiveChildren;
  101. }
  102. var results = await _searchEngine.GetSearchHints(inputItems, request.SearchTerm).ConfigureAwait(false);
  103. var searchResultArray = results.ToArray();
  104. IEnumerable<SearchHintInfo> returnResults = searchResultArray;
  105. if (request.StartIndex.HasValue)
  106. {
  107. returnResults = returnResults.Skip(request.StartIndex.Value);
  108. }
  109. if (request.Limit.HasValue)
  110. {
  111. returnResults = returnResults.Take(request.Limit.Value);
  112. }
  113. return new SearchHintResult
  114. {
  115. TotalRecordCount = searchResultArray.Length,
  116. SearchHints = returnResults.Select(GetSearchHintResult).ToArray()
  117. };
  118. }
  119. /// <summary>
  120. /// Gets the search hint result.
  121. /// </summary>
  122. /// <param name="hintInfo">The hint info.</param>
  123. /// <returns>SearchHintResult.</returns>
  124. private SearchHint GetSearchHintResult(SearchHintInfo hintInfo)
  125. {
  126. var item = hintInfo.Item;
  127. var result = new SearchHint
  128. {
  129. Name = item.Name,
  130. IndexNumber = item.IndexNumber,
  131. ParentIndexNumber = item.ParentIndexNumber,
  132. ItemId = DtoBuilder.GetClientItemId(item),
  133. Type = item.GetType().Name,
  134. MediaType = item.MediaType,
  135. MatchedTerm = hintInfo.MatchedTerm,
  136. DisplayMediaType = item.DisplayMediaType,
  137. RunTimeTicks = item.RunTimeTicks
  138. };
  139. if (item.HasImage(ImageType.Primary))
  140. {
  141. result.PrimaryImageTag = Kernel.Instance.ImageManager.GetImageCacheTag(item, ImageType.Primary, item.GetImage(ImageType.Primary));
  142. }
  143. var episode = item as Episode;
  144. if (episode != null)
  145. {
  146. result.Series = episode.Series.Name;
  147. }
  148. var season = item as Season;
  149. if (season != null)
  150. {
  151. result.Series = season.Series.Name;
  152. result.EpisodeCount = season.RecursiveChildren.OfType<Episode>().Count();
  153. }
  154. var series = item as Series;
  155. if (series != null)
  156. {
  157. result.EpisodeCount = series.RecursiveChildren.OfType<Episode>().Count();
  158. }
  159. var album = item as MusicAlbum;
  160. if (album != null)
  161. {
  162. var songs = album.RecursiveChildren.OfType<Audio>().ToList();
  163. result.SongCount = songs.Count;
  164. result.Artists = songs
  165. .Select(i => i.Artist)
  166. .Where(i => !string.IsNullOrEmpty(i))
  167. .Distinct(StringComparer.OrdinalIgnoreCase)
  168. .ToArray();
  169. result.AlbumArtist = songs.Select(i => i.AlbumArtist).FirstOrDefault(i => !string.IsNullOrEmpty(i));
  170. }
  171. var song = item as Audio;
  172. if (song != null)
  173. {
  174. result.Album = song.Album;
  175. result.AlbumArtist = song.AlbumArtist;
  176. result.Artists = !string.IsNullOrEmpty(song.Artist) ? new[] { song.Artist } : new string[] { };
  177. }
  178. return result;
  179. }
  180. }
  181. }