aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Api/Controllers/SearchController.cs
blob: aeed0c0d61f57a8740db57d329391c09bb5a14a9 (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
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using Jellyfin.Api.Constants;
using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Enums;
using Jellyfin.Extensions;
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.LiveTv;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Search;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Jellyfin.Api.Controllers
{
    /// <summary>
    /// Search controller.
    /// </summary>
    [Route("Search/Hints")]
    [Authorize(Policy = Policies.DefaultAuthorization)]
    public class SearchController : BaseJellyfinApiController
    {
        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="SearchController"/> class.
        /// </summary>
        /// <param name="searchEngine">Instance of <see cref="ISearchEngine"/> interface.</param>
        /// <param name="libraryManager">Instance of <see cref="ILibraryManager"/> interface.</param>
        /// <param name="dtoService">Instance of <see cref="IDtoService"/> interface.</param>
        /// <param name="imageProcessor">Instance of <see cref="IImageProcessor"/> interface.</param>
        public SearchController(
            ISearchEngine searchEngine,
            ILibraryManager libraryManager,
            IDtoService dtoService,
            IImageProcessor imageProcessor)
        {
            _searchEngine = searchEngine;
            _libraryManager = libraryManager;
            _dtoService = dtoService;
            _imageProcessor = imageProcessor;
        }

        /// <summary>
        /// Gets the search hint result.
        /// </summary>
        /// <param name="startIndex">Optional. The record index to start at. All items with a lower index will be dropped from the results.</param>
        /// <param name="limit">Optional. The maximum number of records to return.</param>
        /// <param name="userId">Optional. Supply a user id to search within a user's library or omit to search all.</param>
        /// <param name="searchTerm">The search term to filter on.</param>
        /// <param name="includeItemTypes">If specified, only results with the specified item types are returned. This allows multiple, comma delimited.</param>
        /// <param name="excludeItemTypes">If specified, results with these item types are filtered out. This allows multiple, comma delimited.</param>
        /// <param name="mediaTypes">If specified, only results with the specified media types are returned. This allows multiple, comma delimited.</param>
        /// <param name="parentId">If specified, only children of the parent are returned.</param>
        /// <param name="isMovie">Optional filter for movies.</param>
        /// <param name="isSeries">Optional filter for series.</param>
        /// <param name="isNews">Optional filter for news.</param>
        /// <param name="isKids">Optional filter for kids.</param>
        /// <param name="isSports">Optional filter for sports.</param>
        /// <param name="includePeople">Optional filter whether to include people.</param>
        /// <param name="includeMedia">Optional filter whether to include media.</param>
        /// <param name="includeGenres">Optional filter whether to include genres.</param>
        /// <param name="includeStudios">Optional filter whether to include studios.</param>
        /// <param name="includeArtists">Optional filter whether to include artists.</param>
        /// <response code="200">Search hint returned.</response>
        /// <returns>An <see cref="SearchHintResult"/> with the results of the search.</returns>
        [HttpGet]
        [Description("Gets search hints based on a search term")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public ActionResult<SearchHintResult> GetSearchHints(
            [FromQuery] int? startIndex,
            [FromQuery] int? limit,
            [FromQuery] Guid? userId,
            [FromQuery, Required] string searchTerm,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes,
            [FromQuery] Guid? parentId,
            [FromQuery] bool? isMovie,
            [FromQuery] bool? isSeries,
            [FromQuery] bool? isNews,
            [FromQuery] bool? isKids,
            [FromQuery] bool? isSports,
            [FromQuery] bool includePeople = true,
            [FromQuery] bool includeMedia = true,
            [FromQuery] bool includeGenres = true,
            [FromQuery] bool includeStudios = true,
            [FromQuery] bool includeArtists = true)
        {
            var result = _searchEngine.GetSearchHints(new SearchQuery
            {
                Limit = limit,
                SearchTerm = searchTerm,
                IncludeArtists = includeArtists,
                IncludeGenres = includeGenres,
                IncludeMedia = includeMedia,
                IncludePeople = includePeople,
                IncludeStudios = includeStudios,
                StartIndex = startIndex,
                UserId = userId ?? Guid.Empty,
                IncludeItemTypes = includeItemTypes,
                ExcludeItemTypes = excludeItemTypes,
                MediaTypes = mediaTypes,
                ParentId = parentId,

                IsKids = isKids,
                IsMovie = isMovie,
                IsNews = isNews,
                IsSeries = isSeries,
                IsSports = isSports
            });

            return new SearchHintResult(result.Items.Select(GetSearchHintResult).ToArray(), result.TotalRecordCount);
        }

        /// <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,
                Id = item.Id,
                Type = item.GetBaseItemKind(),
                MediaType = item.MediaType,
                MatchedTerm = hintInfo.MatchedTerm,
                RunTimeTicks = item.RunTimeTicks,
                ProductionYear = item.ProductionYear,
                ChannelId = item.ChannelId,
                EndDate = item.EndDate
            };

#pragma warning disable CS0618
            // Kept for compatibility with older clients
            result.ItemId = result.Id;
#pragma warning restore CS0618

            if (item.IsFolder)
            {
                result.IsFolder = true;
            }

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

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

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

            switch (item)
            {
                case IHasSeries hasSeries:
                    result.Series = hasSeries.SeriesName;
                    break;
                case LiveTvProgram program:
                    result.StartDate = program.StartDate;
                    break;
                case Series series:
                    if (series.Status.HasValue)
                    {
                        result.Status = series.Status.Value.ToString();
                    }

                    break;
                case MusicAlbum album:
                    result.Artists = album.Artists;
                    result.AlbumArtist = album.AlbumArtist;
                    break;
                case Audio song:
                    result.AlbumArtist = song.AlbumArtists?.FirstOrDefault();
                    result.Artists = song.Artists;

                    MusicAlbum musicAlbum = song.AlbumEntity;

                    if (musicAlbum != null)
                    {
                        result.Album = musicAlbum.Name;
                        result.AlbumId = musicAlbum.Id;
                    }
                    else
                    {
                        result.Album = song.Album;
                    }

                    break;
            }

            if (!item.ChannelId.Equals(default))
            {
                var channel = _libraryManager.GetItemById(item.ChannelId);
                result.ChannelName = channel?.Name;
            }

            return result;
        }

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

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

            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", CultureInfo.InvariantCulture);
                }
            }
        }

        private void SetBackdropImageInfo(SearchHint hint, BaseItem item)
        {
            var itemWithImage = (item.HasImage(ImageType.Backdrop) ? item : null)
                ?? 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", CultureInfo.InvariantCulture);
                }
            }
        }

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