Esempio n. 1
0
        /// <summary>
        /// Gets the items.
        /// </summary>
        /// <param name="request">The request.</param>
        private QueryResult <BaseItemDto> GetItems(GetItems request)
        {
            var user = !string.IsNullOrWhiteSpace(request.UserId) ? _userManager.GetUserById(request.UserId) : null;

            var dtoOptions = GetDtoOptions(_authContext, request);

            var result = GetQueryResult(request, dtoOptions, user);

            if (result == null)
            {
                throw new InvalidOperationException("GetItemsToSerialize returned null");
            }

            if (result.Items == null)
            {
                throw new InvalidOperationException("GetItemsToSerialize result.Items returned null");
            }

            var dtoList = _dtoService.GetBaseItemDtos(result.Items, dtoOptions, user);

            if (dtoList == null)
            {
                throw new InvalidOperationException("GetBaseItemDtos returned null");
            }

            return(new QueryResult <BaseItemDto>
            {
                TotalRecordCount = result.TotalRecordCount,
                Items = dtoList
            });
        }
Esempio n. 2
0
        /// <summary>
        /// Gets the items.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Task{ItemsResult}.</returns>
        private async Task <ItemsResult> GetItems(GetItems request)
        {
            var user = !string.IsNullOrWhiteSpace(request.UserId) ? _userManager.GetUserById(request.UserId) : null;

            var result = await GetQueryResult(request, user).ConfigureAwait(false);

            if (result == null)
            {
                throw new InvalidOperationException("GetItemsToSerialize returned null");
            }

            if (result.Items == null)
            {
                throw new InvalidOperationException("GetItemsToSerialize result.Items returned null");
            }

            var dtoOptions = GetDtoOptions(request);

            var dtoList = await _dtoService.GetBaseItemDtos(result.Items, dtoOptions, user).ConfigureAwait(false);

            if (dtoList == null)
            {
                throw new InvalidOperationException("GetBaseItemDtos returned null");
            }

            return(new ItemsResult
            {
                TotalRecordCount = result.TotalRecordCount,
                Items = dtoList.ToArray()
            });
        }
Esempio n. 3
0
        /// <summary>
        /// Gets the items.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Task{ItemsResult}.</returns>
        private async Task <ItemsResult> GetItems(GetItems request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var items = GetItemsToSerialize(request, user);

            // Apply filters
            // Run them starting with the ones that are likely to reduce the list the most
            foreach (var filter in GetFilters(request).OrderByDescending(f => (int)f))
            {
                items = ApplyFilter(items, filter, user);
            }

            items = ApplyAdditionalFilters(request, items);

            items = ApplySearchTerm(request, items);

            items = ApplySortOrder(request, items, user);

            var itemsArray = items.ToArray();

            var pagedItems = ApplyPaging(request, itemsArray);

            var fields = GetItemFields(request).ToList();

            var dtoBuilder = new DtoBuilder(Logger, _libraryManager);

            var returnItems = await Task.WhenAll(pagedItems.Select(i => dtoBuilder.GetBaseItemDto(i, user, fields))).ConfigureAwait(false);

            return(new ItemsResult
            {
                TotalRecordCount = itemsArray.Length,
                Items = returnItems
            });
        }
Esempio n. 4
0
        /// <summary>
        /// Gets the items to serialize.
        /// </summary>
        private QueryResult <BaseItem> GetQueryResult(GetItems request, DtoOptions dtoOptions, User user)
        {
            if (string.Equals(request.IncludeItemTypes, "Playlist", StringComparison.OrdinalIgnoreCase))
            {
                request.ParentId = null;
            }
            else if (string.Equals(request.IncludeItemTypes, "BoxSet", StringComparison.OrdinalIgnoreCase))
            {
                request.ParentId = null;
            }

            var item = string.IsNullOrEmpty(request.ParentId) ?
                       null :
                       _libraryManager.GetItemById(request.ParentId);

            if (item == null)
            {
                item = string.IsNullOrEmpty(request.ParentId) ?
                       user == null ? _libraryManager.RootFolder : _libraryManager.GetUserRootFolder() :
                       _libraryManager.GetItemById(request.ParentId);
            }

            // Default list type = children

            var folder = item as Folder;

            if (folder == null)
            {
                folder = user == null ? _libraryManager.RootFolder : _libraryManager.GetUserRootFolder();
            }

            var hasCollectionType = folder as IHasCollectionType;
            var isPlaylistQuery   = (hasCollectionType != null && string.Equals(hasCollectionType.CollectionType, CollectionType.Playlists, StringComparison.OrdinalIgnoreCase));

            if (isPlaylistQuery)
            {
                request.Recursive        = true;
                request.IncludeItemTypes = "Playlist";
            }

            if (request.Recursive || !string.IsNullOrEmpty(request.Ids) || user == null)
            {
                return(folder.GetItems(GetItemsQuery(request, dtoOptions, user)));
            }

            var userRoot = item as UserRootFolder;

            if (userRoot == null)
            {
                return(folder.GetItems(GetItemsQuery(request, dtoOptions, user)));
            }

            var itemsArray = folder.GetChildren(user, true).ToArray();

            return(new QueryResult <BaseItem>
            {
                Items = itemsArray,
                TotalRecordCount = itemsArray.Length
            });
        }
