SearchService.cs 11 KB

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