예제 #1
0
        /// <summary>
        /// Compares the specified x.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        /// <returns>System.Int32.</returns>
        public int Compare(BaseItem x, BaseItem y)
        {
            var levelX = string.IsNullOrEmpty(x.OfficialRating) ? 0 : _localization.GetRatingLevel(x.OfficialRating) ?? 0;
            var levelY = string.IsNullOrEmpty(y.OfficialRating) ? 0 : _localization.GetRatingLevel(y.OfficialRating) ?? 0;

            return(levelX.CompareTo(levelY));
        }
예제 #2
0
        protected override ItemUpdateType BeforeSave(BoxSet item)
        {
            var updateType = base.BeforeSave(item);

            if (!item.LockedFields.Contains(MetadataFields.OfficialRating))
            {
                var currentOfficialRating = item.OfficialRating;

                // Gather all possible ratings
                var ratings = item.RecursiveChildren
                              .Concat(item.GetLinkedChildren())
                              .Where(i => i is Movie || i is Series)
                              .Select(i => i.OfficialRating)
                              .Where(i => !string.IsNullOrEmpty(i))
                              .Distinct(StringComparer.OrdinalIgnoreCase)
                              .Select(i => new Tuple <string, int?>(i, _iLocalizationManager.GetRatingLevel(i)))
                              .OrderBy(i => i.Item2 ?? 1000)
                              .Select(i => i.Item1);

                item.OfficialRating = ratings.FirstOrDefault() ?? item.OfficialRating;

                if (!string.Equals(currentOfficialRating ?? string.Empty, item.OfficialRating ?? string.Empty,
                                   StringComparison.OrdinalIgnoreCase))
                {
                    updateType = updateType | ItemUpdateType.MetadataEdit;
                }
            }

            return(updateType);
        }
예제 #3
0
        /// <summary>
        /// Compares the specified x.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        /// <returns>System.Int32.</returns>
        public int Compare(BaseItem x, BaseItem y)
        {
            if (x == null)
            {
                throw new ArgumentNullException(nameof(x));
            }

            if (y == null)
            {
                throw new ArgumentNullException(nameof(y));
            }

            var levelX = string.IsNullOrEmpty(x.OfficialRating) ? 0 : _localization.GetRatingLevel(x.OfficialRating) ?? 0;
            var levelY = string.IsNullOrEmpty(y.OfficialRating) ? 0 : _localization.GetRatingLevel(y.OfficialRating) ?? 0;

            return(levelX.CompareTo(levelY));
        }
