SearchService.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. using MediaBrowser.Controller.Drawing;
  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;
  10. using System;
  11. using System.Linq;
  12. using System.Threading.Tasks;
  13. namespace MediaBrowser.Api
  14. {
  15. /// <summary>
  16. /// Class GetSearchHints
  17. /// </summary>
  18. [Route("/Search/Hints", "GET", Summary = "Gets search hints based on a search term")]
  19. public class GetSearchHints : IReturn<SearchHintResult>
  20. {
  21. /// <summary>
  22. /// Skips over a given number of items within the results. Use for paging.
  23. /// </summary>
  24. /// <value>The start index.</value>
  25. [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")]
  26. public int? StartIndex { get; set; }
  27. /// <summary>
  28. /// The maximum number of items to return
  29. /// </summary>
  30. /// <value>The limit.</value>
  31. [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
  32. public int? Limit { get; set; }
  33. /// <summary>
  34. /// Gets or sets the user id.
  35. /// </summary>
  36. /// <value>The user id.</value>
  37. [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")]
  38. public string UserId { get; set; }
  39. /// <summary>
  40. /// Search characters used to find items
  41. /// </summary>
  42. /// <value>The index by.</value>
  43. [ApiMember(Name = "SearchTerm", Description = "The search term to filter on", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
  44. public string SearchTerm { get; set; }
  45. [ApiMember(Name = "IncludePeople", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
  46. public bool IncludePeople { get; set; }
  47. [ApiMember(Name = "IncludeMedia", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
  48. public bool IncludeMedia { get; set; }
  49. [ApiMember(Name = "IncludeGenres", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
  50. public bool IncludeGenres { get; set; }
  51. [ApiMember(Name = "IncludeStudios", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
  52. public bool IncludeStudios { get; set; }
  53. [ApiMember(Name = "IncludeArtists", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
  54. public bool IncludeArtists { get; set; }
  55. [ApiMember(Name = "IncludeItemTypes", Description = "Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimeted.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)]
  56. public string IncludeItemTypes { get; set; }
  57. public GetSearchHints()
  58. {
  59. IncludeArtists = true;
  60. IncludeGenres = true;
  61. IncludeMedia = true;
  62. IncludePeople = true;
  63. IncludeStudios = true;
  64. }
  65. }
  66. /// <summary>
  67. /// Class SearchService
  68. /// </summary>
  69. public class SearchService : BaseApiService
  70. {
  71. /// <summary>
  72. /// The _search engine
  73. /// </summary>
  74. private readonly ISearchEngine _searchEngine;
  75. private readonly ILibraryManager _libraryManager;
  76. private readonly IDtoService _dtoService;
  77. private readonly IImageProcessor _imageProcessor;
  78. /// <summary>
  79. /// Initializes a new instance of the <see cref="SearchService" /> class.
  80. /// </summary>
  81. /// <param name="searchEngine">The search engine.</param>
  82. /// <param name="libraryManager">The library manager.</param>
  83. /// <param name="dtoService">The dto service.</param>
  84. /// <param name="imageProcessor">The image processor.</param>
  85. public SearchService(ISearchEngine searchEngine, ILibraryManager libraryManager, IDtoService dtoService, IImageProcessor imageProcessor)
  86. {
  87. _searchEngine = searchEngine;
  88. _libraryManager = libraryManager;
  89. _dtoService = dtoService;
  90. _imageProcessor = imageProcessor;
  91. }
  92. /// <summary>
  93. /// Gets the specified request.
  94. /// </summary>
  95. /// <param name="request">The request.</param>
  96. /// <returns>System.Object.</returns>
  97. public object Get(GetSearchHints request)
  98. {
  99. var result = GetSearchHintsAsync(request).Result;
  100. return ToOptimizedSerializedResultUsingCache(result);
  101. }
  102. /// <summary>
  103. /// Gets the search hints async.
  104. /// </summary>
  105. /// <param name="request">The request.</param>
  106. /// <returns>Task{IEnumerable{SearchHintResult}}.</returns>
  107. private async Task<SearchHintResult> GetSearchHintsAsync(GetSearchHints request)
  108. {
  109. var result = await _searchEngine.GetSearchHints(new SearchQuery
  110. {
  111. Limit = request.Limit,
  112. SearchTerm = request.SearchTerm,
  113. IncludeArtists = request.IncludeArtists,
  114. IncludeGenres = request.IncludeGenres,
  115. IncludeMedia = request.IncludeMedia,
  116. IncludePeople = request.IncludePeople,
  117. IncludeStudios = request.IncludeStudios,
  118. StartIndex = request.StartIndex,
  119. UserId = request.UserId,
  120. IncludeItemTypes = (request.IncludeItemTypes ?? string.Empty).Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToArray()
  121. }).ConfigureAwait(false);
  122. return new SearchHintResult
  123. {
  124. TotalRecordCount = result.TotalRecordCount,
  125. SearchHints = result.Items.Select(GetSearchHintResult).ToArray()
  126. };
  127. }
  128. /// <summary>
  129. /// Gets the search hint result.
  130. /// </summary>
  131. /// <param name="hintInfo">The hint info.</param>
  132. /// <returns>SearchHintResult.</returns>
  133. private SearchHint GetSearchHintResult(SearchHintInfo hintInfo)
  134. {
  135. var item = hintInfo.Item;
  136. var result = new SearchHint
  137. {
  138. Name = item.Name,
  139. IndexNumber = item.IndexNumber,
  140. ParentIndexNumber = item.ParentIndexNumber,
  141. ItemId = _dtoService.GetDtoId(item),
  142. Type = item.GetClientTypeName(),
  143. MediaType = item.MediaType,
  144. MatchedTerm = hintInfo.MatchedTerm,
  145. DisplayMediaType = item.DisplayMediaType,
  146. RunTimeTicks = item.RunTimeTicks,
  147. ProductionYear = item.ProductionYear
  148. };
  149. var primaryImageTag = _imageProcessor.GetImageCacheTag(item, ImageType.Primary);
  150. if (primaryImageTag.HasValue)
  151. {
  152. result.PrimaryImageTag = primaryImageTag.Value;
  153. }
  154. SetThumbImageInfo(result, item);
  155. SetBackdropImageInfo(result, item);
  156. var episode = item as Episode;
  157. if (episode != null)
  158. {
  159. result.Series = episode.Series.Name;
  160. }
  161. var season = item as Season;
  162. if (season != null)
  163. {
  164. result.Series = season.Series.Name;
  165. result.EpisodeCount = season.GetRecursiveChildren(i => i is Episode).Count;
  166. }
  167. var series = item as Series;
  168. if (series != null)
  169. {
  170. result.EpisodeCount = series.GetRecursiveChildren(i => i is Episode).Count;
  171. }
  172. var album = item as MusicAlbum;
  173. if (album != null)
  174. {
  175. var songs = album.GetRecursiveChildren().OfType<Audio>().ToList();
  176. result.SongCount = songs.Count;
  177. result.Artists = songs.SelectMany(i => i.AllArtists)
  178. .Distinct(StringComparer.OrdinalIgnoreCase)
  179. .ToArray();
  180. result.AlbumArtist = songs.Select(i => i.AlbumArtist).FirstOrDefault(i => !string.IsNullOrEmpty(i));
  181. }
  182. var song = item as Audio;
  183. if (song != null)
  184. {
  185. result.Album = song.Album;
  186. result.AlbumArtist = song.AlbumArtist;
  187. result.Artists = song.Artists.ToArray();
  188. }
  189. return result;
  190. }
  191. private void SetThumbImageInfo(SearchHint hint, BaseItem item)
  192. {
  193. var itemWithImage = item.HasImage(ImageType.Thumb) ? item : null;
  194. if (itemWithImage == null)
  195. {
  196. if (item is Episode)
  197. {
  198. itemWithImage = GetParentWithImage<Series>(item, ImageType.Thumb);
  199. }
  200. }
  201. if (itemWithImage == null)
  202. {
  203. itemWithImage = GetParentWithImage<BaseItem>(item, ImageType.Thumb);
  204. }
  205. if (itemWithImage != null)
  206. {
  207. var tag = _imageProcessor.GetImageCacheTag(itemWithImage, ImageType.Thumb);
  208. if (tag.HasValue)
  209. {
  210. hint.ThumbImageTag = tag.Value;
  211. hint.ThumbImageItemId = itemWithImage.Id.ToString("N");
  212. }
  213. }
  214. }
  215. private void SetBackdropImageInfo(SearchHint hint, BaseItem item)
  216. {
  217. var itemWithImage = item.HasImage(ImageType.Backdrop) ? item : null;
  218. if (itemWithImage == null)
  219. {
  220. itemWithImage = GetParentWithImage<BaseItem>(item, ImageType.Backdrop);
  221. }
  222. if (itemWithImage != null)
  223. {
  224. var tag = _imageProcessor.GetImageCacheTag(itemWithImage, ImageType.Backdrop);
  225. if (tag.HasValue)
  226. {
  227. hint.BackdropImageTag = tag.Value;
  228. hint.BackdropImageItemId = itemWithImage.Id.ToString("N");
  229. }
  230. }
  231. }
  232. private T GetParentWithImage<T>(BaseItem item, ImageType type)
  233. where T : BaseItem
  234. {
  235. return item.Parents.OfType<T>().FirstOrDefault(i => i.HasImage(type));
  236. }
  237. }
  238. }