aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Api/Controllers/ItemsController.cs
blob: 7582c94cfeb99635e0b35ade348d42dd65b06e5a (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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Jellyfin.Api.Constants;
using Jellyfin.Api.Extensions;
using Jellyfin.Api.Helpers;
using Jellyfin.Api.ModelBinders;
using Jellyfin.Data.Enums;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Net;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Dto;
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.Globalization;
using MediaBrowser.Model.Querying;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Jellyfin.Api.Controllers
{
    /// <summary>
    /// The items controller.
    /// </summary>
    [Route("")]
    [Authorize(Policy = Policies.DefaultAuthorization)]
    public class ItemsController : BaseJellyfinApiController
    {
        private readonly IUserManager _userManager;
        private readonly ILibraryManager _libraryManager;
        private readonly ILocalizationManager _localization;
        private readonly IDtoService _dtoService;
        private readonly IAuthorizationContext _authContext;
        private readonly ILogger<ItemsController> _logger;
        private readonly ISessionManager _sessionManager;

        /// <summary>
        /// Initializes a new instance of the <see cref="ItemsController"/> class.
        /// </summary>
        /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param>
        /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param>
        /// <param name="localization">Instance of the <see cref="ILocalizationManager"/> interface.</param>
        /// <param name="dtoService">Instance of the <see cref="IDtoService"/> interface.</param>
        /// <param name="authContext">Instance of the <see cref="IAuthorizationContext"/> interface.</param>
        /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
        /// <param name="sessionManager">Instance of the <see cref="ISessionManager"/> interface.</param>
        public ItemsController(
            IUserManager userManager,
            ILibraryManager libraryManager,
            ILocalizationManager localization,
            IDtoService dtoService,
            IAuthorizationContext authContext,
            ILogger<ItemsController> logger,
            ISessionManager sessionManager)
        {
            _userManager = userManager;
            _libraryManager = libraryManager;
            _localization = localization;
            _dtoService = dtoService;
            _authContext = authContext;
            _logger = logger;
            _sessionManager = sessionManager;
        }

        /// <summary>
        /// Gets items based on a query.
        /// </summary>
        /// <param name="userId">The user id supplied as query parameter.</param>
        /// <param name="maxOfficialRating">Optional filter by maximum official rating (PG, PG-13, TV-MA, etc).</param>
        /// <param name="hasThemeSong">Optional filter by items with theme songs.</param>
        /// <param name="hasThemeVideo">Optional filter by items with theme videos.</param>
        /// <param name="hasSubtitles">Optional filter by items with subtitles.</param>
        /// <param name="hasSpecialFeature">Optional filter by items with special features.</param>
        /// <param name="hasTrailer">Optional filter by items with trailers.</param>
        /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param>
        /// <param name="parentIndexNumber">Optional filter by parent index number.</param>
        /// <param name="hasParentalRating">Optional filter by items that have or do not have a parental rating.</param>
        /// <param name="isHd">Optional filter by items that are HD or not.</param>
        /// <param name="is4K">Optional filter by items that are 4K or not.</param>
        /// <param name="locationTypes">Optional. If specified, results will be filtered based on LocationType. This allows multiple, comma delimited.</param>
        /// <param name="excludeLocationTypes">Optional. If specified, results will be filtered based on the LocationType. This allows multiple, comma delimited.</param>
        /// <param name="isMissing">Optional filter by items that are missing episodes or not.</param>
        /// <param name="isUnaired">Optional filter by items that are unaired episodes or not.</param>
        /// <param name="minCommunityRating">Optional filter by minimum community rating.</param>
        /// <param name="minCriticRating">Optional filter by minimum critic rating.</param>
        /// <param name="minPremiereDate">Optional. The minimum premiere date. Format = ISO.</param>
        /// <param name="minDateLastSaved">Optional. The minimum last saved date. Format = ISO.</param>
        /// <param name="minDateLastSavedForUser">Optional. The minimum last saved date for the current user. Format = ISO.</param>
        /// <param name="maxPremiereDate">Optional. The maximum premiere date. Format = ISO.</param>
        /// <param name="hasOverview">Optional filter by items that have an overview or not.</param>
        /// <param name="hasImdbId">Optional filter by items that have an imdb id or not.</param>
        /// <param name="hasTmdbId">Optional filter by items that have a tmdb id or not.</param>
        /// <param name="hasTvdbId">Optional filter by items that have a tvdb id or not.</param>
        /// <param name="isMovie">Optional filter for live tv movies.</param>
        /// <param name="isSeries">Optional filter for live tv series.</param>
        /// <param name="isNews">Optional filter for live tv news.</param>
        /// <param name="isKids">Optional filter for live tv kids.</param>
        /// <param name="isSports">Optional filter for live tv sports.</param>
        /// <param name="excludeItemIds">Optional. If specified, results will be filtered by excluding item ids. This allows multiple, comma delimited.</param>
        /// <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="recursive">When searching within folders, this determines whether or not the search will be recursive. true/false.</param>
        /// <param name="searchTerm">Optional. Filter based on a search term.</param>
        /// <param name="sortOrder">Sort Order - Ascending,Descending.</param>
        /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
        /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param>
        /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
        /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.</param>
        /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.</param>
        /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param>
        /// <param name="mediaTypes">Optional filter by MediaType. Allows multiple, comma delimited.</param>
        /// <param name="imageTypes">Optional. If specified, results will be filtered based on those containing image types. This allows multiple, comma delimited.</param>
        /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param>
        /// <param name="isPlayed">Optional filter by items that are played, or not.</param>
        /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.</param>
        /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.</param>
        /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.</param>
        /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.</param>
        /// <param name="enableUserData">Optional, include user data.</param>
        /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
        /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
        /// <param name="person">Optional. If specified, results will be filtered to include only those containing the specified person.</param>
        /// <param name="personIds">Optional. If specified, results will be filtered to include only those containing the specified person id.</param>
        /// <param name="personTypes">Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.</param>
        /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.</param>
        /// <param name="artists">Optional. If specified, results will be filtered based on artists. This allows multiple, pipe delimited.</param>
        /// <param name="excludeArtistIds">Optional. If specified, results will be filtered based on artist id. This allows multiple, pipe delimited.</param>
        /// <param name="artistIds">Optional. If specified, results will be filtered to include only those containing the specified artist id.</param>
        /// <param name="albumArtistIds">Optional. If specified, results will be filtered to include only those containing the specified album artist id.</param>
        /// <param name="contributingArtistIds">Optional. If specified, results will be filtered to include only those containing the specified contributing artist id.</param>
        /// <param name="albums">Optional. If specified, results will be filtered based on album. This allows multiple, pipe delimited.</param>
        /// <param name="albumIds">Optional. If specified, results will be filtered based on album id. This allows multiple, pipe delimited.</param>
        /// <param name="ids">Optional. If specific items are needed, specify a list of item id's to retrieve. This allows multiple, comma delimited.</param>
        /// <param name="videoTypes">Optional filter by VideoType (videofile, dvd, bluray, iso). Allows multiple, comma delimited.</param>
        /// <param name="minOfficialRating">Optional filter by minimum official rating (PG, PG-13, TV-MA, etc).</param>
        /// <param name="isLocked">Optional filter by items that are locked.</param>
        /// <param name="isPlaceHolder">Optional filter by items that are placeholders.</param>
        /// <param name="hasOfficialRating">Optional filter by items that have official ratings.</param>
        /// <param name="collapseBoxSetItems">Whether or not to hide items behind their boxsets.</param>
        /// <param name="minWidth">Optional. Filter by the minimum width of the item.</param>
        /// <param name="minHeight">Optional. Filter by the minimum height of the item.</param>
        /// <param name="maxWidth">Optional. Filter by the maximum width of the item.</param>
        /// <param name="maxHeight">Optional. Filter by the maximum height of the item.</param>
        /// <param name="is3D">Optional filter by items that are 3D, or not.</param>
        /// <param name="seriesStatus">Optional filter by Series Status. Allows multiple, comma delimited.</param>
        /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param>
        /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param>
        /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param>
        /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.</param>
        /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.</param>
        /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param>
        /// <param name="enableImages">Optional, include image information in output.</param>
        /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items.</returns>
        [HttpGet("Items")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public async Task<ActionResult<QueryResult<BaseItemDto>>> GetItems(
            [FromQuery] Guid? userId,
            [FromQuery] string? maxOfficialRating,
            [FromQuery] bool? hasThemeSong,
            [FromQuery] bool? hasThemeVideo,
            [FromQuery] bool? hasSubtitles,
            [FromQuery] bool? hasSpecialFeature,
            [FromQuery] bool? hasTrailer,
            [FromQuery] string? adjacentTo,
            [FromQuery] int? parentIndexNumber,
            [FromQuery] bool? hasParentalRating,
            [FromQuery] bool? isHd,
            [FromQuery] bool? is4K,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] locationTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes,
            [FromQuery] bool? isMissing,
            [FromQuery] bool? isUnaired,
            [FromQuery] double? minCommunityRating,
            [FromQuery] double? minCriticRating,
            [FromQuery] DateTime? minPremiereDate,
            [FromQuery] DateTime? minDateLastSaved,
            [FromQuery] DateTime? minDateLastSavedForUser,
            [FromQuery] DateTime? maxPremiereDate,
            [FromQuery] bool? hasOverview,
            [FromQuery] bool? hasImdbId,
            [FromQuery] bool? hasTmdbId,
            [FromQuery] bool? hasTvdbId,
            [FromQuery] bool? isMovie,
            [FromQuery] bool? isSeries,
            [FromQuery] bool? isNews,
            [FromQuery] bool? isKids,
            [FromQuery] bool? isSports,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeItemIds,
            [FromQuery] int? startIndex,
            [FromQuery] int? limit,
            [FromQuery] bool? recursive,
            [FromQuery] string? searchTerm,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder,
            [FromQuery] Guid? parentId,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
            [FromQuery] bool? isFavorite,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy,
            [FromQuery] bool? isPlayed,
            [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres,
            [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings,
            [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] tags,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] int[] years,
            [FromQuery] bool? enableUserData,
            [FromQuery] int? imageTypeLimit,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
            [FromQuery] string? person,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes,
            [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] studios,
            [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] artists,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] artistIds,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumArtistIds,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] contributingArtistIds,
            [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] albums,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumIds,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] VideoType[] videoTypes,
            [FromQuery] string? minOfficialRating,
            [FromQuery] bool? isLocked,
            [FromQuery] bool? isPlaceHolder,
            [FromQuery] bool? hasOfficialRating,
            [FromQuery] bool? collapseBoxSetItems,
            [FromQuery] int? minWidth,
            [FromQuery] int? minHeight,
            [FromQuery] int? maxWidth,
            [FromQuery] int? maxHeight,
            [FromQuery] bool? is3D,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SeriesStatus[] seriesStatus,
            [FromQuery] string? nameStartsWithOrGreater,
            [FromQuery] string? nameStartsWith,
            [FromQuery] string? nameLessThan,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds,
            [FromQuery] bool enableTotalRecordCount = true,
            [FromQuery] bool? enableImages = true)
        {
            var auth = await _authContext.GetAuthorizationInfo(Request).ConfigureAwait(false);

            var user = !auth.IsApiKey && userId.HasValue && !userId.Equals(Guid.Empty)
                ? _userManager.GetUserById(userId.Value)
                : null;

            if (!auth.IsApiKey && user is null)
            {
                return BadRequest("userId is required");
            }

            var dtoOptions = new DtoOptions { Fields = fields }
                .AddClientFields(Request)
                .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);

            if (includeItemTypes.Length == 1
                && (includeItemTypes[0] == BaseItemKind.Playlist
                    || includeItemTypes[0] == BaseItemKind.BoxSet))
            {
                parentId = null;
            }

            var item = _libraryManager.GetParentItem(parentId, userId);
            QueryResult<BaseItem> result;

            if (item is not Folder folder)
            {
                folder = _libraryManager.GetUserRootFolder();
            }

            string? collectionType = null;
            if (folder is IHasCollectionType hasCollectionType)
            {
                collectionType = hasCollectionType.CollectionType;
            }

            if (string.Equals(collectionType, CollectionType.Playlists, StringComparison.OrdinalIgnoreCase))
            {
                recursive = true;
                includeItemTypes = new[] { BaseItemKind.Playlist };
            }

            var enabledChannels = auth.IsApiKey
                ? Array.Empty<Guid>()
                : user.GetPreferenceValues<Guid>(PreferenceKind.EnabledChannels);

            bool isInEnabledFolder = auth.IsApiKey
                                     || Array.IndexOf(user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders), item.Id) != -1
                                     // Assume all folders inside an EnabledChannel are enabled
                                     || Array.IndexOf(enabledChannels, item.Id) != -1
                                     // Assume all items inside an EnabledChannel are enabled
                                     || Array.IndexOf(enabledChannels, item.ChannelId) != -1;

            if (!isInEnabledFolder)
            {
                var collectionFolders = _libraryManager.GetCollectionFolders(item);
                foreach (var collectionFolder in collectionFolders)
                {
                    if (user.GetPreferenceValues<Guid>(PreferenceKind.EnabledFolders).Contains(collectionFolder.Id))
                    {
                        isInEnabledFolder = true;
                    }
                }
            }

            if (item is not UserRootFolder
                && !isInEnabledFolder
                && !user.HasPermission(PermissionKind.EnableAllFolders)
                && !user.HasPermission(PermissionKind.EnableAllChannels)
                && !string.Equals(collectionType, CollectionType.Folders, StringComparison.OrdinalIgnoreCase))
            {
                _logger.LogWarning("{UserName} is not permitted to access Library {ItemName}", user.Username, item.Name);
                return Unauthorized($"{user.Username} is not permitted to access Library {item.Name}.");
            }

            if ((recursive.HasValue && recursive.Value) || ids.Length != 0 || item is not UserRootFolder)
            {
                var query = new InternalItemsQuery(user)
                {
                    IsPlayed = isPlayed,
                    MediaTypes = mediaTypes,
                    IncludeItemTypes = includeItemTypes,
                    ExcludeItemTypes = excludeItemTypes,
                    Recursive = recursive ?? false,
                    OrderBy = RequestHelpers.GetOrderBy(sortBy, sortOrder),
                    IsFavorite = isFavorite,
                    Limit = limit,
                    StartIndex = startIndex,
                    IsMissing = isMissing,
                    IsUnaired = isUnaired,
                    CollapseBoxSetItems = collapseBoxSetItems,
                    NameLessThan = nameLessThan,
                    NameStartsWith = nameStartsWith,
                    NameStartsWithOrGreater = nameStartsWithOrGreater,
                    HasImdbId = hasImdbId,
                    IsPlaceHolder = isPlaceHolder,
                    IsLocked = isLocked,
                    MinWidth = minWidth,
                    MinHeight = minHeight,
                    MaxWidth = maxWidth,
                    MaxHeight = maxHeight,
                    Is3D = is3D,
                    HasTvdbId = hasTvdbId,
                    HasTmdbId = hasTmdbId,
                    IsMovie = isMovie,
                    IsSeries = isSeries,
                    IsNews = isNews,
                    IsKids = isKids,
                    IsSports = isSports,
                    HasOverview = hasOverview,
                    HasOfficialRating = hasOfficialRating,
                    HasParentalRating = hasParentalRating,
                    HasSpecialFeature = hasSpecialFeature,
                    HasSubtitles = hasSubtitles,
                    HasThemeSong = hasThemeSong,
                    HasThemeVideo = hasThemeVideo,
                    HasTrailer = hasTrailer,
                    IsHD = isHd,
                    Is4K = is4K,
                    Tags = tags,
                    OfficialRatings = officialRatings,
                    Genres = genres,
                    ArtistIds = artistIds,
                    AlbumArtistIds = albumArtistIds,
                    ContributingArtistIds = contributingArtistIds,
                    GenreIds = genreIds,
                    StudioIds = studioIds,
                    Person = person,
                    PersonIds = personIds,
                    PersonTypes = personTypes,
                    Years = years,
                    ImageTypes = imageTypes,
                    VideoTypes = videoTypes,
                    AdjacentTo = adjacentTo,
                    ItemIds = ids,
                    MinCommunityRating = minCommunityRating,
                    MinCriticRating = minCriticRating,
                    ParentId = parentId ?? Guid.Empty,
                    ParentIndexNumber = parentIndexNumber,
                    EnableTotalRecordCount = enableTotalRecordCount,
                    ExcludeItemIds = excludeItemIds,
                    DtoOptions = dtoOptions,
                    SearchTerm = searchTerm,
                    MinDateLastSaved = minDateLastSaved?.ToUniversalTime(),
                    MinDateLastSavedForUser = minDateLastSavedForUser?.ToUniversalTime(),
                    MinPremiereDate = minPremiereDate?.ToUniversalTime(),
                    MaxPremiereDate = maxPremiereDate?.ToUniversalTime(),
                };

                if (ids.Length != 0 || !string.IsNullOrWhiteSpace(searchTerm))
                {
                    query.CollapseBoxSetItems = false;
                }

                foreach (var filter in filters)
                {
                    switch (filter)
                    {
                        case ItemFilter.Dislikes:
                            query.IsLiked = false;
                            break;
                        case ItemFilter.IsFavorite:
                            query.IsFavorite = true;
                            break;
                        case ItemFilter.IsFavoriteOrLikes:
                            query.IsFavoriteOrLiked = true;
                            break;
                        case ItemFilter.IsFolder:
                            query.IsFolder = true;
                            break;
                        case ItemFilter.IsNotFolder:
                            query.IsFolder = false;
                            break;
                        case ItemFilter.IsPlayed:
                            query.IsPlayed = true;
                            break;
                        case ItemFilter.IsResumable:
                            query.IsResumable = true;
                            break;
                        case ItemFilter.IsUnplayed:
                            query.IsPlayed = false;
                            break;
                        case ItemFilter.Likes:
                            query.IsLiked = true;
                            break;
                    }
                }

                // Filter by Series Status
                if (seriesStatus.Length != 0)
                {
                    query.SeriesStatuses = seriesStatus;
                }

                // ExcludeLocationTypes
                if (excludeLocationTypes.Any(t => t == LocationType.Virtual))
                {
                    query.IsVirtualItem = false;
                }

                if (locationTypes.Length > 0 && locationTypes.Length < 4)
                {
                    query.IsVirtualItem = locationTypes.Contains(LocationType.Virtual);
                }

                // Min official rating
                if (!string.IsNullOrWhiteSpace(minOfficialRating))
                {
                    query.MinParentalRating = _localization.GetRatingLevel(minOfficialRating);
                }

                // Max official rating
                if (!string.IsNullOrWhiteSpace(maxOfficialRating))
                {
                    query.MaxParentalRating = _localization.GetRatingLevel(maxOfficialRating);
                }

                // Artists
                if (artists.Length != 0)
                {
                    query.ArtistIds = artists.Select(i =>
                    {
                        try
                        {
                            return _libraryManager.GetArtist(i, new DtoOptions(false));
                        }
                        catch
                        {
                            return null;
                        }
                    }).Where(i => i != null).Select(i => i!.Id).ToArray();
                }

                // ExcludeArtistIds
                if (excludeArtistIds.Length != 0)
                {
                    query.ExcludeArtistIds = excludeArtistIds;
                }

                if (albumIds.Length != 0)
                {
                    query.AlbumIds = albumIds;
                }

                // Albums
                if (albums.Length != 0)
                {
                    query.AlbumIds = albums.SelectMany(i =>
                    {
                        return _libraryManager.GetItemIds(new InternalItemsQuery { IncludeItemTypes = new[] { BaseItemKind.MusicAlbum }, Name = i, Limit = 1 });
                    }).ToArray();
                }

                // Studios
                if (studios.Length != 0)
                {
                    query.StudioIds = studios.Select(i =>
                    {
                        try
                        {
                            return _libraryManager.GetStudio(i);
                        }
                        catch
                        {
                            return null;
                        }
                    }).Where(i => i != null).Select(i => i!.Id).ToArray();
                }

                // Apply default sorting if none requested
                if (query.OrderBy.Count == 0)
                {
                    // Albums by artist
                    if (query.ArtistIds.Length > 0 && query.IncludeItemTypes.Length == 1 && query.IncludeItemTypes[0] == BaseItemKind.MusicAlbum)
                    {
                        query.OrderBy = new[] { (ItemSortBy.ProductionYear, SortOrder.Descending), (ItemSortBy.SortName, SortOrder.Ascending) };
                    }
                }

                result = folder.GetItems(query);
            }
            else
            {
                var itemsArray = folder.GetChildren(user, true);
                result = new QueryResult<BaseItem>(itemsArray);
            }

            return new QueryResult<BaseItemDto>(
                startIndex,
                result.TotalRecordCount,
                _dtoService.GetBaseItemDtos(result.Items, dtoOptions, user));
        }

        /// <summary>
        /// Gets items based on a query.
        /// </summary>
        /// <param name="userId">The user id supplied as query parameter.</param>
        /// <param name="maxOfficialRating">Optional filter by maximum official rating (PG, PG-13, TV-MA, etc).</param>
        /// <param name="hasThemeSong">Optional filter by items with theme songs.</param>
        /// <param name="hasThemeVideo">Optional filter by items with theme videos.</param>
        /// <param name="hasSubtitles">Optional filter by items with subtitles.</param>
        /// <param name="hasSpecialFeature">Optional filter by items with special features.</param>
        /// <param name="hasTrailer">Optional filter by items with trailers.</param>
        /// <param name="adjacentTo">Optional. Return items that are siblings of a supplied item.</param>
        /// <param name="parentIndexNumber">Optional filter by parent index number.</param>
        /// <param name="hasParentalRating">Optional filter by items that have or do not have a parental rating.</param>
        /// <param name="isHd">Optional filter by items that are HD or not.</param>
        /// <param name="is4K">Optional filter by items that are 4K or not.</param>
        /// <param name="locationTypes">Optional. If specified, results will be filtered based on LocationType. This allows multiple, comma delimited.</param>
        /// <param name="excludeLocationTypes">Optional. If specified, results will be filtered based on the LocationType. This allows multiple, comma delimited.</param>
        /// <param name="isMissing">Optional filter by items that are missing episodes or not.</param>
        /// <param name="isUnaired">Optional filter by items that are unaired episodes or not.</param>
        /// <param name="minCommunityRating">Optional filter by minimum community rating.</param>
        /// <param name="minCriticRating">Optional filter by minimum critic rating.</param>
        /// <param name="minPremiereDate">Optional. The minimum premiere date. Format = ISO.</param>
        /// <param name="minDateLastSaved">Optional. The minimum last saved date. Format = ISO.</param>
        /// <param name="minDateLastSavedForUser">Optional. The minimum last saved date for the current user. Format = ISO.</param>
        /// <param name="maxPremiereDate">Optional. The maximum premiere date. Format = ISO.</param>
        /// <param name="hasOverview">Optional filter by items that have an overview or not.</param>
        /// <param name="hasImdbId">Optional filter by items that have an imdb id or not.</param>
        /// <param name="hasTmdbId">Optional filter by items that have a tmdb id or not.</param>
        /// <param name="hasTvdbId">Optional filter by items that have a tvdb id or not.</param>
        /// <param name="isMovie">Optional filter for live tv movies.</param>
        /// <param name="isSeries">Optional filter for live tv series.</param>
        /// <param name="isNews">Optional filter for live tv news.</param>
        /// <param name="isKids">Optional filter for live tv kids.</param>
        /// <param name="isSports">Optional filter for live tv sports.</param>
        /// <param name="excludeItemIds">Optional. If specified, results will be filtered by excluding item ids. This allows multiple, comma delimited.</param>
        /// <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="recursive">When searching within folders, this determines whether or not the search will be recursive. true/false.</param>
        /// <param name="searchTerm">Optional. Filter based on a search term.</param>
        /// <param name="sortOrder">Sort Order - Ascending,Descending.</param>
        /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
        /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param>
        /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
        /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.</param>
        /// <param name="filters">Optional. Specify additional filters to apply. This allows multiple, comma delimited. Options: IsFolder, IsNotFolder, IsUnplayed, IsPlayed, IsFavorite, IsResumable, Likes, Dislikes.</param>
        /// <param name="isFavorite">Optional filter by items that are marked as favorite, or not.</param>
        /// <param name="mediaTypes">Optional filter by MediaType. Allows multiple, comma delimited.</param>
        /// <param name="imageTypes">Optional. If specified, results will be filtered based on those containing image types. This allows multiple, comma delimited.</param>
        /// <param name="sortBy">Optional. Specify one or more sort orders, comma delimited. Options: Album, AlbumArtist, Artist, Budget, CommunityRating, CriticRating, DateCreated, DatePlayed, PlayCount, PremiereDate, ProductionYear, SortName, Random, Revenue, Runtime.</param>
        /// <param name="isPlayed">Optional filter by items that are played, or not.</param>
        /// <param name="genres">Optional. If specified, results will be filtered based on genre. This allows multiple, pipe delimited.</param>
        /// <param name="officialRatings">Optional. If specified, results will be filtered based on OfficialRating. This allows multiple, pipe delimited.</param>
        /// <param name="tags">Optional. If specified, results will be filtered based on tag. This allows multiple, pipe delimited.</param>
        /// <param name="years">Optional. If specified, results will be filtered based on production year. This allows multiple, comma delimited.</param>
        /// <param name="enableUserData">Optional, include user data.</param>
        /// <param name="imageTypeLimit">Optional, the max number of images to return, per image type.</param>
        /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
        /// <param name="person">Optional. If specified, results will be filtered to include only those containing the specified person.</param>
        /// <param name="personIds">Optional. If specified, results will be filtered to include only those containing the specified person id.</param>
        /// <param name="personTypes">Optional. If specified, along with Person, results will be filtered to include only those containing the specified person and PersonType. Allows multiple, comma-delimited.</param>
        /// <param name="studios">Optional. If specified, results will be filtered based on studio. This allows multiple, pipe delimited.</param>
        /// <param name="artists">Optional. If specified, results will be filtered based on artists. This allows multiple, pipe delimited.</param>
        /// <param name="excludeArtistIds">Optional. If specified, results will be filtered based on artist id. This allows multiple, pipe delimited.</param>
        /// <param name="artistIds">Optional. If specified, results will be filtered to include only those containing the specified artist id.</param>
        /// <param name="albumArtistIds">Optional. If specified, results will be filtered to include only those containing the specified album artist id.</param>
        /// <param name="contributingArtistIds">Optional. If specified, results will be filtered to include only those containing the specified contributing artist id.</param>
        /// <param name="albums">Optional. If specified, results will be filtered based on album. This allows multiple, pipe delimited.</param>
        /// <param name="albumIds">Optional. If specified, results will be filtered based on album id. This allows multiple, pipe delimited.</param>
        /// <param name="ids">Optional. If specific items are needed, specify a list of item id's to retrieve. This allows multiple, comma delimited.</param>
        /// <param name="videoTypes">Optional filter by VideoType (videofile, dvd, bluray, iso). Allows multiple, comma delimited.</param>
        /// <param name="minOfficialRating">Optional filter by minimum official rating (PG, PG-13, TV-MA, etc).</param>
        /// <param name="isLocked">Optional filter by items that are locked.</param>
        /// <param name="isPlaceHolder">Optional filter by items that are placeholders.</param>
        /// <param name="hasOfficialRating">Optional filter by items that have official ratings.</param>
        /// <param name="collapseBoxSetItems">Whether or not to hide items behind their boxsets.</param>
        /// <param name="minWidth">Optional. Filter by the minimum width of the item.</param>
        /// <param name="minHeight">Optional. Filter by the minimum height of the item.</param>
        /// <param name="maxWidth">Optional. Filter by the maximum width of the item.</param>
        /// <param name="maxHeight">Optional. Filter by the maximum height of the item.</param>
        /// <param name="is3D">Optional filter by items that are 3D, or not.</param>
        /// <param name="seriesStatus">Optional filter by Series Status. Allows multiple, comma delimited.</param>
        /// <param name="nameStartsWithOrGreater">Optional filter by items whose name is sorted equally or greater than a given input string.</param>
        /// <param name="nameStartsWith">Optional filter by items whose name is sorted equally than a given input string.</param>
        /// <param name="nameLessThan">Optional filter by items whose name is equally or lesser than a given input string.</param>
        /// <param name="studioIds">Optional. If specified, results will be filtered based on studio id. This allows multiple, pipe delimited.</param>
        /// <param name="genreIds">Optional. If specified, results will be filtered based on genre id. This allows multiple, pipe delimited.</param>
        /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param>
        /// <param name="enableImages">Optional, include image information in output.</param>
        /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items.</returns>
        [HttpGet("Users/{userId}/Items")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public Task<ActionResult<QueryResult<BaseItemDto>>> GetItemsByUserId(
            [FromRoute] Guid userId,
            [FromQuery] string? maxOfficialRating,
            [FromQuery] bool? hasThemeSong,
            [FromQuery] bool? hasThemeVideo,
            [FromQuery] bool? hasSubtitles,
            [FromQuery] bool? hasSpecialFeature,
            [FromQuery] bool? hasTrailer,
            [FromQuery] string? adjacentTo,
            [FromQuery] int? parentIndexNumber,
            [FromQuery] bool? hasParentalRating,
            [FromQuery] bool? isHd,
            [FromQuery] bool? is4K,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] locationTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] LocationType[] excludeLocationTypes,
            [FromQuery] bool? isMissing,
            [FromQuery] bool? isUnaired,
            [FromQuery] double? minCommunityRating,
            [FromQuery] double? minCriticRating,
            [FromQuery] DateTime? minPremiereDate,
            [FromQuery] DateTime? minDateLastSaved,
            [FromQuery] DateTime? minDateLastSavedForUser,
            [FromQuery] DateTime? maxPremiereDate,
            [FromQuery] bool? hasOverview,
            [FromQuery] bool? hasImdbId,
            [FromQuery] bool? hasTmdbId,
            [FromQuery] bool? hasTvdbId,
            [FromQuery] bool? isMovie,
            [FromQuery] bool? isSeries,
            [FromQuery] bool? isNews,
            [FromQuery] bool? isKids,
            [FromQuery] bool? isSports,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeItemIds,
            [FromQuery] int? startIndex,
            [FromQuery] int? limit,
            [FromQuery] bool? recursive,
            [FromQuery] string? searchTerm,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SortOrder[] sortOrder,
            [FromQuery] Guid? parentId,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFilter[] filters,
            [FromQuery] bool? isFavorite,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] imageTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] sortBy,
            [FromQuery] bool? isPlayed,
            [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] genres,
            [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] officialRatings,
            [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] tags,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] int[] years,
            [FromQuery] bool? enableUserData,
            [FromQuery] int? imageTypeLimit,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
            [FromQuery] string? person,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] personIds,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] personTypes,
            [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] studios,
            [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] artists,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] excludeArtistIds,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] artistIds,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumArtistIds,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] contributingArtistIds,
            [FromQuery, ModelBinder(typeof(PipeDelimitedArrayModelBinder))] string[] albums,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] albumIds,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] ids,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] VideoType[] videoTypes,
            [FromQuery] string? minOfficialRating,
            [FromQuery] bool? isLocked,
            [FromQuery] bool? isPlaceHolder,
            [FromQuery] bool? hasOfficialRating,
            [FromQuery] bool? collapseBoxSetItems,
            [FromQuery] int? minWidth,
            [FromQuery] int? minHeight,
            [FromQuery] int? maxWidth,
            [FromQuery] int? maxHeight,
            [FromQuery] bool? is3D,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] SeriesStatus[] seriesStatus,
            [FromQuery] string? nameStartsWithOrGreater,
            [FromQuery] string? nameStartsWith,
            [FromQuery] string? nameLessThan,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] studioIds,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] Guid[] genreIds,
            [FromQuery] bool enableTotalRecordCount = true,
            [FromQuery] bool? enableImages = true)
        {
            return GetItems(
                userId,
                maxOfficialRating,
                hasThemeSong,
                hasThemeVideo,
                hasSubtitles,
                hasSpecialFeature,
                hasTrailer,
                adjacentTo,
                parentIndexNumber,
                hasParentalRating,
                isHd,
                is4K,
                locationTypes,
                excludeLocationTypes,
                isMissing,
                isUnaired,
                minCommunityRating,
                minCriticRating,
                minPremiereDate,
                minDateLastSaved,
                minDateLastSavedForUser,
                maxPremiereDate,
                hasOverview,
                hasImdbId,
                hasTmdbId,
                hasTvdbId,
                isMovie,
                isSeries,
                isNews,
                isKids,
                isSports,
                excludeItemIds,
                startIndex,
                limit,
                recursive,
                searchTerm,
                sortOrder,
                parentId,
                fields,
                excludeItemTypes,
                includeItemTypes,
                filters,
                isFavorite,
                mediaTypes,
                imageTypes,
                sortBy,
                isPlayed,
                genres,
                officialRatings,
                tags,
                years,
                enableUserData,
                imageTypeLimit,
                enableImageTypes,
                person,
                personIds,
                personTypes,
                studios,
                artists,
                excludeArtistIds,
                artistIds,
                albumArtistIds,
                contributingArtistIds,
                albums,
                albumIds,
                ids,
                videoTypes,
                minOfficialRating,
                isLocked,
                isPlaceHolder,
                hasOfficialRating,
                collapseBoxSetItems,
                minWidth,
                minHeight,
                maxWidth,
                maxHeight,
                is3D,
                seriesStatus,
                nameStartsWithOrGreater,
                nameStartsWith,
                nameLessThan,
                studioIds,
                genreIds,
                enableTotalRecordCount,
                enableImages);
        }

        /// <summary>
        /// Gets items based on a query.
        /// </summary>
        /// <param name="userId">The user id.</param>
        /// <param name="startIndex">The start index.</param>
        /// <param name="limit">The item limit.</param>
        /// <param name="searchTerm">The search term.</param>
        /// <param name="parentId">Specify this to localize the search to a specific item or folder. Omit to use the root.</param>
        /// <param name="fields">Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimited. Options: Budget, Chapters, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines.</param>
        /// <param name="mediaTypes">Optional. Filter by MediaType. Allows multiple, comma delimited.</param>
        /// <param name="enableUserData">Optional. Include user data.</param>
        /// <param name="imageTypeLimit">Optional. The max number of images to return, per image type.</param>
        /// <param name="enableImageTypes">Optional. The image types to include in the output.</param>
        /// <param name="excludeItemTypes">Optional. If specified, results will be filtered based on item type. This allows multiple, comma delimited.</param>
        /// <param name="includeItemTypes">Optional. If specified, results will be filtered based on the item type. This allows multiple, comma delimited.</param>
        /// <param name="enableTotalRecordCount">Optional. Enable the total record count.</param>
        /// <param name="enableImages">Optional. Include image information in output.</param>
        /// <param name="excludeActiveSessions">Optional. Whether to exclude the currently active sessions.</param>
        /// <response code="200">Items returned.</response>
        /// <returns>A <see cref="QueryResult{BaseItemDto}"/> with the items that are resumable.</returns>
        [HttpGet("Users/{userId}/Items/Resume")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        public ActionResult<QueryResult<BaseItemDto>> GetResumeItems(
            [FromRoute, Required] Guid userId,
            [FromQuery] int? startIndex,
            [FromQuery] int? limit,
            [FromQuery] string? searchTerm,
            [FromQuery] Guid? parentId,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ItemFields[] fields,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] string[] mediaTypes,
            [FromQuery] bool? enableUserData,
            [FromQuery] int? imageTypeLimit,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] ImageType[] enableImageTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] excludeItemTypes,
            [FromQuery, ModelBinder(typeof(CommaDelimitedArrayModelBinder))] BaseItemKind[] includeItemTypes,
            [FromQuery] bool enableTotalRecordCount = true,
            [FromQuery] bool? enableImages = true,
            [FromQuery] bool excludeActiveSessions = false)
        {
            var user = _userManager.GetUserById(userId);
            var parentIdGuid = parentId ?? Guid.Empty;
            var dtoOptions = new DtoOptions { Fields = fields }
                .AddClientFields(Request)
                .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);

            var ancestorIds = Array.Empty<Guid>();

            var excludeFolderIds = user.GetPreferenceValues<Guid>(PreferenceKind.LatestItemExcludes);
            if (parentIdGuid.Equals(default) && excludeFolderIds.Length > 0)
            {
                ancestorIds = _libraryManager.GetUserRootFolder().GetChildren(user, true)
                    .Where(i => i is Folder)
                    .Where(i => !excludeFolderIds.Contains(i.Id))
                    .Select(i => i.Id)
                    .ToArray();
            }

            var excludeItemIds = Array.Empty<Guid>();
            if (excludeActiveSessions)
            {
                excludeItemIds = _sessionManager.Sessions
                    .Where(s => s.UserId.Equals(userId) && s.NowPlayingItem != null)
                    .Select(s => s.NowPlayingItem.Id)
                    .ToArray();
            }

            var itemsResult = _libraryManager.GetItemsResult(new InternalItemsQuery(user)
            {
                OrderBy = new[] { (ItemSortBy.DatePlayed, SortOrder.Descending) },
                IsResumable = true,
                StartIndex = startIndex,
                Limit = limit,
                ParentId = parentIdGuid,
                Recursive = true,
                DtoOptions = dtoOptions,
                MediaTypes = mediaTypes,
                IsVirtualItem = false,
                CollapseBoxSetItems = false,
                EnableTotalRecordCount = enableTotalRecordCount,
                AncestorIds = ancestorIds,
                IncludeItemTypes = includeItemTypes,
                ExcludeItemTypes = excludeItemTypes,
                SearchTerm = searchTerm,
                ExcludeItemIds = excludeItemIds
            });

            var returnItems = _dtoService.GetBaseItemDtos(itemsResult.Items, dtoOptions, user);

            return new QueryResult<BaseItemDto>(
                startIndex,
                itemsResult.TotalRecordCount,
                returnItems);
        }
    }
}