Esempio n. 5
0
        /// <summary>
        /// Gets the items to serialize.
        /// </summary>
        private QueryResult <BaseItem> GetQueryResult(GetItems request, DtoOptions dtoOptions, User user)
        {
            var item = string.IsNullOrEmpty(request.ParentId) ?
                       null :
                       _libraryManager.GetItemById(request.ParentId);

            if (string.Equals(request.IncludeItemTypes, "Playlist", StringComparison.OrdinalIgnoreCase))
            {
                if (item == null || user != null)
                {
                    item = _libraryManager.RootFolder.Children.OfType <Folder>().FirstOrDefault(i => string.Equals(i.GetType().Name, "PlaylistsFolder", StringComparison.OrdinalIgnoreCase));
                }
            }
            else if (string.Equals(request.IncludeItemTypes, "BoxSet", StringComparison.OrdinalIgnoreCase))
            {
                item = user == null ? _libraryManager.RootFolder : user.RootFolder;
            }

            if (item == null)
            {
                item = string.IsNullOrEmpty(request.ParentId) ?
                       user == null ? _libraryManager.RootFolder : user.RootFolder :
                       _libraryManager.GetItemById(request.ParentId);
            }

            // Default list type = children

            var folder = item as Folder;

            if (folder == null)
            {
                folder = user == null ? _libraryManager.RootFolder : _libraryManager.GetUserRootFolder();
            }

            if (request.Recursive || !string.IsNullOrEmpty(request.Ids) || user == null)
            {
                return(folder.GetItems(GetItemsQuery(request, dtoOptions, user)));
            }

            var userRoot = item as UserRootFolder;

            if (userRoot == null)
            {
                return(folder.GetItems(GetItemsQuery(request, dtoOptions, user)));
            }

            IEnumerable <BaseItem> items = folder.GetChildren(user, true);

            var itemsArray = items.ToArray();

            return(new QueryResult <BaseItem>
            {
                Items = itemsArray,
                TotalRecordCount = itemsArray.Length
            });
        }
Esempio n. 6
0
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public object Get(GetItems request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var result = GetItems(request);

            return(ToOptimizedResult(result));
        }
Esempio n. 7
0
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public object Get(GetItems request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            var result = GetItems(request);

            return(ToOptimizedSerializedResultUsingCache(result));
        }
Esempio n. 8
0
        /// <summary>
        /// Applies the search term.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="items">The items.</param>
        /// <returns>IEnumerable{BaseItem}.</returns>
        private IEnumerable <BaseItem> ApplySearchTerm(GetItems request, IEnumerable <BaseItem> items)
        {
            var term = request.SearchTerm;

            if (!string.IsNullOrEmpty(term))
            {
                items = _searchEngine.Search(items, request.SearchTerm);
            }

            return(items);
        }
Esempio n. 9
0
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public async Task <object> Get(GetItems request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            var result = await GetItems(request).ConfigureAwait(false);

            return(ToOptimizedSerializedResultUsingCache(result));
        }
Esempio n. 10
0
        /// <summary>
        /// Gets the order by.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>IEnumerable{ItemSortBy}.</returns>
        private IEnumerable <string> GetOrderBy(GetItems request)
        {
            var val = request.SortBy;

            if (string.IsNullOrEmpty(val))
            {
                return(new string[] { });
            }

            return(val.Split(','));
        }
Esempio n. 11
0
        /// <summary>
        /// Gets the item fields.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>IEnumerable{ItemFields}.</returns>
        private IEnumerable <ItemFields> GetItemFields(GetItems request)
        {
            var val = request.Fields;

            if (string.IsNullOrEmpty(val))
            {
                return(new ItemFields[] { });
            }

            return(val.Split(',').Select(v => (ItemFields)Enum.Parse(typeof(ItemFields), v, true)));
        }