예제 #4
0
파일: ItemsService.cs 프로젝트: ta264/Emby
        private InternalItemsQuery GetItemsQuery(GetItems request, DtoOptions dtoOptions, User user)
        {
            var query = new InternalItemsQuery(user)
            {
                IsPlayed         = request.IsPlayed,
                MediaTypes       = request.GetMediaTypes(),
                IncludeItemTypes = request.GetIncludeItemTypes(),
                ExcludeItemTypes = request.GetExcludeItemTypes(),
                Recursive        = request.Recursive,
                OrderBy          = request.GetOrderBy(),

                IsFavorite              = request.IsFavorite,
                Limit                   = request.Limit,
                StartIndex              = request.StartIndex,
                IsMissing               = request.IsMissing,
                IsUnaired               = request.IsUnaired,
                CollapseBoxSetItems     = request.CollapseBoxSetItems,
                NameLessThan            = request.NameLessThan,
                NameStartsWith          = request.NameStartsWith,
                NameStartsWithOrGreater = request.NameStartsWithOrGreater,
                HasImdbId               = request.HasImdbId,
                IsPlaceHolder           = request.IsPlaceHolder,
                IsLocked                = request.IsLocked,
                IsInBoxSet              = request.IsInBoxSet,
                IsHD                   = request.IsHD,
                Is3D                   = request.Is3D,
                HasTvdbId              = request.HasTvdbId,
                HasTmdbId              = request.HasTmdbId,
                HasOverview            = request.HasOverview,
                HasOfficialRating      = request.HasOfficialRating,
                HasParentalRating      = request.HasParentalRating,
                HasSpecialFeature      = request.HasSpecialFeature,
                HasSubtitles           = request.HasSubtitles,
                HasThemeSong           = request.HasThemeSong,
                HasThemeVideo          = request.HasThemeVideo,
                HasTrailer             = request.HasTrailer,
                Tags                   = request.GetTags(),
                OfficialRatings        = request.GetOfficialRatings(),
                Genres                 = request.GetGenres(),
                ArtistIds              = request.GetArtistIds(),
                GenreIds               = request.GetGenreIds(),
                StudioIds              = request.GetStudioIds(),
                Person                 = request.Person,
                PersonIds              = request.GetPersonIds(),
                PersonTypes            = request.GetPersonTypes(),
                Years                  = request.GetYears(),
                ImageTypes             = request.GetImageTypes(),
                VideoTypes             = request.GetVideoTypes(),
                AdjacentTo             = request.AdjacentTo,
                ItemIds                = request.GetItemIds(),
                MinPlayers             = request.MinPlayers,
                MaxPlayers             = request.MaxPlayers,
                MinCommunityRating     = request.MinCommunityRating,
                MinCriticRating        = request.MinCriticRating,
                ParentId               = string.IsNullOrWhiteSpace(request.ParentId) ? (Guid?)null : new Guid(request.ParentId),
                ParentIndexNumber      = request.ParentIndexNumber,
                AiredDuringSeason      = request.AiredDuringSeason,
                EnableTotalRecordCount = request.EnableTotalRecordCount,
                ExcludeItemIds         = request.GetExcludeItemIds(),
                DtoOptions             = dtoOptions
            };

            if (!string.IsNullOrWhiteSpace(request.Ids))
            {
                query.CollapseBoxSetItems = false;
            }

            foreach (var filter in request.GetFilters())
            {
                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;
                }
            }

            if (!string.IsNullOrEmpty(request.MinDateLastSaved))
            {
                query.MinDateLastSaved = DateTime.Parse(request.MinDateLastSaved, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
            }

            if (!string.IsNullOrEmpty(request.MinDateLastSavedForUser))
            {
                query.MinDateLastSavedForUser = DateTime.Parse(request.MinDateLastSavedForUser, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
            }

            if (!string.IsNullOrEmpty(request.MinPremiereDate))
            {
                query.MinPremiereDate = DateTime.Parse(request.MinPremiereDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
            }

            if (!string.IsNullOrEmpty(request.MaxPremiereDate))
            {
                query.MaxPremiereDate = DateTime.Parse(request.MaxPremiereDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
            }

            // Filter by Series Status
            if (!string.IsNullOrEmpty(request.SeriesStatus))
            {
                query.SeriesStatuses = request.SeriesStatus.Split(',').Select(d => (SeriesStatus)Enum.Parse(typeof(SeriesStatus), d, true)).ToArray();
            }

            // ExcludeLocationTypes
            if (!string.IsNullOrEmpty(request.ExcludeLocationTypes))
            {
                var excludeLocationTypes = request.ExcludeLocationTypes.Split(',').Select(d => (LocationType)Enum.Parse(typeof(LocationType), d, true)).ToArray();
                if (excludeLocationTypes.Contains(LocationType.Virtual))
                {
                    query.IsVirtualItem = false;
                }
            }

            if (!string.IsNullOrEmpty(request.LocationTypes))
            {
                var requestedLocationTypes =
                    request.LocationTypes.Split(',');

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

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

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

            // Artists
            if (!string.IsNullOrEmpty(request.Artists))
            {
                query.ArtistIds = request.Artists.Split('|').Select(i =>
                {
                    try
                    {
                        return(_libraryManager.GetArtist(i, new DtoOptions(false)));
                    }
                    catch
                    {
                        return(null);
                    }
                }).Where(i => i != null).Select(i => i.Id.ToString("N")).ToArray();
            }

            // ExcludeArtistIds
            if (!string.IsNullOrWhiteSpace(request.ExcludeArtistIds))
            {
                query.ExcludeArtistIds = request.ExcludeArtistIds.Split('|');
            }

            if (!string.IsNullOrWhiteSpace(request.AlbumIds))
            {
                query.AlbumIds = request.AlbumIds.Split('|');
            }

            // Albums
            if (!string.IsNullOrEmpty(request.Albums))
            {
                query.AlbumIds = request.Albums.Split('|').SelectMany(i =>
                {
                    return(_libraryManager.GetItemIds(new InternalItemsQuery
                    {
                        IncludeItemTypes = new[] { typeof(MusicAlbum).Name },
                        Name = i,
                        Limit = 1
                    }).Select(albumId => albumId.ToString("N")));
                }).ToArray();
            }

            // Studios
            if (!string.IsNullOrEmpty(request.Studios))
            {
                query.StudioIds = request.Studios.Split('|').Select(i =>
                {
                    try
                    {
                        return(_libraryManager.GetStudio(i));
                    }
                    catch
                    {
                        return(null);
                    }
                }).Where(i => i != null).Select(i => i.Id.ToString("N")).ToArray();
            }

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

            return(query);
        }
예제 #5
0
파일: ReportsService.cs 프로젝트: w3fs/Emby
        private bool ApplyAdditionalFilters(BaseReportRequest request, BaseItem i, User user, ILibraryManager libraryManager)
        {
            // Artists
            if (!string.IsNullOrEmpty(request.ArtistIds))
            {
                var artistIds = request.ArtistIds.Split(new[] { '|', ',' });

                var audio = i as IHasArtist;

                if (!(audio != null && artistIds.Any(id =>
                {
                    var artistItem = libraryManager.GetItemById(id);
                    return(artistItem != null && audio.HasAnyArtist(artistItem.Name));
                })))
                {
                    return(false);
                }
            }

            // Artists
            if (!string.IsNullOrEmpty(request.Artists))
            {
                var artists = request.Artists.Split('|');

                var audio = i as IHasArtist;

                if (!(audio != null && artists.Any(audio.HasAnyArtist)))
                {
                    return(false);
                }
            }

            // Albums
            if (!string.IsNullOrEmpty(request.Albums))
            {
                var albums = request.Albums.Split('|');

                var audio = i as Audio;

                if (audio != null)
                {
                    if (!albums.Any(a => string.Equals(a, audio.Album, StringComparison.OrdinalIgnoreCase)))
                    {
                        return(false);
                    }
                }

                var album = i as MusicAlbum;

                if (album != null)
                {
                    if (!albums.Any(a => string.Equals(a, album.Name, StringComparison.OrdinalIgnoreCase)))
                    {
                        return(false);
                    }
                }

                var musicVideo = i as MusicVideo;

                if (musicVideo != null)
                {
                    if (!albums.Any(a => string.Equals(a, musicVideo.Album, StringComparison.OrdinalIgnoreCase)))
                    {
                        return(false);
                    }
                }

                return(false);
            }

            // Min index number
            if (request.MinIndexNumber.HasValue)
            {
                if (!(i.IndexNumber.HasValue && i.IndexNumber.Value >= request.MinIndexNumber.Value))
                {
                    return(false);
                }
            }

            // Min official rating
            if (!string.IsNullOrEmpty(request.MinOfficialRating))
            {
                var level = _localization.GetRatingLevel(request.MinOfficialRating);

                if (level.HasValue)
                {
                    var rating = i.CustomRating;

                    if (string.IsNullOrEmpty(rating))
                    {
                        rating = i.OfficialRating;
                    }

                    if (!string.IsNullOrEmpty(rating))
                    {
                        var itemLevel = _localization.GetRatingLevel(rating);

                        if (!(!itemLevel.HasValue || itemLevel.Value >= level.Value))
                        {
                            return(false);
                        }
                    }
                }
            }

            // Max official rating
            if (!string.IsNullOrEmpty(request.MaxOfficialRating))
            {
                var level = _localization.GetRatingLevel(request.MaxOfficialRating);

                if (level.HasValue)
                {
                    var rating = i.CustomRating;

                    if (string.IsNullOrEmpty(rating))
                    {
                        rating = i.OfficialRating;
                    }

                    if (!string.IsNullOrEmpty(rating))
                    {
                        var itemLevel = _localization.GetRatingLevel(rating);

                        if (!(!itemLevel.HasValue || itemLevel.Value <= level.Value))
                        {
                            return(false);
                        }
                    }
                }
            }

            // LocationTypes
            if (!string.IsNullOrEmpty(request.LocationTypes))
            {
                var vals = request.LocationTypes.Split(',');
                if (!vals.Contains(i.LocationType.ToString(), StringComparer.OrdinalIgnoreCase))
                {
                    return(false);
                }
            }

            // ExcludeLocationTypes
            if (!string.IsNullOrEmpty(request.ExcludeLocationTypes))
            {
                var vals = request.ExcludeLocationTypes.Split(',');
                if (vals.Contains(i.LocationType.ToString(), StringComparer.OrdinalIgnoreCase))
                {
                    return(false);
                }
            }

            if (!string.IsNullOrEmpty(request.AlbumArtistStartsWithOrGreater))
            {
                var ok = new[] { i }.OfType <IHasAlbumArtist>()
                .Any(p => string.Compare(request.AlbumArtistStartsWithOrGreater, p.AlbumArtists.FirstOrDefault(), StringComparison.CurrentCultureIgnoreCase) < 1);

                if (!ok)
                {
                    return(false);
                }
            }

            // Filter by Series Status
            if (!string.IsNullOrEmpty(request.SeriesStatus))
            {
                var vals = request.SeriesStatus.Split(',');

                var ok = new[] { i }.OfType <Series>().Any(p => p.Status.HasValue && vals.Contains(p.Status.Value.ToString(), StringComparer.OrdinalIgnoreCase));

                if (!ok)
                {
                    return(false);
                }
            }

            // Filter by Series AirDays
            if (!string.IsNullOrEmpty(request.AirDays))
            {
                var days = request.AirDays.Split(',').Select(d => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), d, true));

                var ok = new[] { i }.OfType <Series>().Any(p => p.AirDays != null && days.Any(d => p.AirDays.Contains(d)));

                if (!ok)
                {
                    return(false);
                }
            }

            if (request.ParentIndexNumber.HasValue)
            {
                var filterValue = request.ParentIndexNumber.Value;

                var episode = i as Episode;

                if (episode != null)
                {
                    if (episode.ParentIndexNumber.HasValue && episode.ParentIndexNumber.Value != filterValue)
                    {
                        return(false);
                    }
                }

                var song = i as Audio;

                if (song != null)
                {
                    if (song.ParentIndexNumber.HasValue && song.ParentIndexNumber.Value != filterValue)
                    {
                        return(false);
                    }
                }
            }

            if (request.AiredDuringSeason.HasValue)
            {
                var episode = i as Episode;

                if (episode == null)
                {
                    return(false);
                }

                if (!Series.FilterEpisodesBySeason(new[] { episode }, request.AiredDuringSeason.Value, true).Any())
                {
                    return(false);
                }
            }

            if (!string.IsNullOrEmpty(request.MinPremiereDate))
            {
                var date = DateTime.Parse(request.MinPremiereDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();

                if (!(i.PremiereDate.HasValue && i.PremiereDate.Value >= date))
                {
                    return(false);
                }
            }

            if (!string.IsNullOrEmpty(request.MaxPremiereDate))
            {
                var date = DateTime.Parse(request.MaxPremiereDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();

                if (!(i.PremiereDate.HasValue && i.PremiereDate.Value <= date))
                {
                    return(false);
                }
            }

            return(true);
        }
예제 #6
0
        private InternalItemsQuery GetItemsQuery(GetItems request, User user)
        {
            var query = new InternalItemsQuery(user)
            {
                IsPlayed         = request.IsPlayed,
                MediaTypes       = request.GetMediaTypes(),
                IncludeItemTypes = request.GetIncludeItemTypes(),
                ExcludeItemTypes = request.GetExcludeItemTypes(),
                Recursive        = request.Recursive,
                SortBy           = request.GetOrderBy(),
                SortOrder        = request.SortOrder ?? SortOrder.Ascending,

                IsFavorite              = request.IsFavorite,
                Limit                   = request.Limit,
                StartIndex              = request.StartIndex,
                IsMissing               = request.IsMissing,
                IsVirtualUnaired        = request.IsVirtualUnaired,
                IsUnaired               = request.IsUnaired,
                CollapseBoxSetItems     = request.CollapseBoxSetItems,
                NameLessThan            = request.NameLessThan,
                NameStartsWith          = request.NameStartsWith,
                NameStartsWithOrGreater = request.NameStartsWithOrGreater,
                HasImdbId               = request.HasImdbId,
                IsYearMismatched        = request.IsYearMismatched,
                IsPlaceHolder           = request.IsPlaceHolder,
                IsLocked                = request.IsLocked,
                IsInBoxSet              = request.IsInBoxSet,
                IsHD                           = request.IsHD,
                Is3D                           = request.Is3D,
                HasTvdbId                      = request.HasTvdbId,
                HasTmdbId                      = request.HasTmdbId,
                HasOverview                    = request.HasOverview,
                HasOfficialRating              = request.HasOfficialRating,
                HasParentalRating              = request.HasParentalRating,
                HasSpecialFeature              = request.HasSpecialFeature,
                HasSubtitles                   = request.HasSubtitles,
                HasThemeSong                   = request.HasThemeSong,
                HasThemeVideo                  = request.HasThemeVideo,
                HasTrailer                     = request.HasTrailer,
                Tags                           = request.GetTags(),
                OfficialRatings                = request.GetOfficialRatings(),
                Genres                         = request.GetGenres(),
                GenreIds                       = request.GetGenreIds(),
                Studios                        = request.GetStudios(),
                StudioIds                      = request.GetStudioIds(),
                Person                         = request.Person,
                PersonIds                      = request.GetPersonIds(),
                PersonTypes                    = request.GetPersonTypes(),
                Years                          = request.GetYears(),
                ImageTypes                     = request.GetImageTypes().ToArray(),
                VideoTypes                     = request.GetVideoTypes().ToArray(),
                AdjacentTo                     = request.AdjacentTo,
                ItemIds                        = request.GetItemIds(),
                MinPlayers                     = request.MinPlayers,
                MaxPlayers                     = request.MaxPlayers,
                MinCommunityRating             = request.MinCommunityRating,
                MinCriticRating                = request.MinCriticRating,
                ParentId                       = string.IsNullOrWhiteSpace(request.ParentId) ? (Guid?)null : new Guid(request.ParentId),
                ParentIndexNumber              = request.ParentIndexNumber,
                AiredDuringSeason              = request.AiredDuringSeason,
                AlbumArtistStartsWithOrGreater = request.AlbumArtistStartsWithOrGreater,
                EnableTotalRecordCount         = request.EnableTotalRecordCount
            };

            if (!string.IsNullOrWhiteSpace(request.Ids))
            {
                query.CollapseBoxSetItems = false;
            }

            foreach (var filter in request.GetFilters())
            {
                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.IsRecentlyAdded:
                    break;

                case ItemFilter.IsResumable:
                    query.IsResumable = true;
                    break;

                case ItemFilter.IsUnplayed:
                    query.IsPlayed = false;
                    break;

                case ItemFilter.Likes:
                    query.IsLiked = true;
                    break;
                }
            }

            if (!string.IsNullOrEmpty(request.MinPremiereDate))
            {
                query.MinPremiereDate = DateTime.Parse(request.MinPremiereDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
            }

            if (!string.IsNullOrEmpty(request.MaxPremiereDate))
            {
                query.MaxPremiereDate = DateTime.Parse(request.MaxPremiereDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
            }

            // Filter by Series Status
            if (!string.IsNullOrEmpty(request.SeriesStatus))
            {
                query.SeriesStatuses = request.SeriesStatus.Split(',').Select(d => (SeriesStatus)Enum.Parse(typeof(SeriesStatus), d, true)).ToArray();
            }

            // Filter by Series AirDays
            if (!string.IsNullOrEmpty(request.AirDays))
            {
                query.AirDays = request.AirDays.Split(',').Select(d => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), d, true)).ToArray();
            }

            // ExcludeLocationTypes
            if (!string.IsNullOrEmpty(request.ExcludeLocationTypes))
            {
                query.ExcludeLocationTypes = request.ExcludeLocationTypes.Split(',').Select(d => (LocationType)Enum.Parse(typeof(LocationType), d, true)).ToArray();
            }

            if (!string.IsNullOrEmpty(request.LocationTypes))
            {
                query.LocationTypes = request.LocationTypes.Split(',').Select(d => (LocationType)Enum.Parse(typeof(LocationType), d, true)).ToArray();
            }

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

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

            // Artists
            if (!string.IsNullOrEmpty(request.ArtistIds))
            {
                var artistIds = request.ArtistIds.Split(new[] { '|', ',' });

                var artistItems = artistIds.Select(_libraryManager.GetItemById).Where(i => i != null).ToList();
                query.ArtistNames = artistItems.Select(i => i.Name).ToArray();
            }

            // Artists
            if (!string.IsNullOrEmpty(request.Artists))
            {
                query.ArtistNames = request.Artists.Split('|');
            }

            // Albums
            if (!string.IsNullOrEmpty(request.Albums))
            {
                query.AlbumNames = request.Albums.Split('|');
            }

            return(query);
        }
예제 #7
0
        /// <summary>
        /// Applies the additional filters.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="items">The items.</param>
        /// <returns>IEnumerable{BaseItem}.</returns>
        private IEnumerable <BaseItem> ApplyAdditionalFilters(GetItems request, IEnumerable <BaseItem> items, User user)
        {
            // Artists
            if (!string.IsNullOrEmpty(request.Artists))
            {
                var artists = request.Artists.Split('|');

                items = items.Where(i =>
                {
                    var audio = i as Audio;

                    if (audio != null)
                    {
                        return(artists.Any(audio.HasArtist));
                    }

                    var album = i as MusicAlbum;

                    if (album != null)
                    {
                        return(artists.Any(album.HasArtist));
                    }

                    var musicVideo = i as MusicVideo;

                    if (musicVideo != null)
                    {
                        return(artists.Any(musicVideo.HasArtist));
                    }

                    return(false);
                });
            }

            if (!string.IsNullOrEmpty(request.AdjacentTo))
            {
                var item = DtoBuilder.GetItemByClientId(request.AdjacentTo, _userManager, _libraryManager);

                var allSiblings = item.Parent.GetChildren(user, true).OrderBy(i => i.SortName).ToList();

                var index = allSiblings.IndexOf(item);

                var previousId = Guid.Empty;
                var nextId     = Guid.Empty;

                if (index > 0)
                {
                    previousId = allSiblings[index - 1].Id;
                }

                if (index < allSiblings.Count - 1)
                {
                    nextId = allSiblings[index + 1].Id;
                }

                items = items.Where(i => i.Id == previousId || i.Id == nextId);
            }

            // Min official rating
            if (!string.IsNullOrEmpty(request.MinOfficialRating))
            {
                var level = _localization.GetRatingLevel(request.MinOfficialRating);

                if (level.HasValue)
                {
                    items = items.Where(i =>
                    {
                        var rating = i.CustomRating ?? i.OfficialRating;

                        if (string.IsNullOrEmpty(rating))
                        {
                            return(true);
                        }

                        var itemLevel = _localization.GetRatingLevel(rating);

                        return(!itemLevel.HasValue || itemLevel.Value >= level.Value);
                    });
                }
            }

            // Max official rating
            if (!string.IsNullOrEmpty(request.MaxOfficialRating))
            {
                var level = _localization.GetRatingLevel(request.MinOfficialRating);

                if (level.HasValue)
                {
                    items = items.Where(i =>
                    {
                        var rating = i.CustomRating ?? i.OfficialRating;

                        if (string.IsNullOrEmpty(rating))
                        {
                            return(true);
                        }

                        var itemLevel = _localization.GetRatingLevel(rating);

                        return(!itemLevel.HasValue || itemLevel.Value <= level.Value);
                    });
                }
            }

            // Exclude item types
            if (!string.IsNullOrEmpty(request.ExcludeItemTypes))
            {
                var vals = request.ExcludeItemTypes.Split(',');
                items = items.Where(f => !vals.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase));
            }

            // Include item types
            if (!string.IsNullOrEmpty(request.IncludeItemTypes))
            {
                var vals = request.IncludeItemTypes.Split(',');
                items = items.Where(f => vals.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase));
            }

            if (!string.IsNullOrEmpty(request.NameStartsWithOrGreater))
            {
                items = items.Where(i => string.Compare(request.NameStartsWithOrGreater, i.SortName, StringComparison.CurrentCultureIgnoreCase) < 1);
            }

            // Filter by Series Status
            if (!string.IsNullOrEmpty(request.SeriesStatus))
            {
                var vals = request.SeriesStatus.Split(',');

                items = items.OfType <Series>().Where(i => i.Status.HasValue && vals.Contains(i.Status.Value.ToString(), StringComparer.OrdinalIgnoreCase));
            }

            // Filter by Series AirDays
            if (!string.IsNullOrEmpty(request.AirDays))
            {
                var days = request.AirDays.Split(',').Select(d => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), d, true));

                items = items.OfType <Series>().Where(i => i.AirDays != null && days.Any(d => i.AirDays.Contains(d)));
            }

            // Filter by Video3DFormat
            if (request.Is3D.HasValue)
            {
                items = items.OfType <Video>().Where(i => request.Is3D.Value == i.Video3DFormat.HasValue);
            }

            // Filter by VideoType
            if (!string.IsNullOrEmpty(request.VideoTypes))
            {
                var types = request.VideoTypes.Split(',');

                items = items.OfType <Video>().Where(i => types.Contains(i.VideoType.ToString(), StringComparer.OrdinalIgnoreCase));
            }

            if (!string.IsNullOrEmpty(request.MediaTypes))
            {
                var types = request.MediaTypes.Split(',');

                items = items.Where(i => !string.IsNullOrEmpty(i.MediaType) && types.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase));
            }

            var imageTypes = GetImageTypes(request).ToArray();

            if (imageTypes.Length > 0)
            {
                items = items.Where(item => imageTypes.Any(imageType => HasImage(item, imageType)));
            }

            var genres = request.Genres;

            // Apply genre filter
            if (!string.IsNullOrEmpty(genres))
            {
                var vals = genres.Split(',');
                items = items.Where(f => f.Genres != null && vals.Any(v => f.Genres.Contains(v, StringComparer.OrdinalIgnoreCase)));
            }

            var studios = request.Studios;

            // Apply studio filter
            if (!string.IsNullOrEmpty(studios))
            {
                var vals = studios.Split(',');
                items = items.Where(f => f.Studios != null && vals.Any(v => f.Studios.Contains(v, StringComparer.OrdinalIgnoreCase)));
            }

            var years = request.Years;

            // Apply year filter
            if (!string.IsNullOrEmpty(years))
            {
                var vals = years.Split(',').Select(int.Parse);
                items = items.Where(f => f.ProductionYear.HasValue && vals.Contains(f.ProductionYear.Value));
            }

            var personName = request.Person;

            // Apply person filter
            if (!string.IsNullOrEmpty(personName))
            {
                var personTypes = request.PersonTypes;

                if (string.IsNullOrEmpty(personTypes))
                {
                    items = items.Where(item => item.People != null && item.People.Any(p => string.Equals(p.Name, personName, StringComparison.OrdinalIgnoreCase)));
                }
                else
                {
                    var types = personTypes.Split(',');

                    items = items.Where(item =>
                                        item.People != null &&
                                        item.People.Any(p =>
                                                        p.Name.Equals(personName, StringComparison.OrdinalIgnoreCase) && types.Contains(p.Type, StringComparer.OrdinalIgnoreCase)));
                }
            }

            if (request.HasTrailer.HasValue)
            {
                items = items.Where(i => request.HasTrailer.Value ? i.LocalTrailerIds.Count > 0 : i.LocalTrailerIds.Count == 0);
            }

            if (request.HasThemeSong.HasValue)
            {
                items = items.Where(i => request.HasThemeSong.Value ? i.ThemeSongIds.Count > 0 : i.ThemeSongIds.Count == 0);
            }

            if (request.HasThemeVideo.HasValue)
            {
                items = items.Where(i => request.HasThemeVideo.Value ? i.ThemeVideoIds.Count > 0 : i.ThemeVideoIds.Count == 0);
            }

            if (request.HasSpecialFeature.HasValue)
            {
                items = items.OfType <Movie>().Where(i => request.HasSpecialFeature.Value ? i.SpecialFeatureIds.Count > 0 : i.SpecialFeatureIds.Count == 0);
            }

            if (request.HasSubtitles.HasValue)
            {
                items = items.OfType <Video>().Where(i =>
                {
                    if (request.HasSubtitles.Value)
                    {
                        return(i.MediaStreams != null && i.MediaStreams.Any(m => m.Type == MediaStreamType.Subtitle));
                    }

                    return(i.MediaStreams == null || i.MediaStreams.All(m => m.Type != MediaStreamType.Subtitle));
                });
            }

            return(items);
        }
