aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Api/SearchService.cs
blob: 50033eee8289b2c8e6fe2655bfdd826437c86479 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
using System.Linq;
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Search;
using System.Threading.Tasks;
using MediaBrowser.Controller.LiveTv;
using MediaBrowser.Model.Services;

namespace MediaBrowser.Api
{
    /// <summary>
    /// Class GetSearchHints
    /// </summary>
    [Route("/Search/Hints", "GET", Summary = "Gets search hints based on a search term")]
    public class GetSearchHints : IReturn<SearchHintResult>
    {
        /// <summary>
        /// Skips over a given number of items within the results. Use for paging.
        /// </summary>
        /// <value>The start index.</value>
        [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")]
        public int? StartIndex { get; set; }

        /// <summary>
        /// The maximum number of items to return
        /// </summary>
        /// <value>The limit.</value>
        [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
        public int? Limit { get; set; }

        /// <summary>
        /// Gets or sets the user id.
        /// </summary>
        /// <value>The user id.</value>
        [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")]
        public string UserId { get; set; }

        /// <summary>
        /// Search characters used to find items
        /// </summary>
        /// <value>The index by.</value>
        [ApiMember(Name = "SearchTerm", Description = "The search term to filter on", IsRequired = true, DataType = "string", ParameterType = "query", Verb = "GET")]
        public string SearchTerm { get; set; }


        [ApiMember(Name = "IncludePeople", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
        public bool IncludePeople { get; set; }

        [ApiMember(Name = "IncludeMedia", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
        public bool IncludeMedia { get; set; }

        [ApiMember(Name = "IncludeGenres", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
        public bool IncludeGenres { get; set; }

        [ApiMember(Name = "IncludeStudios", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
        public bool IncludeStudios { get; set; }

        [ApiMember(Name = "IncludeArtists", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")]
        public bool IncludeArtists { get; set; }

        [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)]
        public string IncludeItemTypes { get; set; }

        [ApiMember(Name = "ExcludeItemTypes", 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)]
        public string ExcludeItemTypes { get; set; }

        [ApiMember(Name = "MediaTypes", 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)]
        public string MediaTypes { get; set; }

        public string ParentId { get; set; }

        [ApiMember(Name = "IsMovie", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
        public bool? IsMovie { get; set; }

        [ApiMember(Name = "IsSeries", Description = "Optional filter for movies.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
        public bool? IsSeries { get; set; }

        [ApiMember(Name = "IsNews", Description = "Optional filter for news.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
        public bool? IsNews { get; set; }

        [ApiMember(Name = "IsKids", Description = "Optional filter for kids.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
        public bool? IsKids { get; set; }

        [ApiMember(Name = "IsSports", Description = "Optional filter for sports.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET,POST")]
        public bool? IsSports { get; set; }

        public GetSearchHints()
        {
            IncludeArtists = true;
            IncludeGenres = true;
            IncludeMedia = true;
            IncludePeople = true;
            IncludeStudios = true;
        }
    }

    /// <summary>
    /// Class SearchService
    /// </summary>
    [Authenticated]
    public class SearchService : BaseApiService
    {
        /// <summary>
        /// The _search engine
        /// </summary>
        private readonly ISearchEngine _searchEngine;
        private readonly ILibraryManager _libraryManager;
        private readonly IDtoService _dtoService;
        private readonly IImageProcessor _imageProcessor;

        /// <summary>
        /// Initializes a new instance of the <see cref="SearchService" /> class.
        /// </summary>
        /// <param name="searchEngine">The search engine.</param>
        /// <param name="libraryManager">The library manager.</param>
        /// <param name="dtoService">The dto service.</param>
        /// <param name="imageProcessor">The image processor.</param>
        public SearchService(ISearchEngine searchEngine, ILibraryManager libraryManager, IDtoService dtoService, IImageProcessor imageProcessor)
        {
            _searchEngine = searchEngine;
            _libraryManager = libraryManager;
            _dtoService = dtoService;
            _imageProcessor = imageProcessor;
        }

        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public async Task<object> Get(GetSearchHints request)
        {
            var result = await GetSearchHintsAsync(request).ConfigureAwait(false);

            return ToOptimizedSerializedResultUsingCache(result);
        }

        /// <summary>
        /// Gets the search hints async.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Task{IEnumerable{SearchHintResult}}.</returns>
        private async Task<SearchHintResult> GetSearchHintsAsync(GetSearchHints request)
        {
            var result = await _searchEngine.GetSearchHints(new SearchQuery
            {
                Limit = request.Limit,
                SearchTerm = request.SearchTerm,
                IncludeArtists = request.IncludeArtists,
                IncludeGenres = request.IncludeGenres,
                IncludeMedia = request.IncludeMedia,
                IncludePeople = request.IncludePeople,
                IncludeStudios = request.IncludeStudios,
                StartIndex = request.StartIndex,
                UserId = request.UserId,
                IncludeItemTypes = ApiEntryPoint.Split(request.IncludeItemTypes, ',', true),
                ExcludeItemTypes = ApiEntryPoint.Split(request.ExcludeItemTypes, ',', true),
                MediaTypes = ApiEntryPoint.Split(request.MediaTypes, ',', true),
                ParentId = request.ParentId,

                IsKids = request.IsKids,
                IsMovie = request.IsMovie,
                IsNews = request.IsNews,
                IsSeries = request.IsSeries,
                IsSports = request.IsSports

            }).ConfigureAwait(false);

            return new SearchHintResult
            {
                TotalRecordCount = result.TotalRecordCount,

                SearchHints = result.Items.Select(GetSearchHintResult).ToArray()
            };
        }

        /// <summary>
        /// Gets the search hint result.
        /// </summary>
        /// <param name="hintInfo">The hint info.</param>
        /// <returns>SearchHintResult.</returns>
        private SearchHint GetSearchHintResult(SearchHintInfo hintInfo)
        {
            var item = hintInfo.Item;

            var result = new SearchHint
            {
                Name = item.Name,
                IndexNumber = item.IndexNumber,
                ParentIndexNumber = item.ParentIndexNumber,
                ItemId = _dtoService.GetDtoId(item),
                Type = item.GetClientTypeName(),
                MediaType = item.MediaType,
                MatchedTerm = hintInfo.MatchedTerm,
                RunTimeTicks = item.RunTimeTicks,
                ProductionYear = item.ProductionYear,
                ChannelId = item.ChannelId,
                EndDate = item.EndDate
            };

            var primaryImageTag = _imageProcessor.GetImageCacheTag(item, ImageType.Primary);

            if (primaryImageTag != null)
            {
                result.PrimaryImageTag = primaryImageTag;
                result.PrimaryImageAspectRatio = _dtoService.GetPrimaryImageAspectRatio(item);
            }

            SetThumbImageInfo(result, item);
            SetBackdropImageInfo(result, item);

            var program = item as LiveTvProgram;
            if (program != null)
            {
                result.StartDate = program.StartDate;
            }

            var hasSeries = item as IHasSeries;
            if (hasSeries != null)
            {
                result.Series = hasSeries.SeriesName;
            }

            var series = item as Series;
            if (series != null)
            {
                if (series.Status.HasValue)
                {
                    result.Status = series.Status.Value.ToString();
                }
            }

            var album = item as MusicAlbum;

            if (album != null)
            {
                result.Artists = album.Artists;
                result.AlbumArtist = album.AlbumArtist;
            }

            var song = item as Audio;

            if (song != null)
            {
                result.AlbumArtist = song.AlbumArtists.FirstOrDefault();
                result.Artists = song.Artists;

                album = song.AlbumEntity;

                if (album != null)
                {
                    result.Album = album.Name;
                    result.AlbumId = album.Id.ToString("N");
                }
                else
                {
                    result.Album = song.Album;
                }
            }

            if (!string.IsNullOrWhiteSpace(item.ChannelId))
            {
                var channel = _libraryManager.GetItemById(item.ChannelId);
                result.ChannelName = channel == null ? null : channel.Name;
            }

            return result;
        }

        private void SetThumbImageInfo(SearchHint hint, BaseItem item)
        {
            var itemWithImage = item.HasImage(ImageType.Thumb) ? item : null;

            if (itemWithImage == null)
            {
                if (item is Episode)
                {
                    itemWithImage = GetParentWithImage<Series>(item, ImageType.Thumb);
                }
            }

            if (itemWithImage == null)
            {
                itemWithImage = GetParentWithImage<BaseItem>(item, ImageType.Thumb);
            }

            if (itemWithImage != null)
            {
                var tag = _imageProcessor.GetImageCacheTag(itemWithImage, ImageType.Thumb);

                if (tag != null)
                {
                    hint.ThumbImageTag = tag;
                    hint.ThumbImageItemId = itemWithImage.Id.ToString("N");
                }
            }
        }

        private void SetBackdropImageInfo(SearchHint hint, BaseItem item)
        {
            var itemWithImage = item.HasImage(ImageType.Backdrop) ? item : null;

            if (itemWithImage == null)
            {
                itemWithImage = GetParentWithImage<BaseItem>(item, ImageType.Backdrop);
            }

            if (itemWithImage != null)
            {
                var tag = _imageProcessor.GetImageCacheTag(itemWithImage, ImageType.Backdrop);

                if (tag != null)
                {
                    hint.BackdropImageTag = tag;
                    hint.BackdropImageItemId = itemWithImage.Id.ToString("N");
                }
            }
        }

        private T GetParentWithImage<T>(BaseItem item, ImageType type)
            where T : BaseItem
        {
            return item.GetParents().OfType<T>().FirstOrDefault(i => i.HasImage(type));
        }
    }
}