Esempio n. 12
0
        /// <summary>
        /// Gets the image types.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>IEnumerable{ImageType}.</returns>
        private static IEnumerable <ImageType> GetImageTypes(GetItems request)
        {
            var val = request.ImageTypes;

            if (string.IsNullOrEmpty(val))
            {
                return(new ImageType[] { });
            }

            return(val.Split(',').Select(v => (ImageType)Enum.Parse(typeof(ImageType), v, true)));
        }
Esempio n. 13
0
        /// <summary>
        /// Gets the items.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Task{ItemsResult}.</returns>
        private async Task <ItemsResult> GetItems(GetItems request)
        {
            var user = !string.IsNullOrWhiteSpace(request.UserId) ? _userManager.GetUserById(request.UserId) : null;

            var result = await GetItemsToSerialize(request, user).ConfigureAwait(false);

            var dtoOptions = GetDtoOptions(request);

            return(new ItemsResult
            {
                TotalRecordCount = result.TotalRecordCount,
                Items = _dtoService.GetBaseItemDtos(result.Items, dtoOptions, user).ToArray()
            });
        }
Esempio n. 14
0
        private IEnumerable <BaseItem> FilterVirtualEpisodes(GetItems request, IEnumerable <BaseItem> items, User user)
        {
            items = FilterVirtualSeasons(request, items, user);

            if (request.IsMissing.HasValue)
            {
                var val = request.IsMissing.Value;
                items = items.Where(i =>
                {
                    var e = i as Episode;
                    if (e != null)
                    {
                        return(e.IsMissingEpisode == val);
                    }
                    return(true);
                });
            }

            if (request.IsUnaired.HasValue)
            {
                var val = request.IsUnaired.Value;
                items = items.Where(i =>
                {
                    var e = i as Episode;
                    if (e != null)
                    {
                        return(e.IsUnaired == val);
                    }
                    return(true);
                });
            }

            if (request.IsVirtualUnaired.HasValue)
            {
                var val = request.IsVirtualUnaired.Value;
                items = items.Where(i =>
                {
                    var e = i as Episode;
                    if (e != null)
                    {
                        return(e.IsVirtualUnaired == val);
                    }
                    return(true);
                });
            }

            return(items);
        }
Esempio n. 15
0
        /// <summary>
        /// Applies the paging.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="items">The items.</param>
        /// <returns>IEnumerable{BaseItem}.</returns>
        private IEnumerable <BaseItem> ApplyPaging(GetItems request, IEnumerable <BaseItem> items)
        {
            // Start at
            if (request.StartIndex.HasValue)
            {
                items = items.Skip(request.StartIndex.Value);
            }

            // Return limit
            if (request.Limit.HasValue)
            {
                items = items.Take(request.Limit.Value);
            }

            return(items);
        }
Esempio n. 16
0
        /// <summary>
        /// Gets the items to serialize.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="user">The user.</param>
        /// <returns>IEnumerable{BaseItem}.</returns>
        private async Task <QueryResult <BaseItem> > GetQueryResult(GetItems request, User user)
        {
            var item = string.IsNullOrEmpty(request.ParentId) ?
                       user == null ? _libraryManager.RootFolder : user.RootFolder :
                       _libraryManager.GetItemById(request.ParentId);

            if (string.Equals(request.IncludeItemTypes, "Playlist", StringComparison.OrdinalIgnoreCase))
            {
                //item = user == null ? _libraryManager.RootFolder : user.RootFolder;
            }
            else if (string.Equals(request.IncludeItemTypes, "BoxSet", StringComparison.OrdinalIgnoreCase))
            {
                item = user == null ? _libraryManager.RootFolder : user.RootFolder;
            }

            // Default list type = children

            var folder = item as Folder;

            if (folder == null)
            {
                folder = user == null ? _libraryManager.RootFolder : _libraryManager.GetUserRootFolder();
            }

            if (request.Recursive || !string.IsNullOrEmpty(request.Ids) || user == null)
            {
                return(await folder.GetItems(GetItemsQuery(request, user)).ConfigureAwait(false));
            }

            var userRoot = item as UserRootFolder;

            if (userRoot == null)
            {
                return(await folder.GetItems(GetItemsQuery(request, user)).ConfigureAwait(false));
            }

            IEnumerable <BaseItem> items = folder.GetChildren(user, true);

            var itemsArray = items.ToArray();

            return(new QueryResult <BaseItem>
            {
                Items = itemsArray,
                TotalRecordCount = itemsArray.Length
            });
        }