예제 #8
0
        private InternalItemsQuery GetItemsQuery(BaseReportRequest request, User user)
        {
            var query = new InternalItemsQuery(user)
            {
                IsPlayed                = request.IsPlayed,
                MediaTypes              = request.GetMediaTypes(),
                IncludeItemTypes        = request.GetIncludeItemTypes(),
                ExcludeItemTypes        = request.GetExcludeItemTypes(),
                Recursive               = request.Recursive,
                OrderBy                 = request.GetOrderBy(),
                Limit                   = request.Limit,
                StartIndex              = request.StartIndex,
                IsMissing               = request.IsMissing,
                IsUnaired               = request.IsUnaired,
                CollapseBoxSetItems     = request.CollapseBoxSetItems,
                NameLessThan            = request.NameLessThan,
                NameStartsWith          = request.NameStartsWith,
                NameStartsWithOrGreater = request.NameStartsWithOrGreater,
                HasImdbId               = request.HasImdbId,
                IsPlaceHolder           = request.IsPlaceHolder,
                IsLocked                = request.IsLocked,
                IsHD                   = request.IsHD,
                Is3D                   = request.Is3D,
                HasTvdbId              = request.HasTvdbId,
                HasTmdbId              = request.HasTmdbId,
                HasOverview            = request.HasOverview,
                HasOfficialRating      = request.HasOfficialRating,
                HasParentalRating      = request.HasParentalRating,
                HasSpecialFeature      = request.HasSpecialFeature,
                HasSubtitles           = request.HasSubtitles,
                HasThemeSong           = request.HasThemeSong,
                HasThemeVideo          = request.HasThemeVideo,
                HasTrailer             = request.HasTrailer,
                Tags                   = request.GetTags(),
                OfficialRatings        = request.GetOfficialRatings(),
                Genres                 = request.GetGenres(),
                GenreIds               = request.GetGenreIds(),
                StudioIds              = request.GetStudioIds(),
                Person                 = request.Person,
                PersonIds              = request.GetPersonIds(),
                PersonTypes            = request.GetPersonTypes(),
                Years                  = request.GetYears(),
                ImageTypes             = request.GetImageTypes().ToArray(),
                VideoTypes             = request.GetVideoTypes().ToArray(),
                AdjacentTo             = request.AdjacentTo,
                ItemIds                = request.GetItemIds(),
                MinPlayers             = request.MinPlayers,
                MaxPlayers             = request.MaxPlayers,
                MinCommunityRating     = request.MinCommunityRating,
                MinCriticRating        = request.MinCriticRating,
                ParentId               = string.IsNullOrWhiteSpace(request.ParentId) ? Guid.Empty : new Guid(request.ParentId),
                ParentIndexNumber      = request.ParentIndexNumber,
                EnableTotalRecordCount = request.EnableTotalRecordCount
            };

            if (request.Limit == -1)
            {
                query.Limit = null;
            }

            if (!string.IsNullOrWhiteSpace(request.Ids))
            {
                query.CollapseBoxSetItems = false;
            }

            query.IsFavorite = null;
            if (request.IsFavorite == true)
            {
                query.IsFavorite = true;
            }
            else if (request.IsNotFavorite == true)
            {
                query.IsFavorite = false;
            }

            foreach (var filter in request.GetFilters())
            {
                switch (filter)
                {
                case ItemFilter.Dislikes:
                    query.IsLiked = false;
                    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;
                }
            }

            if (!string.IsNullOrEmpty(request.MinPremiereDate))
            {
                query.MinPremiereDate = DateTime.Parse(request.MinPremiereDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
            }

            if (!string.IsNullOrEmpty(request.MaxPremiereDate))
            {
                query.MaxPremiereDate = DateTime.Parse(request.MaxPremiereDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
            }

            // Filter by Series Status
            if (!string.IsNullOrEmpty(request.SeriesStatus))
            {
                query.SeriesStatuses = request.SeriesStatus.Split(',').Select(d => (SeriesStatus)Enum.Parse(typeof(SeriesStatus), d, true)).ToArray();
            }

            // ExcludeLocationTypes
            if (!string.IsNullOrEmpty(request.ExcludeLocationTypes))
            {
                var excludeLocationTypes = request.ExcludeLocationTypes.Split(',').Select(d => (LocationType)Enum.Parse(typeof(LocationType), d, true)).ToArray();
                if (excludeLocationTypes.Contains(LocationType.Virtual))
                {
                    query.IsVirtualItem = false;
                }
            }

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

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

            query.CollapseBoxSetItems = false;

            return(query);
        }
예제 #9
0
        private InternalItemsQuery GetItemsQuery(BaseReportRequest request, DtoOptions dtoOptions, User user)
        {
            var query = new InternalItemsQuery(user)
            {
                IsPlayed         = request.IsPlayed,
                MediaTypes       = request.GetMediaTypes(),
                IncludeItemTypes = request.GetIncludeItemTypes(),
                ExcludeItemTypes = request.GetExcludeItemTypes(),
                Recursive        = request.Recursive,
                OrderBy          = request.GetOrderBy(),

                IsFavorite              = request.IsFavorite,
                StartIndex              = request.StartIndex,
                IsVirtualItem           = request.IsMissing,
                IsUnaired               = request.IsUnaired,
                NameLessThan            = request.NameLessThan,
                NameStartsWith          = request.NameStartsWith,
                NameStartsWithOrGreater = request.NameStartsWithOrGreater,
                IsLocked               = request.IsLocked,
                MinWidth               = request.MinWidth,
                MinHeight              = request.MinHeight,
                MaxWidth               = request.MaxWidth,
                MaxHeight              = request.MaxHeight,
                Is3D                   = request.Is3D,
                HasOverview            = request.HasOverview,
                HasOfficialRating      = request.HasOfficialRating,
                HasParentalRating      = request.HasParentalRating,
                HasExtra               = request.HasSpecialFeature,
                HasSubtitles           = request.HasSubtitles,
                HasThemeSong           = request.HasThemeSong,
                HasThemeVideo          = request.HasThemeVideo,
                HasTrailer             = request.HasTrailer,
                IsHD                   = request.IsHD,
                Is4K                   = request.Is4K,
                Tags                   = request.GetTags(),
                OfficialRatings        = request.GetOfficialRatings(),
                Genres                 = request.GetGenres(),
                ArtistIds              = ParseIds(request.ArtistIds, _libraryManager),
                AlbumArtistIds         = ParseIds(request.AlbumArtistIds, _libraryManager),
                ContributingArtistIds  = ParseIds(request.ContributingArtistIds, _libraryManager),
                GenreIds               = ParseIds(request.GenreIds, _libraryManager),
                StudioIds              = ParseIds(request.StudioIds, _libraryManager),
                PersonIds              = ParseIds(request.PersonIds, _libraryManager),
                PersonTypes            = request.GetPersonTypes(),
                Years                  = request.GetYears(),
                ImageTypes             = request.GetImageTypes(),
                Containers             = request.GetContainers(),
                AdjacentTo             = _libraryManager.GetInternalId(request.AdjacentTo),
                ItemIds                = ParseIds(request.Ids, _libraryManager),
                MinPlayers             = request.MinPlayers,
                MaxPlayers             = request.MaxPlayers,
                MinCommunityRating     = request.MinCommunityRating,
                MinCriticRating        = request.MinCriticRating,
                ParentIds              = ParseIds(request.ParentId, _libraryManager),
                ParentIndexNumber      = request.ParentIndexNumber,
                EnableTotalRecordCount = request.EnableTotalRecordCount,
                ExcludeItemIds         = ParseIds(request.ExcludeItemIds, _libraryManager),
                DtoOptions             = dtoOptions,
                SearchTerm             = request.SearchTerm,
                IsMovie                = request.IsMovie,
                IsSports               = request.IsSports,
                IsKids                 = request.IsKids,
                IsNews                 = request.IsNews,
                IsSeries               = request.IsSeries
            };

            var hasAnyProviderId     = new List <string>();
            var missingAnyProviderId = new List <string>();

            if (request.HasImdbId.HasValue)
            {
                if (request.HasImdbId.Value)
                {
                    hasAnyProviderId.Add(MetadataProviders.Imdb.ToString());
                }
                else
                {
                    missingAnyProviderId.Add(MetadataProviders.Imdb.ToString());
                }
            }

            if (request.HasTvdbId.HasValue)
            {
                if (request.HasTvdbId.Value)
                {
                    hasAnyProviderId.Add(MetadataProviders.Tvdb.ToString());
                }
                else
                {
                    missingAnyProviderId.Add(MetadataProviders.Tvdb.ToString());
                }
            }

            if (request.HasTmdbId.HasValue)
            {
                if (request.HasTmdbId.Value)
                {
                    hasAnyProviderId.Add(MetadataProviders.Tmdb.ToString());
                }
                else
                {
                    missingAnyProviderId.Add(MetadataProviders.Tmdb.ToString());
                }
            }

            query.HasAnyProviderId     = hasAnyProviderId.ToArray();
            query.MissingAnyProviderId = missingAnyProviderId.ToArray();

            foreach (var filter in request.GetFilters())
            {
                switch (filter)
                {
                case ItemFilter.Dislikes:
                    query.IsLiked = false;
                    break;

                case ItemFilter.IsFavorite:
                    query.IsFavorite = true;
                    break;

                case ItemFilter.IsFavoriteOrLikes:
                    query.IsFavorite = 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;
                }
            }

            if (!string.IsNullOrEmpty(request.MinDateLastSaved))
            {
                query.MinDateLastSaved = DateTime.Parse(request.MinDateLastSaved, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
            }

            if (!string.IsNullOrEmpty(request.MinDateLastSavedForUser))
            {
                query.MinDateLastSavedForUser = DateTime.Parse(request.MinDateLastSavedForUser, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
            }

            if (!string.IsNullOrEmpty(request.MinPremiereDate))
            {
                query.MinPremiereDate = DateTime.Parse(request.MinPremiereDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
            }

            if (!string.IsNullOrEmpty(request.MaxPremiereDate))
            {
                query.MaxPremiereDate = DateTime.Parse(request.MaxPremiereDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
            }

            // Filter by Series Status
            if (!string.IsNullOrEmpty(request.SeriesStatus))
            {
                query.SeriesStatuses = request.SeriesStatus.Split(',').Select(d => (SeriesStatus)Enum.Parse(typeof(SeriesStatus), d, true)).ToArray();
            }

            // ExcludeLocationTypes
            if (!string.IsNullOrEmpty(request.ExcludeLocationTypes))
            {
                var excludeLocationTypes = request.ExcludeLocationTypes.Split(',').Select(d => (LocationType)Enum.Parse(typeof(LocationType), d, true)).ToArray();
                if (excludeLocationTypes.Contains(LocationType.Virtual))
                {
                    query.IsVirtualItem = false;
                }
            }

            if (!string.IsNullOrEmpty(request.LocationTypes))
            {
                var requestedLocationTypes =
                    request.LocationTypes.Split(',');

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

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

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

            // ExcludeArtistIds
            if (!string.IsNullOrWhiteSpace(request.ExcludeArtistIds))
            {
                query.ExcludeArtistIds = ParseIds(request.ExcludeArtistIds, _libraryManager);
            }

            if (!string.IsNullOrWhiteSpace(request.AlbumIds))
            {
                query.AlbumIds = ParseIds(request.AlbumIds, _libraryManager);
            }

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

            if (request.Limit > -1 && request.Limit < int.MaxValue)
            {
                query.Limit = request.Limit;
            }

            return(query);
        }
예제 #10
0
        public ActionResult <QueryResult <BaseItemDto> > GetItems(
            [FromRoute, Required] Guid?uId,
            [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] string?locationTypes,
            [FromQuery] string?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] string?excludeItemIds,
            [FromQuery] int?startIndex,
            [FromQuery] int?limit,
            [FromQuery] bool?recursive,
            [FromQuery] string?searchTerm,
            [FromQuery] string?sortOrder,
            [FromQuery] string?parentId,
            [FromQuery] string?fields,
            [FromQuery] string?excludeItemTypes,
            [FromQuery] string?includeItemTypes,
            [FromQuery] string?filters,
            [FromQuery] bool?isFavorite,
            [FromQuery] string?mediaTypes,
            [FromQuery] string?imageTypes,
            [FromQuery] string?sortBy,
            [FromQuery] bool?isPlayed,
            [FromQuery] string?genres,
            [FromQuery] string?officialRatings,
            [FromQuery] string?tags,
            [FromQuery] string?years,
            [FromQuery] bool?enableUserData,
            [FromQuery] int?imageTypeLimit,
            [FromQuery] string?enableImageTypes,
            [FromQuery] string?person,
            [FromQuery] string?personIds,
            [FromQuery] string?personTypes,
            [FromQuery] string?studios,
            [FromQuery] string?artists,
            [FromQuery] string?excludeArtistIds,
            [FromQuery] string?artistIds,
            [FromQuery] string?albumArtistIds,
            [FromQuery] string?contributingArtistIds,
            [FromQuery] string?albums,
            [FromQuery] string?albumIds,
            [FromQuery] string?ids,
            [FromQuery] string?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] string?seriesStatus,
            [FromQuery] string?nameStartsWithOrGreater,
            [FromQuery] string?nameStartsWith,
            [FromQuery] string?nameLessThan,
            [FromQuery] string?studioIds,
            [FromQuery] string?genreIds,
            [FromQuery] bool enableTotalRecordCount = true,
            [FromQuery] bool?enableImages           = true)
        {
            // use user id route parameter over query parameter
            userId = uId ?? userId;

            var user = userId.HasValue && !userId.Equals(Guid.Empty)
                ? _userManager.GetUserById(userId.Value)
                : null;
            var dtoOptions = new DtoOptions()
                             .AddItemFields(fields)
                             .AddClientFields(Request)
                             .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);

            if (string.Equals(includeItemTypes, "Playlist", StringComparison.OrdinalIgnoreCase) ||
                string.Equals(includeItemTypes, "BoxSet", StringComparison.OrdinalIgnoreCase))
            {
                parentId = null;
            }

            BaseItem?item = null;
            QueryResult <BaseItem> result;

            if (!string.IsNullOrEmpty(parentId))
            {
                item = _libraryManager.GetItemById(parentId);
            }

            item ??= _libraryManager.GetUserRootFolder();

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

            if (folder is IHasCollectionType hasCollectionType &&
                string.Equals(hasCollectionType.CollectionType, CollectionType.Playlists, StringComparison.OrdinalIgnoreCase))
            {
                recursive        = true;
                includeItemTypes = "Playlist";
            }

            bool isInEnabledFolder = user !.GetPreference(PreferenceKind.EnabledFolders).Any(i => new Guid(i) == item.Id)
                                     // Assume all folders inside an EnabledChannel are enabled
                                     || user.GetPreference(PreferenceKind.EnabledChannels).Any(i => new Guid(i) == item.Id)
                                     // Assume all items inside an EnabledChannel are enabled
                                     || user.GetPreference(PreferenceKind.EnabledChannels).Any(i => new Guid(i) == item.ChannelId);

            var collectionFolders = _libraryManager.GetCollectionFolders(item);

            foreach (var collectionFolder in collectionFolders)
            {
                if (user.GetPreference(PreferenceKind.EnabledFolders).Contains(
                        collectionFolder.Id.ToString("N", CultureInfo.InvariantCulture),
                        StringComparer.OrdinalIgnoreCase))
                {
                    isInEnabledFolder = true;
                }
            }

            if (!(item is UserRootFolder) &&
                !isInEnabledFolder &&
                !user.HasPermission(PermissionKind.EnableAllFolders) &&
                !user.HasPermission(PermissionKind.EnableAllChannels))
            {
                _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) || !string.IsNullOrEmpty(ids) || !(item is UserRootFolder))
            {
                var query = new InternalItemsQuery(user !)
                {
                    IsPlayed                = isPlayed,
                    MediaTypes              = RequestHelpers.Split(mediaTypes, ',', true),
                    IncludeItemTypes        = RequestHelpers.Split(includeItemTypes, ',', true),
                    ExcludeItemTypes        = RequestHelpers.Split(excludeItemTypes, ',', true),
                    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,
                    HasOverview             = hasOverview,
                    HasOfficialRating       = hasOfficialRating,
                    HasParentalRating       = hasParentalRating,
                    HasSpecialFeature       = hasSpecialFeature,
                    HasSubtitles            = hasSubtitles,
                    HasThemeSong            = hasThemeSong,
                    HasThemeVideo           = hasThemeVideo,
                    HasTrailer              = hasTrailer,
                    IsHD                    = isHd,
                    Is4K                    = is4K,
                    Tags                    = RequestHelpers.Split(tags, '|', true),
                    OfficialRatings         = RequestHelpers.Split(officialRatings, '|', true),
                    Genres                  = RequestHelpers.Split(genres, '|', true),
                    ArtistIds               = RequestHelpers.GetGuids(artistIds),
                    AlbumArtistIds          = RequestHelpers.GetGuids(albumArtistIds),
                    ContributingArtistIds   = RequestHelpers.GetGuids(contributingArtistIds),
                    GenreIds                = RequestHelpers.GetGuids(genreIds),
                    StudioIds               = RequestHelpers.GetGuids(studioIds),
                    Person                  = person,
                    PersonIds               = RequestHelpers.GetGuids(personIds),
                    PersonTypes             = RequestHelpers.Split(personTypes, ',', true),
                    Years                   = RequestHelpers.Split(years, ',', true).Select(int.Parse).ToArray(),
                    ImageTypes              = RequestHelpers.Split(imageTypes, ',', true).Select(v => Enum.Parse <ImageType>(v, true)).ToArray(),
                    VideoTypes              = RequestHelpers.Split(videoTypes, ',', true).Select(v => Enum.Parse <VideoType>(v, true)).ToArray(),
                    AdjacentTo              = adjacentTo,
                    ItemIds                 = RequestHelpers.GetGuids(ids),
                    MinCommunityRating      = minCommunityRating,
                    MinCriticRating         = minCriticRating,
                    ParentId                = string.IsNullOrWhiteSpace(parentId) ? Guid.Empty : new Guid(parentId),
                    ParentIndexNumber       = parentIndexNumber,
                    EnableTotalRecordCount  = enableTotalRecordCount,
                    ExcludeItemIds          = RequestHelpers.GetGuids(excludeItemIds),
                    DtoOptions              = dtoOptions,
                    SearchTerm              = searchTerm,
                    MinDateLastSaved        = minDateLastSaved?.ToUniversalTime(),
                    MinDateLastSavedForUser = minDateLastSavedForUser?.ToUniversalTime(),
                    MinPremiereDate         = minPremiereDate?.ToUniversalTime(),
                    MaxPremiereDate         = maxPremiereDate?.ToUniversalTime(),
                };

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

                foreach (var filter in RequestHelpers.GetFilters(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 (!string.IsNullOrEmpty(seriesStatus))
                {
                    query.SeriesStatuses = seriesStatus.Split(',').Select(d => (SeriesStatus)Enum.Parse(typeof(SeriesStatus), d, true)).ToArray();
                }

                // ExcludeLocationTypes
                if (!string.IsNullOrEmpty(excludeLocationTypes))
                {
                    if (excludeLocationTypes.Split(',').Select(d => (LocationType)Enum.Parse(typeof(LocationType), d, true)).ToArray().Contains(LocationType.Virtual))
                    {
                        query.IsVirtualItem = false;
                    }
                }

                if (!string.IsNullOrEmpty(locationTypes))
                {
                    var requestedLocationTypes = locationTypes.Split(',');
                    if (requestedLocationTypes.Length > 0 && requestedLocationTypes.Length < 4)
                    {
                        query.IsVirtualItem = requestedLocationTypes.Contains(LocationType.Virtual.ToString());
                    }
                }

                // 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 (!string.IsNullOrEmpty(artists))
                {
                    query.ArtistIds = artists.Split('|').Select(i =>
                    {
                        try
                        {
                            return(_libraryManager.GetArtist(i, new DtoOptions(false)));
                        }
                        catch
                        {
                            return(null);
                        }
                    }).Where(i => i != null).Select(i => i !.Id).ToArray();
                }

                // ExcludeArtistIds
                if (!string.IsNullOrWhiteSpace(excludeArtistIds))
                {
                    query.ExcludeArtistIds = RequestHelpers.GetGuids(excludeArtistIds);
                }

                if (!string.IsNullOrWhiteSpace(albumIds))
                {
                    query.AlbumIds = RequestHelpers.GetGuids(albumIds);
                }

                // Albums
                if (!string.IsNullOrEmpty(albums))
                {
                    query.AlbumIds = albums.Split('|').SelectMany(i =>
                    {
                        return(_libraryManager.GetItemIds(new InternalItemsQuery {
                            IncludeItemTypes = new[] { nameof(MusicAlbum) }, Name = i, Limit = 1
                        }));
                    }).ToArray();
                }

                // Studios
                if (!string.IsNullOrEmpty(studios))
                {
                    query.StudioIds = studios.Split('|').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 && string.Equals(query.IncludeItemTypes[0], "MusicAlbum", StringComparison.OrdinalIgnoreCase))
                    {
                        query.OrderBy = new[] { new ValueTuple <string, SortOrder>(ItemSortBy.ProductionYear, SortOrder.Descending), new ValueTuple <string, SortOrder>(ItemSortBy.SortName, SortOrder.Ascending) };
                    }
                }

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

            return(new QueryResult <BaseItemDto> {
                StartIndex = startIndex.GetValueOrDefault(), TotalRecordCount = result.TotalRecordCount, Items = _dtoService.GetBaseItemDtos(result.Items, dtoOptions, user)
            });
        }
예제 #11
0
        /// <summary> Applies the additional filters. </summary>
        /// <param name="request"> The request. </param>
        /// <param name="i"> Zero-based index of the. </param>
        /// <param name="user"> The user. </param>
        /// <param name="isPreFiltered"> true if this object is pre filtered. </param>
        /// <param name="libraryManager"> Manager for library. </param>
        /// <returns> true if it succeeds, false if it fails. </returns>
        private bool ApplyAdditionalFilters(BaseReportRequest request, BaseItem i, User user, bool isPreFiltered, ILibraryManager libraryManager)
        {
            var video = i as Video;

            if (!isPreFiltered)
            {
                var mediaTypes = request.GetMediaTypes();
                if (mediaTypes.Length > 0)
                {
                    if (!(!string.IsNullOrEmpty(i.MediaType) && mediaTypes.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase)))
                    {
                        return(false);
                    }
                }

                if (request.IsPlayed.HasValue)
                {
                    var val = request.IsPlayed.Value;
                    if (i.IsPlayed(user) != val)
                    {
                        return(false);
                    }
                }

                // Exclude item types
                var excluteItemTypes = request.GetExcludeItemTypes();
                if (excluteItemTypes.Length > 0 && excluteItemTypes.Contains(i.GetType().Name, StringComparer.OrdinalIgnoreCase))
                {
                    return(false);
                }

                // Include item types
                var includeItemTypes = request.GetIncludeItemTypes();
                if (includeItemTypes.Length > 0 && !includeItemTypes.Contains(i.GetType().Name, StringComparer.OrdinalIgnoreCase))
                {
                    return(false);
                }

                if (request.IsInBoxSet.HasValue)
                {
                    var val = request.IsInBoxSet.Value;
                    if (i.Parents.OfType <BoxSet>().Any() != val)
                    {
                        return(false);
                    }
                }

                // Filter by Video3DFormat
                if (request.Is3D.HasValue)
                {
                    var val = request.Is3D.Value;

                    if (video == null || val != video.Video3DFormat.HasValue)
                    {
                        return(false);
                    }
                }

                if (request.IsHD.HasValue)
                {
                    var val = request.IsHD.Value;

                    if (video == null || val != video.IsHD)
                    {
                        return(false);
                    }
                }

                if (request.IsUnidentified.HasValue)
                {
                    var val = request.IsUnidentified.Value;
                    if (i.IsUnidentified != val)
                    {
                        return(false);
                    }
                }

                if (request.IsLocked.HasValue)
                {
                    var val = request.IsLocked.Value;
                    if (i.IsLocked != val)
                    {
                        return(false);
                    }
                }

                if (request.HasOverview.HasValue)
                {
                    var filterValue = request.HasOverview.Value;

                    var hasValue = !string.IsNullOrEmpty(i.Overview);

                    if (hasValue != filterValue)
                    {
                        return(false);
                    }
                }

                if (request.HasImdbId.HasValue)
                {
                    var filterValue = request.HasImdbId.Value;

                    var hasValue = !string.IsNullOrEmpty(i.GetProviderId(MetadataProviders.Imdb));

                    if (hasValue != filterValue)
                    {
                        return(false);
                    }
                }

                if (request.HasTmdbId.HasValue)
                {
                    var filterValue = request.HasTmdbId.Value;

                    var hasValue = !string.IsNullOrEmpty(i.GetProviderId(MetadataProviders.Tmdb));

                    if (hasValue != filterValue)
                    {
                        return(false);
                    }
                }

                if (request.HasTvdbId.HasValue)
                {
                    var filterValue = request.HasTvdbId.Value;

                    var hasValue = !string.IsNullOrEmpty(i.GetProviderId(MetadataProviders.Tvdb));

                    if (hasValue != filterValue)
                    {
                        return(false);
                    }
                }

                if (request.IsYearMismatched.HasValue)
                {
                    var filterValue = request.IsYearMismatched.Value;

                    if (UserViewBuilder.IsYearMismatched(i, libraryManager) != filterValue)
                    {
                        return(false);
                    }
                }

                if (request.HasOfficialRating.HasValue)
                {
                    var filterValue = request.HasOfficialRating.Value;

                    var hasValue = !string.IsNullOrEmpty(i.OfficialRating);

                    if (hasValue != filterValue)
                    {
                        return(false);
                    }
                }

                if (request.IsPlaceHolder.HasValue)
                {
                    var filterValue = request.IsPlaceHolder.Value;

                    var isPlaceHolder = false;

                    var hasPlaceHolder = i as ISupportsPlaceHolders;

                    if (hasPlaceHolder != null)
                    {
                        isPlaceHolder = hasPlaceHolder.IsPlaceHolder;
                    }

                    if (isPlaceHolder != filterValue)
                    {
                        return(false);
                    }
                }

                if (request.HasSpecialFeature.HasValue)
                {
                    var filterValue = request.HasSpecialFeature.Value;

                    var movie = i as IHasSpecialFeatures;

                    if (movie != null)
                    {
                        var ok = filterValue
                                                        ? movie.SpecialFeatureIds.Count > 0
                                                        : movie.SpecialFeatureIds.Count == 0;

                        if (!ok)
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }

                if (request.HasSubtitles.HasValue)
                {
                    var val = request.HasSubtitles.Value;

                    if (video == null || val != video.HasSubtitles)
                    {
                        return(false);
                    }
                }

                if (request.HasParentalRating.HasValue)
                {
                    var val = request.HasParentalRating.Value;

                    var rating = i.CustomRating;

                    if (string.IsNullOrEmpty(rating))
                    {
                        rating = i.OfficialRating;
                    }

                    if (val)
                    {
                        if (string.IsNullOrEmpty(rating))
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(rating))
                        {
                            return(false);
                        }
                    }
                }

                if (request.HasTrailer.HasValue)
                {
                    var val          = request.HasTrailer.Value;
                    var trailerCount = 0;

                    var hasTrailers = i as IHasTrailers;
                    if (hasTrailers != null)
                    {
                        trailerCount = hasTrailers.GetTrailerIds().Count;
                    }

                    var ok = val ? trailerCount > 0 : trailerCount == 0;

                    if (!ok)
                    {
                        return(false);
                    }
                }

                if (request.HasThemeSong.HasValue)
                {
                    var filterValue = request.HasThemeSong.Value;

                    var themeCount     = 0;
                    var iHasThemeMedia = i as IHasThemeMedia;

                    if (iHasThemeMedia != null)
                    {
                        themeCount = iHasThemeMedia.ThemeSongIds.Count;
                    }
                    var ok = filterValue ? themeCount > 0 : themeCount == 0;

                    if (!ok)
                    {
                        return(false);
                    }
                }

                if (request.HasThemeVideo.HasValue)
                {
                    var filterValue = request.HasThemeVideo.Value;

                    var themeCount     = 0;
                    var iHasThemeMedia = i as IHasThemeMedia;

                    if (iHasThemeMedia != null)
                    {
                        themeCount = iHasThemeMedia.ThemeVideoIds.Count;
                    }
                    var ok = filterValue ? themeCount > 0 : themeCount == 0;

                    if (!ok)
                    {
                        return(false);
                    }
                }

                // Apply tag filter
                var tags = request.GetTags();
                if (tags.Length > 0)
                {
                    var hasTags = i as IHasTags;
                    if (hasTags == null)
                    {
                        return(false);
                    }
                    if (!(tags.Any(v => hasTags.Tags.Contains(v, StringComparer.OrdinalIgnoreCase))))
                    {
                        return(false);
                    }
                }

                // Apply official rating filter
                var officialRatings = request.GetOfficialRatings();
                if (officialRatings.Length > 0 && !officialRatings.Contains(i.OfficialRating ?? string.Empty))
                {
                    return(false);
                }

                // Apply genre filter
                var genres = request.GetGenres();
                if (genres.Length > 0 && !(genres.Any(v => i.Genres.Contains(v, StringComparer.OrdinalIgnoreCase))))
                {
                    return(false);
                }

                // Filter by VideoType
                var videoTypes = request.GetVideoTypes();
                if (videoTypes.Length > 0 && (video == null || !videoTypes.Contains(video.VideoType)))
                {
                    return(false);
                }

                var imageTypes = request.GetImageTypes().ToList();
                if (imageTypes.Count > 0)
                {
                    if (!(imageTypes.Any(i.HasImage)))
                    {
                        return(false);
                    }
                }

                // Apply studio filter
                var studios = request.GetStudios();
                if (studios.Length > 0 && !studios.Any(v => i.Studios.Contains(v, StringComparer.OrdinalIgnoreCase)))
                {
                    return(false);
                }

                // Apply studio filter
                var studioIds = request.GetStudioIds();
                if (studioIds.Length > 0 && !studioIds.Any(id =>
                {
                    var studioItem = libraryManager.GetItemById(id);
                    return(studioItem != null && i.Studios.Contains(studioItem.Name, StringComparer.OrdinalIgnoreCase));
                }))
                {
                    return(false);
                }

                // Apply year filter
                var years = request.GetYears();
                if (years.Length > 0 && !(i.ProductionYear.HasValue && years.Contains(i.ProductionYear.Value)))
                {
                    return(false);
                }

                // Apply person filter
                var personIds = request.GetPersonIds();
                if (personIds.Length > 0)
                {
                    var names = personIds
                                .Select(libraryManager.GetItemById)
                                .Select(p => p == null ? "-1" : p.Name)
                                .ToList();

                    if (!(names.Any(v => _libraryManager.GetPeople(i).Select(p => p.Name).Contains(v, StringComparer.OrdinalIgnoreCase))))
                    {
                        return(false);
                    }
                }

                // Apply person filter
                if (!string.IsNullOrEmpty(request.Person))
                {
                    var personTypes = request.GetPersonTypes();

                    if (personTypes.Length == 0)
                    {
                        if (!(_libraryManager.GetPeople(i).Any(p => string.Equals(p.Name, request.Person, StringComparison.OrdinalIgnoreCase))))
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        var types = personTypes;

                        var ok = new[] { i }.Any(item =>
                                                 _libraryManager.GetPeople(i).Any(p =>
                                                                                  p.Name.Equals(request.Person, StringComparison.OrdinalIgnoreCase) && (types.Contains(p.Type, StringComparer.OrdinalIgnoreCase) || types.Contains(p.Role, StringComparer.OrdinalIgnoreCase))));

                        if (!ok)
                        {
                            return(false);
                        }
                    }
                }
            }

            if (request.MinCommunityRating.HasValue)
            {
                var val = request.MinCommunityRating.Value;

                if (!(i.CommunityRating.HasValue && i.CommunityRating >= val))
                {
                    return(false);
                }
            }

            if (request.MinCriticRating.HasValue)
            {
                var val = request.MinCriticRating.Value;

                var hasCriticRating = i as IHasCriticRating;

                if (hasCriticRating != null)
                {
                    if (!(hasCriticRating.CriticRating.HasValue && hasCriticRating.CriticRating >= val))
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }

            // Artists
            if (!string.IsNullOrEmpty(request.ArtistIds))
            {
                var artistIds = request.ArtistIds.Split('|');

                var audio = i as IHasArtist;

                if (!(audio != null && artistIds.Any(id =>
                {
                    var artistItem = libraryManager.GetItemById(id);
                    return(artistItem != null && audio.HasAnyArtist(artistItem.Name));
                })))
                {
                    return(false);
                }
            }

            // Artists
            if (!string.IsNullOrEmpty(request.Artists))
            {
                var artists = request.Artists.Split('|');

                var audio = i as IHasArtist;

                if (!(audio != null && artists.Any(audio.HasAnyArtist)))
                {
                    return(false);
                }
            }

            // Albums
            if (!string.IsNullOrEmpty(request.Albums))
            {
                var albums = request.Albums.Split('|');

                var audio = i as Audio;

                if (audio != null)
                {
                    if (!albums.Any(a => string.Equals(a, audio.Album, StringComparison.OrdinalIgnoreCase)))
                    {
                        return(false);
                    }
                }

                var album = i as MusicAlbum;

                if (album != null)
                {
                    if (!albums.Any(a => string.Equals(a, album.Name, StringComparison.OrdinalIgnoreCase)))
                    {
                        return(false);
                    }
                }

                var musicVideo = i as MusicVideo;

                if (musicVideo != null)
                {
                    if (!albums.Any(a => string.Equals(a, musicVideo.Album, StringComparison.OrdinalIgnoreCase)))
                    {
                        return(false);
                    }
                }

                return(false);
            }

            // Min index number
            if (request.MinIndexNumber.HasValue)
            {
                if (!(i.IndexNumber.HasValue && i.IndexNumber.Value >= request.MinIndexNumber.Value))
                {
                    return(false);
                }
            }

            // Min official rating
            if (!string.IsNullOrEmpty(request.MinOfficialRating))
            {
                var level = _localization.GetRatingLevel(request.MinOfficialRating);

                if (level.HasValue)
                {
                    var rating = i.CustomRating;

                    if (string.IsNullOrEmpty(rating))
                    {
                        rating = i.OfficialRating;
                    }

                    if (!string.IsNullOrEmpty(rating))
                    {
                        var itemLevel = _localization.GetRatingLevel(rating);

                        if (!(!itemLevel.HasValue || itemLevel.Value >= level.Value))
                        {
                            return(false);
                        }
                    }
                }
            }

            // Max official rating
            if (!string.IsNullOrEmpty(request.MaxOfficialRating))
            {
                var level = _localization.GetRatingLevel(request.MaxOfficialRating);

                if (level.HasValue)
                {
                    var rating = i.CustomRating;

                    if (string.IsNullOrEmpty(rating))
                    {
                        rating = i.OfficialRating;
                    }

                    if (!string.IsNullOrEmpty(rating))
                    {
                        var itemLevel = _localization.GetRatingLevel(rating);

                        if (!(!itemLevel.HasValue || itemLevel.Value <= level.Value))
                        {
                            return(false);
                        }
                    }
                }
            }

            // LocationTypes
            if (!string.IsNullOrEmpty(request.LocationTypes))
            {
                var vals = request.LocationTypes.Split(',');
                if (!vals.Contains(i.LocationType.ToString(), StringComparer.OrdinalIgnoreCase))
                {
                    return(false);
                }
            }

            // ExcludeLocationTypes
            if (!string.IsNullOrEmpty(request.ExcludeLocationTypes))
            {
                var vals = request.ExcludeLocationTypes.Split(',');
                if (vals.Contains(i.LocationType.ToString(), StringComparer.OrdinalIgnoreCase))
                {
                    return(false);
                }
            }

            if (!string.IsNullOrEmpty(request.AlbumArtistStartsWithOrGreater))
            {
                var ok = new[] { i }.OfType <IHasAlbumArtist>()
                .Any(p => string.Compare(request.AlbumArtistStartsWithOrGreater, p.AlbumArtists.FirstOrDefault(), StringComparison.CurrentCultureIgnoreCase) < 1);

                if (!ok)
                {
                    return(false);
                }
            }

            // Filter by Series Status
            if (!string.IsNullOrEmpty(request.SeriesStatus))
            {
                var vals = request.SeriesStatus.Split(',');

                var ok = new[] { i }.OfType <Series>().Any(p => p.Status.HasValue && vals.Contains(p.Status.Value.ToString(), StringComparer.OrdinalIgnoreCase));

                if (!ok)
                {
                    return(false);
                }
            }

            // Filter by Series AirDays
            if (!string.IsNullOrEmpty(request.AirDays))
            {
                var days = request.AirDays.Split(',').Select(d => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), d, true));

                var ok = new[] { i }.OfType <Series>().Any(p => p.AirDays != null && days.Any(d => p.AirDays.Contains(d)));

                if (!ok)
                {
                    return(false);
                }
            }

            if (request.MinPlayers.HasValue)
            {
                var filterValue = request.MinPlayers.Value;

                var game = i as Game;

                if (game != null)
                {
                    var players = game.PlayersSupported ?? 1;

                    var ok = players >= filterValue;

                    if (!ok)
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }

            if (request.MaxPlayers.HasValue)
            {
                var filterValue = request.MaxPlayers.Value;

                var game = i as Game;

                if (game != null)
                {
                    var players = game.PlayersSupported ?? 1;

                    var ok = players <= filterValue;

                    if (!ok)
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }

            if (request.ParentIndexNumber.HasValue)
            {
                var filterValue = request.ParentIndexNumber.Value;

                var episode = i as Episode;

                if (episode != null)
                {
                    if (episode.ParentIndexNumber.HasValue && episode.ParentIndexNumber.Value != filterValue)
                    {
                        return(false);
                    }
                }

                var song = i as Audio;

                if (song != null)
                {
                    if (song.ParentIndexNumber.HasValue && song.ParentIndexNumber.Value != filterValue)
                    {
                        return(false);
                    }
                }
            }

            if (request.AiredDuringSeason.HasValue)
            {
                var episode = i as Episode;

                if (episode == null)
                {
                    return(false);
                }

                if (!Series.FilterEpisodesBySeason(new[] { episode }, request.AiredDuringSeason.Value, true).Any())
                {
                    return(false);
                }
            }

            if (!string.IsNullOrEmpty(request.MinPremiereDate))
            {
                var date = DateTime.Parse(request.MinPremiereDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();

                if (!(i.PremiereDate.HasValue && i.PremiereDate.Value >= date))
                {
                    return(false);
                }
            }

            if (!string.IsNullOrEmpty(request.MaxPremiereDate))
            {
                var date = DateTime.Parse(request.MaxPremiereDate, null, DateTimeStyles.RoundtripKind).ToUniversalTime();

                if (!(i.PremiereDate.HasValue && i.PremiereDate.Value <= date))
                {
                    return(false);
                }
            }

            return(true);
        }
예제 #12
0
        /// <summary>
        /// Applies the additional filters.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="items">The items.</param>
        /// <returns>IEnumerable{BaseItem}.</returns>
        private IEnumerable <BaseItem> ApplyAdditionalFilters(GetItems request, IEnumerable <BaseItem> items, User user)
        {
            if (request.MinCommunityRating.HasValue)
            {
                var val = request.MinCommunityRating.Value;

                items = items.Where(i => i.CommunityRating.HasValue && i.CommunityRating >= val);
            }

            if (request.MinCriticRating.HasValue)
            {
                var val = request.MinCriticRating.Value;

                items = items.Where(i =>
                {
                    var hasCriticRating = i as IHasCriticRating;

                    if (hasCriticRating != null)
                    {
                        return(hasCriticRating.CriticRating.HasValue && hasCriticRating.CriticRating >= val);
                    }

                    return(false);
                });
            }

            // Artists
            if (!string.IsNullOrEmpty(request.Artists))
            {
                var artists = request.Artists.Split('|');

                items = items.Where(i =>
                {
                    var audio = i as IHasArtist;

                    return(audio != null && artists.Any(audio.HasArtist));
                });
            }

            // Albums
            if (!string.IsNullOrEmpty(request.Albums))
            {
                var albums = request.Albums.Split('|');

                items = items.Where(i =>
                {
                    var audio = i as Audio;

                    if (audio != null)
                    {
                        return(albums.Any(a => string.Equals(a, audio.Album, StringComparison.OrdinalIgnoreCase)));
                    }

                    var album = i as MusicAlbum;

                    if (album != null)
                    {
                        return(albums.Any(a => string.Equals(a, album.Name, StringComparison.OrdinalIgnoreCase)));
                    }

                    var musicVideo = i as MusicVideo;

                    if (musicVideo != null)
                    {
                        return(albums.Any(a => string.Equals(a, musicVideo.Album, StringComparison.OrdinalIgnoreCase)));
                    }

                    return(false);
                });
            }

            if (!string.IsNullOrEmpty(request.AdjacentTo))
            {
                var item = _dtoService.GetItemByDtoId(request.AdjacentTo);

                var allSiblings = item.Parent.GetChildren(user, true).OrderBy(i => i.SortName).ToList();

                var index = allSiblings.IndexOf(item);

                var previousId = Guid.Empty;
                var nextId     = Guid.Empty;

                if (index > 0)
                {
                    previousId = allSiblings[index - 1].Id;
                }

                if (index < allSiblings.Count - 1)
                {
                    nextId = allSiblings[index + 1].Id;
                }

                items = items.Where(i => i.Id == previousId || i.Id == nextId);
            }

            // Min index number
            if (request.MinIndexNumber.HasValue)
            {
                items = items.Where(i => i.IndexNumber.HasValue && i.IndexNumber.Value >= request.MinIndexNumber.Value);
            }

            // Min official rating
            if (!string.IsNullOrEmpty(request.MinOfficialRating))
            {
                var level = _localization.GetRatingLevel(request.MinOfficialRating);

                if (level.HasValue)
                {
                    items = items.Where(i =>
                    {
                        var rating = i.CustomRating;

                        if (string.IsNullOrEmpty(rating))
                        {
                            rating = i.OfficialRating;
                        }

                        if (string.IsNullOrEmpty(rating))
                        {
                            return(true);
                        }

                        var itemLevel = _localization.GetRatingLevel(rating);

                        return(!itemLevel.HasValue || itemLevel.Value >= level.Value);
                    });
                }
            }

            // Max official rating
            if (!string.IsNullOrEmpty(request.MaxOfficialRating))
            {
                var level = _localization.GetRatingLevel(request.MaxOfficialRating);

                if (level.HasValue)
                {
                    items = items.Where(i =>
                    {
                        var rating = i.CustomRating;

                        if (string.IsNullOrEmpty(rating))
                        {
                            rating = i.OfficialRating;
                        }

                        if (string.IsNullOrEmpty(rating))
                        {
                            return(true);
                        }

                        var itemLevel = _localization.GetRatingLevel(rating);

                        return(!itemLevel.HasValue || itemLevel.Value <= level.Value);
                    });
                }
            }

            // Exclude item types
            if (!string.IsNullOrEmpty(request.ExcludeItemTypes))
            {
                var vals = request.ExcludeItemTypes.Split(',');
                items = items.Where(f => !vals.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase));
            }

            // Include item types
            if (!string.IsNullOrEmpty(request.IncludeItemTypes))
            {
                var vals = request.IncludeItemTypes.Split(',');
                items = items.Where(f => vals.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase));
            }

            // LocationTypes
            if (!string.IsNullOrEmpty(request.LocationTypes))
            {
                var vals = request.LocationTypes.Split(',');
                items = items.Where(f => vals.Contains(f.LocationType.ToString(), StringComparer.OrdinalIgnoreCase));
            }

            // ExcludeLocationTypes
            if (!string.IsNullOrEmpty(request.ExcludeLocationTypes))
            {
                var vals = request.ExcludeLocationTypes.Split(',');
                items = items.Where(f => !vals.Contains(f.LocationType.ToString(), StringComparer.OrdinalIgnoreCase));
            }

            if (!string.IsNullOrEmpty(request.NameStartsWithOrGreater))
            {
                items = items.Where(i => string.Compare(request.NameStartsWithOrGreater, i.SortName, StringComparison.CurrentCultureIgnoreCase) < 1);
            }

            if (!string.IsNullOrEmpty(request.AlbumArtistStartsWithOrGreater))
            {
                items = items.OfType <IHasAlbumArtist>()
                        .Where(i => string.Compare(request.AlbumArtistStartsWithOrGreater, i.AlbumArtist, StringComparison.CurrentCultureIgnoreCase) < 1)
                        .Cast <BaseItem>();
            }

            // Filter by Series Status
            if (!string.IsNullOrEmpty(request.SeriesStatus))
            {
                var vals = request.SeriesStatus.Split(',');

                items = items.OfType <Series>().Where(i => i.Status.HasValue && vals.Contains(i.Status.Value.ToString(), StringComparer.OrdinalIgnoreCase));
            }

            // Filter by Series AirDays
            if (!string.IsNullOrEmpty(request.AirDays))
            {
                var days = request.AirDays.Split(',').Select(d => (DayOfWeek)Enum.Parse(typeof(DayOfWeek), d, true));

                items = items.OfType <Series>().Where(i => i.AirDays != null && days.Any(d => i.AirDays.Contains(d)));
            }

            // Filter by Video3DFormat
            if (request.Is3D.HasValue)
            {
                items = items.OfType <Video>().Where(i => request.Is3D.Value == i.Video3DFormat.HasValue);
            }

            // Filter by VideoType
            if (!string.IsNullOrEmpty(request.VideoTypes))
            {
                var types = request.VideoTypes.Split(',');

                items = items.OfType <Video>().Where(i => types.Contains(i.VideoType.ToString(), StringComparer.OrdinalIgnoreCase));
            }

            if (!string.IsNullOrEmpty(request.MediaTypes))
            {
                var types = request.MediaTypes.Split(',');

                items = items.Where(i => !string.IsNullOrEmpty(i.MediaType) && types.Contains(i.MediaType, StringComparer.OrdinalIgnoreCase));
            }

            var imageTypes = request.GetImageTypes().ToList();

            if (imageTypes.Count > 0)
            {
                items = items.Where(item => imageTypes.Any(imageType => HasImage(item, imageType)));
            }

            // Apply genre filter
            if (!string.IsNullOrEmpty(request.Genres))
            {
                var vals = request.Genres.Split(',');
                items = items.Where(f => vals.Any(v => f.Genres.Contains(v, StringComparer.OrdinalIgnoreCase)));
            }

            // Apply genre filter
            if (!string.IsNullOrEmpty(request.AllGenres))
            {
                var vals = request.AllGenres.Split(',');
                items = items.Where(f => vals.All(v => f.Genres.Contains(v, StringComparer.OrdinalIgnoreCase)));
            }

            // Apply studio filter
            if (!string.IsNullOrEmpty(request.Studios))
            {
                var vals = request.Studios.Split(',');
                items = items.Where(f => vals.Any(v => f.Studios.Contains(v, StringComparer.OrdinalIgnoreCase)));
            }

            // Apply year filter
            if (!string.IsNullOrEmpty(request.Years))
            {
                var vals = request.Years.Split(',').Select(int.Parse).ToList();
                items = items.Where(f => f.ProductionYear.HasValue && vals.Contains(f.ProductionYear.Value));
            }

            // Apply person filter
            if (!string.IsNullOrEmpty(request.Person))
            {
                var personTypes = request.PersonTypes;

                if (string.IsNullOrEmpty(personTypes))
                {
                    items = items.Where(item => item.People.Any(p => string.Equals(p.Name, request.Person, StringComparison.OrdinalIgnoreCase)));
                }
                else
                {
                    var types = personTypes.Split(',');

                    items = items.Where(item =>
                                        item.People != null &&
                                        item.People.Any(p =>
                                                        p.Name.Equals(request.Person, StringComparison.OrdinalIgnoreCase) && (types.Contains(p.Type, StringComparer.OrdinalIgnoreCase) || types.Contains(p.Role, StringComparer.OrdinalIgnoreCase))));
                }
            }

            if (request.HasTrailer.HasValue)
            {
                items = items.Where(i => request.HasTrailer.Value ? i.LocalTrailerIds.Count > 0 : i.LocalTrailerIds.Count == 0);
            }

            if (request.HasThemeSong.HasValue)
            {
                items = items.Where(i => request.HasThemeSong.Value ? i.ThemeSongIds.Count > 0 : i.ThemeSongIds.Count == 0);
            }

            if (request.HasThemeVideo.HasValue)
            {
                items = items.Where(i => request.HasThemeVideo.Value ? i.ThemeVideoIds.Count > 0 : i.ThemeVideoIds.Count == 0);
            }

            if (request.MinPlayers.HasValue)
            {
                var filterValue = request.MinPlayers.Value;

                items = items.Where(i =>
                {
                    var game = i as Game;

                    if (game != null)
                    {
                        var players = game.PlayersSupported ?? 1;

                        return(players >= filterValue);
                    }

                    return(false);
                });
            }

            if (request.MaxPlayers.HasValue)
            {
                var filterValue = request.MaxPlayers.Value;

                items = items.Where(i =>
                {
                    var game = i as Game;

                    if (game != null)
                    {
                        var players = game.PlayersSupported ?? 1;

                        return(players <= filterValue);
                    }

                    return(false);
                });
            }

            if (request.HasSpecialFeature.HasValue)
            {
                var filterValue = request.HasSpecialFeature.Value;

                items = items.Where(i =>
                {
                    var movie = i as Movie;

                    if (movie != null)
                    {
                        return(filterValue
                                   ? movie.SpecialFeatureIds.Count > 0
                                   : movie.SpecialFeatureIds.Count == 0);
                    }

                    var series = i as Series;

                    if (series != null)
                    {
                        return(filterValue
                                   ? series.SpecialFeatureIds.Count > 0
                                   : series.SpecialFeatureIds.Count == 0);
                    }

                    return(false);
                });
            }

            if (request.HasSubtitles.HasValue)
            {
                items = items.OfType <Video>().Where(i =>
                {
                    if (request.HasSubtitles.Value)
                    {
                        return(i.MediaStreams != null && i.MediaStreams.Any(m => m.Type == MediaStreamType.Subtitle));
                    }

                    return(i.MediaStreams == null || i.MediaStreams.All(m => m.Type != MediaStreamType.Subtitle));
                });
            }

            if (request.HasParentalRating.HasValue)
            {
                items = items.Where(i =>
                {
                    var rating = i.CustomRating;

                    if (string.IsNullOrEmpty(rating))
                    {
                        rating = i.OfficialRating;
                    }

                    if (request.HasParentalRating.Value)
                    {
                        return(!string.IsNullOrEmpty(rating));
                    }

                    return(string.IsNullOrEmpty(rating));
                });
            }

            if (request.IsHD.HasValue)
            {
                var val = request.IsHD.Value;
                items = items.OfType <Video>().Where(i => i.IsHD == val);
            }

            if (request.ParentIndexNumber.HasValue)
            {
                var filterValue = request.ParentIndexNumber.Value;

                items = items.Where(i =>
                {
                    var episode = i as Episode;

                    if (episode != null)
                    {
                        return(episode.ParentIndexNumber.HasValue && episode.ParentIndexNumber.Value == filterValue);
                    }

                    var song = i as Audio;

                    if (song != null)
                    {
                        return(song.ParentIndexNumber.HasValue && song.ParentIndexNumber.Value == filterValue);
                    }

                    return(true);
                });
            }

            return(items);
        }