Esempio n. 17
0
        /// <summary>
        /// Gets the items to serialize.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="user">The user.</param>
        /// <returns>IEnumerable{BaseItem}.</returns>
        /// <exception cref="System.InvalidOperationException"></exception>
        private IEnumerable <BaseItem> GetItemsToSerialize(GetItems request, User user)
        {
            var item = string.IsNullOrEmpty(request.ParentId) ? user.RootFolder : DtoBuilder.GetItemByClientId(request.ParentId, _userManager, _libraryManager, user.Id);

            // Default list type = children

            if (!string.IsNullOrEmpty(request.Ids))
            {
                var idList = request.Ids.Split(',').ToList();

                return(idList.Select(i => DtoBuilder.GetItemByClientId(i, _userManager, _libraryManager, user.Id)));
            }

            if (request.Recursive)
            {
                return(((Folder)item).GetRecursiveChildren(user));
            }

            return(((Folder)item).GetChildren(user, true, request.IndexBy));
        }
Esempio n. 18
0
        /// <summary>
        /// Gets the items.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>Task{ItemsResult}.</returns>
        private ItemsResult GetItems(GetItems request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var items = GetItemsToSerialize(request, user);

            items = items.AsParallel();

            items = ApplyAdditionalFilters(request, items, user);

            // Apply filters
            // Run them starting with the ones that are likely to reduce the list the most
            foreach (var filter in request.GetFilters().OrderByDescending(f => (int)f))
            {
                items = ApplyFilter(items, filter, user, _userDataRepository);
            }

            items = FilterVirtualEpisodes(request, items, user);

            items = items.AsEnumerable();

            items = ApplySearchTerm(request, items);

            items = ApplySortOrder(request, items, user, _libraryManager);

            var itemsArray = items.ToList();

            var pagedItems = ApplyPaging(request, itemsArray);

            var fields = request.GetItemFields().ToList();

            var returnItems = pagedItems.Select(i => _dtoService.GetBaseItemDto(i, fields, user)).ToArray();

            return(new ItemsResult
            {
                TotalRecordCount = itemsArray.Count,
                Items = returnItems
            });
        }
Esempio n. 19
0
        /// <summary>
        /// Gets the items to serialize.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="user">The user.</param>
        /// <returns>IEnumerable{BaseItem}.</returns>
        /// <exception cref="System.InvalidOperationException"></exception>
        private IEnumerable <BaseItem> GetItemsToSerialize(GetItems request, User user)
        {
            var item = string.IsNullOrEmpty(request.ParentId) ? user.RootFolder : _dtoService.GetItemByDtoId(request.ParentId, user.Id);

            // Default list type = children
            IEnumerable <BaseItem> items;

            if (!string.IsNullOrEmpty(request.Ids))
            {
                var idList = request.Ids.Split(',').ToList();

                items = idList.Select(i => _dtoService.GetItemByDtoId(i, user.Id));
            }

            else if (request.Recursive)
            {
                items = ((Folder)item).GetRecursiveChildren(user);
            }
            else
            {
                items = ((Folder)item).GetChildren(user, true, request.IndexBy);
            }

            if (request.IncludeIndexContainers)
            {
                var list = items.ToList();

                var containers = list.Select(i => i.IndexContainer)
                                 .Where(i => i != null);

                list.AddRange(containers);

                return(list.Distinct());
            }

            return(items);
        }
Esempio n. 20
0
        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);
        }
Esempio n. 21
0
        private InternalItemsQuery GetItemsQuery(GetItems request, User user)
        {
            var query = new InternalItemsQuery
            {
                User             = user,
                IsPlayed         = request.IsPlayed,
                MediaTypes       = request.GetMediaTypes(),
                IncludeItemTypes = request.GetIncludeItemTypes(),
                ExcludeItemTypes = request.GetExcludeItemTypes(),
                Recursive        = request.Recursive,
                SortBy           = request.GetOrderBy(),
                SortOrder        = request.SortOrder ?? SortOrder.Ascending,

                Filter = i => ApplyAdditionalFilters(request, i, user, _libraryManager),

                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,
                IsUnidentified          = request.IsUnidentified,
                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(),
                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
            };

            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;
                }
            }

            return(query);
        }
Esempio n. 22
0
        private bool ApplyAdditionalFilters(GetItems 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);
        }
Esempio n. 23
0
        /// <summary>
        /// Applies sort order
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="items">The items.</param>
        /// <param name="user">The user.</param>
        /// <returns>IEnumerable{BaseItem}.</returns>
        private IEnumerable <BaseItem> ApplySortOrder(GetItems request, IEnumerable <BaseItem> items, User user)
        {
            var orderBy = GetOrderBy(request).ToArray();

            return(orderBy.Length == 0 ? items : _libraryManager.Sort(items, user, orderBy, request.SortOrder ?? SortOrder.Ascending));
        }
Esempio n. 24
0
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public async Task <object> Get(GetItems request)
        {
            var result = await GetItems(request).ConfigureAwait(false);

            return(ToOptimizedSerializedResultUsingCache(result));
        }
Esempio n. 25
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);
        }
Esempio n. 26
0
        /// <summary>
        /// Gets the items to serialize.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="user">The user.</param>
        /// <returns>IEnumerable{BaseItem}.</returns>
        private async Task <QueryResult <BaseItem> > GetItemsToSerialize(GetItems request, User user)
        {
            var item = string.IsNullOrEmpty(request.ParentId) ?
                       user == null ? _libraryManager.RootFolder : user.RootFolder :
                       _libraryManager.GetItemById(request.ParentId);

            if (string.Equals(request.IncludeItemTypes, "Playlist", StringComparison.OrdinalIgnoreCase))
            {
                //item = user == null ? _libraryManager.RootFolder : user.RootFolder;
            }
            else if (string.Equals(request.IncludeItemTypes, "BoxSet", StringComparison.OrdinalIgnoreCase))
            {
                item = user == null ? _libraryManager.RootFolder : user.RootFolder;
            }

            // Default list type = children

            if (!string.IsNullOrEmpty(request.Ids))
            {
                request.Recursive = true;
                var query  = GetItemsQuery(request, user);
                var result = await((Folder)item).GetItems(query).ConfigureAwait(false);

                if (string.IsNullOrWhiteSpace(request.SortBy))
                {
                    var ids = query.ItemIds.ToList();

                    // Try to preserve order
                    result.Items = result.Items.OrderBy(i => ids.IndexOf(i.Id.ToString("N"))).ToArray();
                }

                return(result);
            }

            if (request.Recursive)
            {
                return(await((Folder)item).GetItems(GetItemsQuery(request, user)).ConfigureAwait(false));
            }

            if (user == null)
            {
                return(await((Folder)item).GetItems(GetItemsQuery(request, null)).ConfigureAwait(false));
            }

            var userRoot = item as UserRootFolder;

            if (userRoot == null)
            {
                return(await((Folder)item).GetItems(GetItemsQuery(request, user)).ConfigureAwait(false));
            }

            IEnumerable <BaseItem> items = ((Folder)item).GetChildren(user, true);

            var itemsArray = items.ToArray();

            return(new QueryResult <BaseItem>
            {
                Items = itemsArray,
                TotalRecordCount = itemsArray.Length
            });
        }
Esempio n. 27
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)
        {
            var imageTypes = GetImageTypes(request).ToArray();

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

            // Exclude item types
            var excludeItemTypes = request.ExcludeItemTypes;

            if (!string.IsNullOrEmpty(excludeItemTypes))
            {
                var vals = excludeItemTypes.Split(',');
                items = items.Where(f => !vals.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase));
            }

            var includeItemTypes = request.IncludeItemTypes;

            if (!string.IsNullOrEmpty(includeItemTypes))
            {
                var vals = includeItemTypes.Split(',');
                items = items.Where(f => vals.Contains(f.GetType().Name, StringComparer.OrdinalIgnoreCase));
            }

            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 personType = request.PersonType;

                items = !string.IsNullOrEmpty(personType)
                            ? items.Where(item => item.People != null && item.People.Any(p => p.Name.Equals(personName, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(personType, StringComparison.OrdinalIgnoreCase)))
                            : items.Where(item => item.People != null && item.People.Any(p => p.Name.Equals(personName, StringComparison.OrdinalIgnoreCase)));
            }

            return(items);
        }
Esempio n. 28
0
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public object Get(GetItems request)
        {
            var result = GetItems(request).Result;

            return(ToOptimizedResult(result));
        }
Esempio n. 29
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);
        }
Esempio n. 30
0
        /// <summary>
        /// Applies sort order
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="items">The items.</param>
        /// <param name="user">The user.</param>
        /// <param name="libraryManager">The library manager.</param>
        /// <returns>IEnumerable{BaseItem}.</returns>
        internal static IEnumerable <BaseItem> ApplySortOrder(GetItems request, IEnumerable <BaseItem> items, User user, ILibraryManager libraryManager)
        {
            var orderBy = request.GetOrderBy().ToArray();

            return(orderBy.Length == 0 ? items : libraryManager.Sort(items, user, orderBy, request.SortOrder ?? SortOrder.Ascending));
        }