コード例 #1
0
ファイル: ArtistsValidator.cs プロジェクト: vvuk/Emby
        /// <summary>
        /// Runs the specified progress.
        /// </summary>
        /// <param name="progress">The progress.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        public async Task Run(IProgress <double> progress, CancellationToken cancellationToken)
        {
            var names = _itemRepo.GetAllArtistNames();

            var numComplete = 0;
            var count       = names.Count;

            foreach (var name in names)
            {
                try
                {
                    var item = _libraryManager.GetArtist(name);

                    await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    // Don't clutter the log
                    break;
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error refreshing {0}", ex, name);
                }

                numComplete++;
                double percent = numComplete;
                percent /= count;
                percent *= 100;

                progress.Report(percent);
            }

            progress.Report(100);
        }
コード例 #2
0
        /// <summary>
        /// Gets all artists.
        /// </summary>
        /// <param name="allItems">All items.</param>
        /// <returns>Task{Artist[]}.</returns>
        private Task <Artist[]> GetAllArtists(IEnumerable <BaseItem> allItems)
        {
            var itemsList = allItems.OfType <Audio>().ToList();

            var tasks = itemsList
                        .SelectMany(i =>
            {
                var list = new List <string>();

                if (!string.IsNullOrEmpty(i.AlbumArtist))
                {
                    list.Add(i.AlbumArtist);
                }
                if (!string.IsNullOrEmpty(i.Artist))
                {
                    list.Add(i.Artist);
                }

                return(list);
            })
                        .Distinct(StringComparer.OrdinalIgnoreCase)
                        .Select(i => _libraryManager.GetArtist(i));

            return(Task.WhenAll(tasks));
        }
コード例 #3
0
ファイル: ArtistsValidator.cs プロジェクト: ximliu/jellyfin
        /// <summary>
        /// Runs the specified progress.
        /// </summary>
        /// <param name="progress">The progress.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        public async Task Run(IProgress <double> progress, CancellationToken cancellationToken)
        {
            var names = _itemRepo.GetAllArtistNames();

            var numComplete = 0;
            var count       = names.Count;

            foreach (var name in names)
            {
                try
                {
                    var item = _libraryManager.GetArtist(name);

                    await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    // Don't clutter the log
                    throw;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error refreshing {ArtistName}", name);
                }

                numComplete++;
                double percent = numComplete;
                percent /= count;
                percent *= 100;

                progress.Report(percent);
            }

            var deadEntities = _libraryManager.GetItemList(new InternalItemsQuery
            {
                IncludeItemTypes = new[] { BaseItemKind.MusicArtist },
                IsDeadArtist     = true,
                IsLocked         = false
            }).Cast <MusicArtist>().ToList();

            foreach (var item in deadEntities)
            {
                if (!item.IsAccessedByName)
                {
                    continue;
                }

                _logger.LogInformation("Deleting dead {2} {0} {1}.", item.Id.ToString("N", CultureInfo.InvariantCulture), item.Name, item.GetType().Name);

                _libraryManager.DeleteItem(
                    item,
                    new DeleteOptions
                {
                    DeleteFileLocation = false
                },
                    false);
            }

            progress.Report(100);
        }
コード例 #4
0
ファイル: InstantMixService.cs プロジェクト: xTraXx/FreeEmby
        public Task <object> Get(GetInstantMixFromArtist request)
        {
            var user   = _userManager.GetUserById(request.UserId);
            var artist = _libraryManager.GetArtist(request.Name);

            var items = _musicManager.GetInstantMixFromArtist(artist, user);

            return(GetResult(items, user, request));
        }
コード例 #5
0
ファイル: InstantMixService.cs プロジェクト: sytone/Emby
        public Task <object> Get(GetInstantMixFromArtist request)
        {
            var user   = _userManager.GetUserById(request.UserId);
            var artist = _libraryManager.GetArtist(request.Name, new DtoOptions(false));

            var dtoOptions = GetDtoOptions(_authContext, request);

            var items = _musicManager.GetInstantMixFromArtist(artist, user, dtoOptions);

            return(GetResult(items, user, request, dtoOptions));
        }
コード例 #6
0
        /// <summary>
        /// Gets all artists.
        /// </summary>
        /// <param name="allSongs">All songs.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="progress">The progress.</param>
        /// <returns>Task{Artist[]}.</returns>
        private async Task <List <Artist> > GetAllArtists(IEnumerable <Audio> allSongs, CancellationToken cancellationToken, IProgress <double> progress)
        {
            var allArtists = allSongs
                             .SelectMany(i =>
            {
                var list = new List <string>();

                if (!string.IsNullOrEmpty(i.AlbumArtist))
                {
                    list.Add(i.AlbumArtist);
                }
                list.AddRange(i.Artists);

                return(list);
            })
                             .Distinct(StringComparer.OrdinalIgnoreCase)
                             .ToList();

            var returnArtists = new List <Artist>(allArtists.Count);

            var numComplete = 0;
            var numArtists  = allArtists.Count;

            foreach (var artist in allArtists)
            {
                cancellationToken.ThrowIfCancellationRequested();

                try
                {
                    var artistItem = _libraryManager.GetArtist(artist);

                    await artistItem.RefreshMetadata(cancellationToken).ConfigureAwait(false);

                    returnArtists.Add(artistItem);
                }
                catch (IOException ex)
                {
                    _logger.ErrorException("Error validating Artist {0}", ex, artist);
                }

                // Update progress
                numComplete++;
                double percent = numComplete;
                percent /= numArtists;

                progress.Report(100 * percent);
            }

            return(returnArtists);
        }
コード例 #7
0
ファイル: BaseApiService.cs プロジェクト: bassbum37/jellyfin
        protected MusicArtist GetArtist(string name, ILibraryManager libraryManager, DtoOptions dtoOptions)
        {
            if (name.IndexOf(BaseItem.SlugChar) != -1)
            {
                var result = GetItemFromSlugName <MusicArtist>(libraryManager, name, dtoOptions);

                if (result != null)
                {
                    return(result);
                }
            }

            return(libraryManager.GetArtist(name, dtoOptions));
        }
コード例 #8
0
        private QueryResult <BaseItem> GetMusicAlbumArtists(Folder parent, User user, UserItemsQuery query)
        {
            var artists = GetRecursiveChildren(parent, user, new[] { CollectionType.Music })
                          .Where(i => !i.IsFolder)
                          .OfType <IHasAlbumArtist>()
                          .SelectMany(i => i.AlbumArtists)
                          .Distinct(StringComparer.OrdinalIgnoreCase)
                          .Select(i =>
            {
                try
                {
                    return(_libraryManager.GetArtist(i));
                }
                catch
                {
                    // Already logged at lower levels
                    return(null);
                }
            })
                          .Where(i => i != null);

            return(GetResult(artists, query));
        }
コード例 #9
0
ファイル: MusicManager.cs プロジェクト: wilhil/MediaBrowser
        public IEnumerable <Audio> GetInstantMixFromArtist(string name, User user)
        {
            var artist = _libraryManager.GetArtist(name);

            var genres = user.RootFolder
                         .GetRecursiveChildren(user)
                         .OfType <Audio>()
                         .Where(i => i.HasArtist(name))
                         .SelectMany(i => i.Genres)
                         .Concat(artist.Genres)
                         .Distinct(StringComparer.OrdinalIgnoreCase);

            return(GetInstantMixFromGenres(genres, user));
        }
コード例 #10
0
        public ActionResult <BaseItemDto> GetArtistByName([FromRoute, Required] string name, [FromQuery] Guid?userId)
        {
            var dtoOptions = new DtoOptions().AddClientFields(Request);

            var item = _libraryManager.GetArtist(name, dtoOptions);

            if (userId.HasValue && !userId.Equals(Guid.Empty))
            {
                var user = _userManager.GetUserById(userId.Value);

                return(_dtoService.GetBaseItemDto(item, dtoOptions, user));
            }

            return(_dtoService.GetBaseItemDto(item, dtoOptions));
        }
コード例 #11
0
        protected MusicArtist GetArtist(string name, ILibraryManager libraryManager)
        {
            if (name.IndexOf(BaseItem.SlugChar) != -1)
            {
                var result = libraryManager.GetItemList(new InternalItemsQuery
                {
                    SlugName         = name,
                    IncludeItemTypes = new[] { typeof(MusicArtist).Name }
                }).OfType <MusicArtist>().FirstOrDefault();

                if (result != null)
                {
                    return(result);
                }
            }

            return(libraryManager.GetArtist(name));
        }
コード例 #12
0
        /// <summary>
        /// Runs the specified progress.
        /// </summary>
        /// <param name="progress">The progress.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        public async Task Run(IProgress <double> progress, CancellationToken cancellationToken)
        {
            var allSongs = _libraryManager.RootFolder
                           .GetRecursiveChildren(i => !i.IsFolder && (i is IHasArtist))
                           .Cast <IHasArtist>()
                           .ToList();

            var allArtists = allSongs.SelectMany(i => i.AllArtists)
                             .Distinct(StringComparer.OrdinalIgnoreCase)
                             .ToList();

            var returnArtists = new List <MusicArtist>(allArtists.Count);

            var numComplete = 0;
            var numArtists  = allArtists.Count;

            foreach (var artist in allArtists)
            {
                cancellationToken.ThrowIfCancellationRequested();

                try
                {
                    var artistItem = _libraryManager.GetArtist(artist);

                    await artistItem.RefreshMetadata(cancellationToken).ConfigureAwait(false);

                    returnArtists.Add(artistItem);
                }
                catch (IOException ex)
                {
                    _logger.ErrorException("Error validating Artist {0}", ex, artist);
                }

                // Update progress
                numComplete++;
                double percent = numComplete;
                percent /= numArtists;

                progress.Report(100 * percent);
            }
        }
コード例 #13
0
        /// <summary>
        /// Gets all artists.
        /// </summary>
        /// <param name="allSongs">All songs.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="progress">The progress.</param>
        /// <returns>Task{Artist[]}.</returns>
        private async Task <List <MusicArtist> > GetAllArtists(IEnumerable <Audio> allSongs, CancellationToken cancellationToken, IProgress <double> progress)
        {
            var allArtists = _libraryManager.GetAllArtists(allSongs)
                             .ToList();

            var returnArtists = new List <MusicArtist>(allArtists.Count);

            var numComplete = 0;
            var numArtists  = allArtists.Count;

            foreach (var artist in allArtists)
            {
                cancellationToken.ThrowIfCancellationRequested();

                try
                {
                    var artistItem = _libraryManager.GetArtist(artist);

                    await artistItem.RefreshMetadata(cancellationToken).ConfigureAwait(false);

                    returnArtists.Add(artistItem);
                }
                catch (IOException ex)
                {
                    _logger.ErrorException("Error validating Artist {0}", ex, artist);
                }

                // Update progress
                numComplete++;
                double percent = numComplete;
                percent /= numArtists;

                progress.Report(100 * percent);
            }

            return(returnArtists);
        }
コード例 #14
0
ファイル: DtoService.cs プロジェクト: zindsia/jellyfin
        /// <summary>
        /// Sets simple property values on a DTOBaseItem
        /// </summary>
        /// <param name="dto">The dto.</param>
        /// <param name="item">The item.</param>
        /// <param name="owner">The owner.</param>
        /// <param name="options">The options.</param>
        private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, DtoOptions options)
        {
            if (options.ContainsField(ItemFields.DateCreated))
            {
                dto.DateCreated = item.DateCreated;
            }

            if (options.ContainsField(ItemFields.Settings))
            {
                dto.LockedFields   = item.LockedFields;
                dto.LockData       = item.IsLocked;
                dto.ForcedSortName = item.ForcedSortName;
            }
            dto.Container = item.Container;

            dto.EndDate = item.EndDate;

            if (options.ContainsField(ItemFields.ExternalUrls))
            {
                dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
            }

            if (options.ContainsField(ItemFields.Tags))
            {
                dto.Tags = item.Tags;
            }

            var hasAspectRatio = item as IHasAspectRatio;

            if (hasAspectRatio != null)
            {
                dto.AspectRatio = hasAspectRatio.AspectRatio;
            }

            var backdropLimit = options.GetImageLimit(ImageType.Backdrop);

            if (backdropLimit > 0)
            {
                dto.BackdropImageTags = GetImageTags(item, item.GetImages(ImageType.Backdrop).Take(backdropLimit).ToList());
            }

            if (options.ContainsField(ItemFields.ScreenshotImageTags))
            {
                var screenshotLimit = options.GetImageLimit(ImageType.Screenshot);
                if (screenshotLimit > 0)
                {
                    dto.ScreenshotImageTags = GetImageTags(item, item.GetImages(ImageType.Screenshot).Take(screenshotLimit).ToList());
                }
            }

            if (options.ContainsField(ItemFields.Genres))
            {
                dto.Genres = item.Genres;
                AttachGenreItems(dto, item);
            }

            if (options.EnableImages)
            {
                dto.ImageTags = new Dictionary <ImageType, string>();

                // Prevent implicitly captured closure
                var currentItem = item;
                foreach (var image in currentItem.ImageInfos.Where(i => !currentItem.AllowsMultipleImages(i.Type))
                         .ToList())
                {
                    if (options.GetImageLimit(image.Type) > 0)
                    {
                        var tag = GetImageCacheTag(item, image);

                        if (tag != null)
                        {
                            dto.ImageTags[image.Type] = tag;
                        }
                    }
                }
            }

            dto.Id                = item.Id;
            dto.IndexNumber       = item.IndexNumber;
            dto.ParentIndexNumber = item.ParentIndexNumber;

            if (item.IsFolder)
            {
                dto.IsFolder = true;
            }
            else if (item is IHasMediaSources)
            {
                dto.IsFolder = false;
            }

            dto.MediaType = item.MediaType;

            if (!(item is LiveTvProgram))
            {
                dto.LocationType = item.LocationType;
            }

            dto.Audio = item.Audio;

            if (options.ContainsField(ItemFields.Settings))
            {
                dto.PreferredMetadataCountryCode = item.PreferredMetadataCountryCode;
                dto.PreferredMetadataLanguage    = item.PreferredMetadataLanguage;
            }

            dto.CriticRating = item.CriticRating;

            var hasDisplayOrder = item as IHasDisplayOrder;

            if (hasDisplayOrder != null)
            {
                dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
            }

            var hasCollectionType = item as IHasCollectionType;

            if (hasCollectionType != null)
            {
                dto.CollectionType = hasCollectionType.CollectionType;
            }

            if (options.ContainsField(ItemFields.RemoteTrailers))
            {
                dto.RemoteTrailers = item.RemoteTrailers;
            }

            dto.Name           = item.Name;
            dto.OfficialRating = item.OfficialRating;

            if (options.ContainsField(ItemFields.Overview))
            {
                dto.Overview = item.Overview;
            }

            if (options.ContainsField(ItemFields.OriginalTitle))
            {
                dto.OriginalTitle = item.OriginalTitle;
            }

            if (options.ContainsField(ItemFields.ParentId))
            {
                dto.ParentId = item.DisplayParentId;
            }

            AddInheritedImages(dto, item, options, owner);

            if (options.ContainsField(ItemFields.Path))
            {
                dto.Path = GetMappedPath(item, owner);
            }

            if (options.ContainsField(ItemFields.EnableMediaSourceDisplay))
            {
                dto.EnableMediaSourceDisplay = item.EnableMediaSourceDisplay;
            }

            dto.PremiereDate   = item.PremiereDate;
            dto.ProductionYear = item.ProductionYear;

            if (options.ContainsField(ItemFields.ProviderIds))
            {
                dto.ProviderIds = item.ProviderIds;
            }

            dto.RunTimeTicks = item.RunTimeTicks;

            if (options.ContainsField(ItemFields.SortName))
            {
                dto.SortName = item.SortName;
            }

            if (options.ContainsField(ItemFields.CustomRating))
            {
                dto.CustomRating = item.CustomRating;
            }

            if (options.ContainsField(ItemFields.Taglines))
            {
                if (!string.IsNullOrEmpty(item.Tagline))
                {
                    dto.Taglines = new string[] { item.Tagline };
                }

                if (dto.Taglines == null)
                {
                    dto.Taglines = Array.Empty <string>();
                }
            }

            dto.Type = item.GetClientTypeName();
            if ((item.CommunityRating ?? 0) > 0)
            {
                dto.CommunityRating = item.CommunityRating;
            }

            var supportsPlaceHolders = item as ISupportsPlaceHolders;

            if (supportsPlaceHolders != null && supportsPlaceHolders.IsPlaceHolder)
            {
                dto.IsPlaceHolder = supportsPlaceHolders.IsPlaceHolder;
            }

            // Add audio info
            var audio = item as Audio;

            if (audio != null)
            {
                dto.Album = audio.Album;
                if (audio.ExtraType.HasValue)
                {
                    dto.ExtraType = audio.ExtraType.Value.ToString();
                }

                var albumParent = audio.AlbumEntity;

                if (albumParent != null)
                {
                    dto.AlbumId = albumParent.Id;

                    dto.AlbumPrimaryImageTag = GetImageCacheTag(albumParent, ImageType.Primary);
                }

                //if (options.ContainsField(ItemFields.MediaSourceCount))
                //{
                // Songs always have one
                //}
            }

            var hasArtist = item as IHasArtist;

            if (hasArtist != null)
            {
                dto.Artists = hasArtist.Artists;

                //var artistItems = _libraryManager.GetArtists(new InternalItemsQuery
                //{
                //    EnableTotalRecordCount = false,
                //    ItemIds = new[] { item.Id.ToString("N") }
                //});

                //dto.ArtistItems = artistItems.Items
                //    .Select(i =>
                //    {
                //        var artist = i.Item1;
                //        return new NameIdPair
                //        {
                //            Name = artist.Name,
                //            Id = artist.Id.ToString("N")
                //        };
                //    })
                //    .ToList();

                // Include artists that are not in the database yet, e.g., just added via metadata editor
                //var foundArtists = artistItems.Items.Select(i => i.Item1.Name).ToList();
                dto.ArtistItems = hasArtist.Artists
                                  //.Except(foundArtists, new DistinctNameComparer())
                                  .Select(i =>
                {
                    // This should not be necessary but we're seeing some cases of it
                    if (string.IsNullOrEmpty(i))
                    {
                        return(null);
                    }

                    var artist = _libraryManager.GetArtist(i, new DtoOptions(false)
                    {
                        EnableImages = false
                    });
                    if (artist != null)
                    {
                        return(new NameGuidPair
                        {
                            Name = artist.Name,
                            Id = artist.Id
                        });
                    }

                    return(null);
                }).Where(i => i != null).ToArray();
            }

            var hasAlbumArtist = item as IHasAlbumArtist;

            if (hasAlbumArtist != null)
            {
                dto.AlbumArtist = hasAlbumArtist.AlbumArtists.FirstOrDefault();

                //var artistItems = _libraryManager.GetAlbumArtists(new InternalItemsQuery
                //{
                //    EnableTotalRecordCount = false,
                //    ItemIds = new[] { item.Id.ToString("N") }
                //});

                //dto.AlbumArtists = artistItems.Items
                //    .Select(i =>
                //    {
                //        var artist = i.Item1;
                //        return new NameIdPair
                //        {
                //            Name = artist.Name,
                //            Id = artist.Id.ToString("N")
                //        };
                //    })
                //    .ToList();

                dto.AlbumArtists = hasAlbumArtist.AlbumArtists
                                   //.Except(foundArtists, new DistinctNameComparer())
                                   .Select(i =>
                {
                    // This should not be necessary but we're seeing some cases of it
                    if (string.IsNullOrEmpty(i))
                    {
                        return(null);
                    }

                    var artist = _libraryManager.GetArtist(i, new DtoOptions(false)
                    {
                        EnableImages = false
                    });
                    if (artist != null)
                    {
                        return(new NameGuidPair
                        {
                            Name = artist.Name,
                            Id = artist.Id
                        });
                    }

                    return(null);
                }).Where(i => i != null).ToArray();
            }

            // Add video info
            var video = item as Video;

            if (video != null)
            {
                dto.VideoType     = video.VideoType;
                dto.Video3DFormat = video.Video3DFormat;
                dto.IsoType       = video.IsoType;

                if (video.HasSubtitles)
                {
                    dto.HasSubtitles = video.HasSubtitles;
                }

                if (video.AdditionalParts.Length != 0)
                {
                    dto.PartCount = video.AdditionalParts.Length + 1;
                }

                if (options.ContainsField(ItemFields.MediaSourceCount))
                {
                    var mediaSourceCount = video.MediaSourceCount;
                    if (mediaSourceCount != 1)
                    {
                        dto.MediaSourceCount = mediaSourceCount;
                    }
                }

                if (options.ContainsField(ItemFields.Chapters))
                {
                    dto.Chapters = _itemRepo.GetChapters(item);
                }

                if (video.ExtraType.HasValue)
                {
                    dto.ExtraType = video.ExtraType.Value.ToString();
                }
            }

            if (options.ContainsField(ItemFields.MediaStreams))
            {
                // Add VideoInfo
                var iHasMediaSources = item as IHasMediaSources;

                if (iHasMediaSources != null)
                {
                    MediaStream[] mediaStreams;

                    if (dto.MediaSources != null && dto.MediaSources.Length > 0)
                    {
                        if (item.SourceType == SourceType.Channel)
                        {
                            mediaStreams = dto.MediaSources[0].MediaStreams.ToArray();
                        }
                        else
                        {
                            mediaStreams = dto.MediaSources.Where(i => string.Equals(i.Id, item.Id.ToString("N"), StringComparison.OrdinalIgnoreCase))
                                           .SelectMany(i => i.MediaStreams)
                                           .ToArray();
                        }
                    }
                    else
                    {
                        mediaStreams = _mediaSourceManager().GetStaticMediaSources(item, true).First().MediaStreams.ToArray();
                    }

                    dto.MediaStreams = mediaStreams;
                }
            }

            BaseItem[] allExtras = null;

            if (options.ContainsField(ItemFields.SpecialFeatureCount))
            {
                if (allExtras == null)
                {
                    allExtras = item.GetExtras().ToArray();
                }

                dto.SpecialFeatureCount = allExtras.Count(i => i.ExtraType.HasValue && BaseItem.DisplayExtraTypes.Contains(i.ExtraType.Value));
            }

            if (options.ContainsField(ItemFields.LocalTrailerCount))
            {
                if (allExtras == null)
                {
                    allExtras = item.GetExtras().ToArray();
                }

                dto.LocalTrailerCount = allExtras.Count(i => i.ExtraType.HasValue && i.ExtraType.Value == ExtraType.Trailer);
            }

            // Add EpisodeInfo
            var episode = item as Episode;

            if (episode != null)
            {
                dto.IndexNumberEnd = episode.IndexNumberEnd;
                dto.SeriesName     = episode.SeriesName;

                if (options.ContainsField(ItemFields.SpecialEpisodeNumbers))
                {
                    dto.AirsAfterSeasonNumber   = episode.AirsAfterSeasonNumber;
                    dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
                    dto.AirsBeforeSeasonNumber  = episode.AirsBeforeSeasonNumber;
                }

                dto.SeasonName = episode.SeasonName;
                dto.SeasonId   = episode.SeasonId;
                dto.SeriesId   = episode.SeriesId;

                Series episodeSeries = null;

                //if (options.ContainsField(ItemFields.SeriesPrimaryImage))
                {
                    episodeSeries = episodeSeries ?? episode.Series;
                    if (episodeSeries != null)
                    {
                        dto.SeriesPrimaryImageTag = GetImageCacheTag(episodeSeries, ImageType.Primary);
                    }
                }

                if (options.ContainsField(ItemFields.SeriesStudio))
                {
                    episodeSeries = episodeSeries ?? episode.Series;
                    if (episodeSeries != null)
                    {
                        dto.SeriesStudio = episodeSeries.Studios.FirstOrDefault();
                    }
                }
            }

            // Add SeriesInfo
            var series = item as Series;

            if (series != null)
            {
                dto.AirDays = series.AirDays;
                dto.AirTime = series.AirTime;
                dto.Status  = series.Status.HasValue ? series.Status.Value.ToString() : null;
            }

            // Add SeasonInfo
            var season = item as Season;

            if (season != null)
            {
                dto.SeriesName = season.SeriesName;
                dto.SeriesId   = season.SeriesId;

                series = null;

                if (options.ContainsField(ItemFields.SeriesStudio))
                {
                    series = series ?? season.Series;
                    if (series != null)
                    {
                        dto.SeriesStudio = series.Studios.FirstOrDefault();
                    }
                }

                //if (options.ContainsField(ItemFields.SeriesPrimaryImage))
                {
                    series = series ?? season.Series;
                    if (series != null)
                    {
                        dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
                    }
                }
            }

            var musicVideo = item as MusicVideo;

            if (musicVideo != null)
            {
                SetMusicVideoProperties(dto, musicVideo);
            }

            var book = item as Book;

            if (book != null)
            {
                SetBookProperties(dto, book);
            }

            if (options.ContainsField(ItemFields.ProductionLocations))
            {
                if (item.ProductionLocations.Length > 0 || item is Movie)
                {
                    dto.ProductionLocations = item.ProductionLocations;
                }
            }

            if (options.ContainsField(ItemFields.Width))
            {
                var width = item.Width;
                if (width > 0)
                {
                    dto.Width = width;
                }
            }

            if (options.ContainsField(ItemFields.Height))
            {
                var height = item.Height;
                if (height > 0)
                {
                    dto.Height = height;
                }
            }

            if (options.ContainsField(ItemFields.IsHD))
            {
                // Compatibility
                if (item.IsHD)
                {
                    dto.IsHD = true;
                }
            }

            var photo = item as Photo;

            if (photo != null)
            {
                SetPhotoProperties(dto, photo);
            }

            dto.ChannelId = item.ChannelId;

            if (item.SourceType == SourceType.Channel)
            {
                var channel = _libraryManager.GetItemById(item.ChannelId);
                if (channel != null)
                {
                    dto.ChannelName = channel.Name;
                }
            }
        }
コード例 #15
0
 protected MusicArtist GetArtist(string name, ILibraryManager libraryManager)
 {
     return(libraryManager.GetArtist(DeSlugArtistName(name, libraryManager)));
 }
コード例 #16
0
        /// <summary>
        /// Gets the search hints.
        /// </summary>
        /// <param name="inputItems">The input items.</param>
        /// <param name="searchTerm">The search term.</param>
        /// <returns>IEnumerable{SearchHintResult}.</returns>
        /// <exception cref="System.ArgumentNullException">searchTerm</exception>
        public async Task <IEnumerable <SearchHintInfo> > GetSearchHints(IEnumerable <BaseItem> inputItems, string searchTerm)
        {
            if (string.IsNullOrEmpty(searchTerm))
            {
                throw new ArgumentNullException("searchTerm");
            }

            var terms = GetWords(searchTerm);

            var hints = new List <Tuple <BaseItem, string, int> >();

            var items = inputItems.Where(i => !(i is MusicArtist)).ToList();

            // Add search hints based on item name
            hints.AddRange(items.Where(i => !string.IsNullOrEmpty(i.Name)).Select(item =>
            {
                var index = GetIndex(item.Name, searchTerm, terms);

                return(new Tuple <BaseItem, string, int>(item, index.Item1, index.Item2));
            }));

            // Find artists
            var artists = items.OfType <Audio>()
                          .SelectMany(i =>
            {
                var list = new List <string>();

                if (!string.IsNullOrEmpty(i.AlbumArtist))
                {
                    list.Add(i.AlbumArtist);
                }
                list.AddRange(i.Artists);

                return(list);
            })
                          .Distinct(StringComparer.OrdinalIgnoreCase)
                          .ToList();

            foreach (var item in artists)
            {
                var index = GetIndex(item, searchTerm, terms);

                if (index.Item2 != -1)
                {
                    try
                    {
                        var artist = await _libraryManager.GetArtist(item).ConfigureAwait(false);

                        hints.Add(new Tuple <BaseItem, string, int>(artist, index.Item1, index.Item2));
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorException("Error getting {0}", ex, item);
                    }
                }
            }

            // Find genres, from non-audio items
            var genres = items.Where(i => !(i is IHasMusicGenres) && !(i is Game))
                         .SelectMany(i => i.Genres)
                         .Where(i => !string.IsNullOrEmpty(i))
                         .Distinct(StringComparer.OrdinalIgnoreCase)
                         .ToList();

            foreach (var item in genres)
            {
                var index = GetIndex(item, searchTerm, terms);

                if (index.Item2 != -1)
                {
                    try
                    {
                        var genre = await _libraryManager.GetGenre(item).ConfigureAwait(false);

                        hints.Add(new Tuple <BaseItem, string, int>(genre, index.Item1, index.Item2));
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorException("Error getting {0}", ex, item);
                    }
                }
            }

            // Find music genres
            var musicGenres = items.Where(i => i is IHasMusicGenres)
                              .SelectMany(i => i.Genres)
                              .Where(i => !string.IsNullOrEmpty(i))
                              .Distinct(StringComparer.OrdinalIgnoreCase)
                              .ToList();

            foreach (var item in musicGenres)
            {
                var index = GetIndex(item, searchTerm, terms);

                if (index.Item2 != -1)
                {
                    try
                    {
                        var genre = await _libraryManager.GetMusicGenre(item).ConfigureAwait(false);

                        hints.Add(new Tuple <BaseItem, string, int>(genre, index.Item1, index.Item2));
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorException("Error getting {0}", ex, item);
                    }
                }
            }

            // Find music genres
            var gameGenres = items.OfType <Game>()
                             .SelectMany(i => i.Genres)
                             .Where(i => !string.IsNullOrEmpty(i))
                             .Distinct(StringComparer.OrdinalIgnoreCase)
                             .ToList();

            foreach (var item in gameGenres)
            {
                var index = GetIndex(item, searchTerm, terms);

                if (index.Item2 != -1)
                {
                    try
                    {
                        var genre = await _libraryManager.GetGameGenre(item).ConfigureAwait(false);

                        hints.Add(new Tuple <BaseItem, string, int>(genre, index.Item1, index.Item2));
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorException("Error getting {0}", ex, item);
                    }
                }
            }

            // Find studios
            var studios = items.SelectMany(i => i.Studios)
                          .Where(i => !string.IsNullOrEmpty(i))
                          .Distinct(StringComparer.OrdinalIgnoreCase)
                          .ToList();

            foreach (var item in studios)
            {
                var index = GetIndex(item, searchTerm, terms);

                if (index.Item2 != -1)
                {
                    try
                    {
                        var studio = await _libraryManager.GetStudio(item).ConfigureAwait(false);

                        hints.Add(new Tuple <BaseItem, string, int>(studio, index.Item1, index.Item2));
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorException("Error getting {0}", ex, item);
                    }
                }
            }

            // Find persons
            var persons = items.SelectMany(i => i.People)
                          .Select(i => i.Name)
                          .Where(i => !string.IsNullOrEmpty(i))
                          .Distinct(StringComparer.OrdinalIgnoreCase)
                          .ToList();

            foreach (var item in persons)
            {
                var index = GetIndex(item, searchTerm, terms);

                if (index.Item2 != -1)
                {
                    try
                    {
                        var person = await _libraryManager.GetPerson(item).ConfigureAwait(false);

                        hints.Add(new Tuple <BaseItem, string, int>(person, index.Item1, index.Item2));
                    }
                    catch (Exception ex)
                    {
                        _logger.ErrorException("Error getting {0}", ex, item);
                    }
                }
            }

            return(hints.Where(i => i.Item3 >= 0).OrderBy(i => i.Item3).Select(i => new SearchHintInfo
            {
                Item = i.Item1,
                MatchedTerm = i.Item2
            }));
        }
コード例 #17
0
ファイル: SearchEngine.cs プロジェクト: mckartha/MediaBrowser
        /// <summary>
        /// Gets the search hints.
        /// </summary>
        /// <param name="inputItems">The input items.</param>
        /// <param name="query">The query.</param>
        /// <returns>IEnumerable{SearchHintResult}.</returns>
        /// <exception cref="System.ArgumentNullException">searchTerm</exception>
        private Task <IEnumerable <SearchHintInfo> > GetSearchHints(IEnumerable <BaseItem> inputItems, SearchQuery query)
        {
            var searchTerm = query.SearchTerm;

            if (string.IsNullOrWhiteSpace(searchTerm))
            {
                throw new ArgumentNullException("searchTerm");
            }

            var terms = GetWords(searchTerm);

            var hints = new List <Tuple <BaseItem, string, int> >();

            var items = inputItems.Where(i => !(i is MusicArtist)).ToList();

            if (query.IncludeMedia)
            {
                // Add search hints based on item name
                hints.AddRange(items.Where(i => !string.IsNullOrWhiteSpace(i.Name)).Select(item =>
                {
                    var index = GetIndex(item.Name, searchTerm, terms);

                    return(new Tuple <BaseItem, string, int>(item, index.Item1, index.Item2));
                }));
            }

            if (query.IncludeArtists)
            {
                // Find artists
                var artists = items.OfType <Audio>()
                              .SelectMany(i => i.AllArtists)
                              .Where(i => !string.IsNullOrWhiteSpace(i))
                              .Distinct(StringComparer.OrdinalIgnoreCase)
                              .ToList();

                foreach (var item in artists)
                {
                    var index = GetIndex(item, searchTerm, terms);

                    if (index.Item2 != -1)
                    {
                        try
                        {
                            var artist = _libraryManager.GetArtist(item);

                            hints.Add(new Tuple <BaseItem, string, int>(artist, index.Item1, index.Item2));
                        }
                        catch (Exception ex)
                        {
                            _logger.ErrorException("Error getting {0}", ex, item);
                        }
                    }
                }
            }

            if (query.IncludeGenres)
            {
                // Find genres, from non-audio items
                var genres = items.Where(i => !(i is IHasMusicGenres) && !(i is Game))
                             .SelectMany(i => i.Genres)
                             .Where(i => !string.IsNullOrWhiteSpace(i))
                             .Distinct(StringComparer.OrdinalIgnoreCase)
                             .ToList();

                foreach (var item in genres)
                {
                    var index = GetIndex(item, searchTerm, terms);

                    if (index.Item2 != -1)
                    {
                        try
                        {
                            var genre = _libraryManager.GetGenre(item);

                            hints.Add(new Tuple <BaseItem, string, int>(genre, index.Item1, index.Item2));
                        }
                        catch (Exception ex)
                        {
                            _logger.ErrorException("Error getting {0}", ex, item);
                        }
                    }
                }

                // Find music genres
                var musicGenres = items.Where(i => i is IHasMusicGenres)
                                  .SelectMany(i => i.Genres)
                                  .Where(i => !string.IsNullOrWhiteSpace(i))
                                  .Distinct(StringComparer.OrdinalIgnoreCase)
                                  .ToList();

                foreach (var item in musicGenres)
                {
                    var index = GetIndex(item, searchTerm, terms);

                    if (index.Item2 != -1)
                    {
                        try
                        {
                            var genre = _libraryManager.GetMusicGenre(item);

                            hints.Add(new Tuple <BaseItem, string, int>(genre, index.Item1, index.Item2));
                        }
                        catch (Exception ex)
                        {
                            _logger.ErrorException("Error getting {0}", ex, item);
                        }
                    }
                }

                // Find music genres
                var gameGenres = items.OfType <Game>()
                                 .SelectMany(i => i.Genres)
                                 .Where(i => !string.IsNullOrWhiteSpace(i))
                                 .Distinct(StringComparer.OrdinalIgnoreCase)
                                 .ToList();

                foreach (var item in gameGenres)
                {
                    var index = GetIndex(item, searchTerm, terms);

                    if (index.Item2 != -1)
                    {
                        try
                        {
                            var genre = _libraryManager.GetGameGenre(item);

                            hints.Add(new Tuple <BaseItem, string, int>(genre, index.Item1, index.Item2));
                        }
                        catch (Exception ex)
                        {
                            _logger.ErrorException("Error getting {0}", ex, item);
                        }
                    }
                }
            }

            if (query.IncludeStudios)
            {
                // Find studios
                var studios = items.SelectMany(i => i.Studios)
                              .Where(i => !string.IsNullOrWhiteSpace(i))
                              .Distinct(StringComparer.OrdinalIgnoreCase)
                              .ToList();

                foreach (var item in studios)
                {
                    var index = GetIndex(item, searchTerm, terms);

                    if (index.Item2 != -1)
                    {
                        try
                        {
                            var studio = _libraryManager.GetStudio(item);

                            hints.Add(new Tuple <BaseItem, string, int>(studio, index.Item1, index.Item2));
                        }
                        catch (Exception ex)
                        {
                            _logger.ErrorException("Error getting {0}", ex, item);
                        }
                    }
                }
            }

            if (query.IncludePeople)
            {
                // Find persons
                var persons = items.SelectMany(i => i.People)
                              .Select(i => i.Name)
                              .Where(i => !string.IsNullOrWhiteSpace(i))
                              .Distinct(StringComparer.OrdinalIgnoreCase)
                              .ToList();

                foreach (var item in persons)
                {
                    var index = GetIndex(item, searchTerm, terms);

                    if (index.Item2 != -1)
                    {
                        try
                        {
                            var person = _libraryManager.GetPerson(item);

                            hints.Add(new Tuple <BaseItem, string, int>(person, index.Item1, index.Item2));
                        }
                        catch (Exception ex)
                        {
                            _logger.ErrorException("Error getting {0}", ex, item);
                        }
                    }
                }
            }

            var returnValue = hints.Where(i => i.Item3 >= 0).OrderBy(i => i.Item3).Select(i => new SearchHintInfo
            {
                Item        = i.Item1,
                MatchedTerm = i.Item2
            });

            return(Task.FromResult(returnValue));
        }
コード例 #18
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)
            });
        }
コード例 #19
0
        public object Get(GetFavoritesView request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var allItems = user.RootFolder.GetRecursiveChildren(user)
                           .ToList();

            var allFavoriteItems = allItems.Where(i => _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite)
                                   .ToList();

            var itemsWithImages = allFavoriteItems.Where(i => !string.IsNullOrEmpty(i.PrimaryImagePath))
                                  .ToList();

            var itemsWithBackdrops = allFavoriteItems.Where(i => i.BackdropImagePaths.Count > 0)
                                     .ToList();

            var view = new FavoritesView();

            var fields = new List <ItemFields>();

            view.BackdropItems = FilterItemsForBackdropDisplay(itemsWithBackdrops.OrderBy(i => Guid.NewGuid()))
                                 .Take(10)
                                 .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                                 .ToList();

            var spotlightItems = itemsWithBackdrops.OrderBy(i => Guid.NewGuid())
                                 .Take(10)
                                 .ToList();

            view.SpotlightItems = spotlightItems
                                  .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                                  .ToList();

            fields.Add(ItemFields.PrimaryImageAspectRatio);

            view.Albums = itemsWithImages
                          .OfType <MusicAlbum>()
                          .OrderBy(i => Guid.NewGuid())
                          .Take(4)
                          .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                          .ToList();

            view.Books = itemsWithImages
                         .OfType <Book>()
                         .OrderBy(i => Guid.NewGuid())
                         .Take(6)
                         .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                         .ToList();

            view.Episodes = itemsWithImages
                            .OfType <Episode>()
                            .OrderBy(i => Guid.NewGuid())
                            .Take(6)
                            .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                            .ToList();

            view.Games = itemsWithImages
                         .OfType <Game>()
                         .OrderBy(i => Guid.NewGuid())
                         .Take(6)
                         .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                         .ToList();

            view.Movies = itemsWithImages
                          .OfType <Movie>()
                          .OrderBy(i => Guid.NewGuid())
                          .Take(6)
                          .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                          .ToList();

            view.Series = itemsWithImages
                          .OfType <Series>()
                          .OrderBy(i => Guid.NewGuid())
                          .Take(6)
                          .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                          .ToList();

            view.Songs = itemsWithImages
                         .OfType <Audio>()
                         .OrderBy(i => Guid.NewGuid())
                         .Take(4)
                         .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                         .ToList();

            view.MiniSpotlights = itemsWithBackdrops
                                  .Except(spotlightItems)
                                  .OrderBy(i => Guid.NewGuid())
                                  .Take(5)
                                  .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                                  .ToList();

            var artists = allItems.OfType <Audio>()
                          .SelectMany(i =>
            {
                var list = new List <string>();

                if (!string.IsNullOrEmpty(i.AlbumArtist))
                {
                    list.Add(i.AlbumArtist);
                }
                list.AddRange(i.Artists);

                return(list);
            })
                          .Distinct(StringComparer.OrdinalIgnoreCase)
                          .OrderBy(i => Guid.NewGuid())
                          .Select(i =>
            {
                try
                {
                    return(_libraryManager.GetArtist(i));
                }
                catch
                {
                    return(null);
                }
            })
                          .Where(i => i != null && _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite)
                          .Take(4)
                          .ToList();

            view.Artists = artists
                           .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                           .ToList();

            return(ToOptimizedResult(view));
        }
コード例 #20
0
        /// <summary>
        /// Gets the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns>System.Object.</returns>
        public object Get(GetItemCounts request)
        {
            var items = GetAllLibraryItems(request.UserId, _userManager, _libraryManager)
                        .Where(i => i.LocationType != LocationType.Virtual)
                        .ToList();

            var filteredItems = request.UserId.HasValue ? FilterItems(items, request, request.UserId.Value).ToList() : items;

            var albums      = filteredItems.OfType <MusicAlbum>().ToList();
            var episodes    = filteredItems.OfType <Episode>().ToList();
            var games       = filteredItems.OfType <Game>().ToList();
            var movies      = filteredItems.OfType <Movie>().ToList();
            var musicVideos = filteredItems.OfType <MusicVideo>().ToList();
            var adultVideos = filteredItems.OfType <AdultVideo>().ToList();
            var boxsets     = filteredItems.OfType <BoxSet>().ToList();
            var books       = filteredItems.OfType <Book>().ToList();
            var songs       = filteredItems.OfType <Audio>().ToList();
            var series      = filteredItems.OfType <Series>().ToList();

            var counts = new ItemCounts
            {
                AlbumCount      = albums.Count,
                EpisodeCount    = episodes.Count,
                GameCount       = games.Count,
                GameSystemCount = filteredItems.OfType <GameSystem>().Count(),
                MovieCount      = movies.Count,
                SeriesCount     = series.Count,
                SongCount       = songs.Count,
                TrailerCount    = filteredItems.OfType <Trailer>().Count(),
                MusicVideoCount = musicVideos.Count,
                AdultVideoCount = adultVideos.Count,
                BoxSetCount     = boxsets.Count,
                BookCount       = books.Count,

                UniqueTypes = items.Select(i => i.GetType().Name).Distinct().ToList()
            };

            var people = items.SelectMany(i => i.People)
                         .Select(i => i.Name)
                         .Distinct(StringComparer.OrdinalIgnoreCase)
                         .Select(i =>
            {
                try
                {
                    return(_libraryManager.GetPerson(i));
                }
                catch
                {
                    return(null);
                }
            })
                         .Where(i => i != null)
                         .ToList();

            people             = request.UserId.HasValue ? FilterItems(people, request, request.UserId.Value).ToList() : people;
            counts.PersonCount = people.Count;

            var artists = items.OfType <Audio>().SelectMany(i =>
            {
                var list = new List <string>();

                if (!string.IsNullOrEmpty(i.AlbumArtist))
                {
                    list.Add(i.AlbumArtist);
                }
                list.AddRange(i.Artists);

                return(list);
            })
                          .Distinct(StringComparer.OrdinalIgnoreCase)
                          .Select(i =>
            {
                try
                {
                    return(_libraryManager.GetArtist(i));
                }
                catch
                {
                    return(null);
                }
            })
                          .Where(i => i != null)
                          .ToList();

            artists            = request.UserId.HasValue ? FilterItems(artists, request, request.UserId.Value).ToList() : artists;
            counts.ArtistCount = artists.Count;

            return(ToOptimizedResult(counts));
        }
コード例 #21
0
        /// <summary>
        /// Runs the specified progress.
        /// </summary>
        /// <param name="progress">The progress.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        public async Task Run(IProgress <double> progress, CancellationToken cancellationToken)
        {
            var names = _itemRepo.GetAllArtistNames();

            var numComplete = 0;
            var count       = names.Count;

            foreach (var name in names)
            {
                try
                {
                    var item = _libraryManager.GetArtist(name);

                    await item.RefreshMetadata(cancellationToken).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    // Don't clutter the log
                    throw;
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error refreshing {0}", ex, name);
                }

                numComplete++;
                double percent = numComplete;
                percent /= count;
                percent *= 100;

                progress.Report(percent);
            }

            names = names.Select(i => i.RemoveDiacritics()).DistinctNames().ToList();

            var artistEntities = _libraryManager.GetItemList(new InternalItemsQuery
            {
                IncludeItemTypes = new[] { typeof(MusicArtist).Name }
            }).Cast <MusicArtist>().ToList();

            foreach (var artist in artistEntities)
            {
                if (!artist.IsAccessedByName)
                {
                    continue;
                }

                var name = (artist.Name ?? string.Empty).RemoveDiacritics();

                if (!names.Contains(name, StringComparer.OrdinalIgnoreCase))
                {
                    _logger.Info("Deleting dead artist {0} {1}.", artist.Id.ToString("N"), artist.Name);

                    await _libraryManager.DeleteItem(artist, new DeleteOptions
                    {
                        DeleteFileLocation = false
                    }).ConfigureAwait(false);
                }
            }

            progress.Report(100);
        }
コード例 #22
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);
        }
コード例 #23
0
        public object Get(GetFavoritesView request)
        {
            var user = _userManager.GetUserById(request.UserId);

            var allItems = user.RootFolder.GetRecursiveChildren(user)
                           .ToList();

            var allFavoriteItems = allItems.Where(i => _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite)
                                   .ToList();

            var itemsWithImages = allFavoriteItems.Where(i => !string.IsNullOrEmpty(i.PrimaryImagePath))
                                  .ToList();

            var itemsWithBackdrops = allFavoriteItems.Where(i => i.GetImages(ImageType.Backdrop).Any())
                                     .ToList();

            var view = new FavoritesView();

            var fields = new List <ItemFields>();

            view.BackdropItems = FilterItemsForBackdropDisplay(itemsWithBackdrops)
                                 .Randomize("backdrop")
                                 .Take(10)
                                 .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                                 .ToList();

            var spotlightItems = itemsWithBackdrops.Randomize("spotlight")
                                 .Take(10)
                                 .ToList();

            view.SpotlightItems = spotlightItems
                                  .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                                  .ToList();

            fields.Add(ItemFields.PrimaryImageAspectRatio);

            view.Albums = itemsWithImages
                          .OfType <MusicAlbum>()
                          .Randomize()
                          .Take(4)
                          .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                          .ToList();

            view.Books = itemsWithImages
                         .OfType <Book>()
                         .Randomize()
                         .Take(6)
                         .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                         .ToList();

            view.Episodes = itemsWithImages
                            .OfType <Episode>()
                            .Randomize()
                            .Take(6)
                            .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                            .ToList();

            view.Games = itemsWithImages
                         .OfType <Game>()
                         .Randomize()
                         .Take(6)
                         .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                         .ToList();

            view.Movies = itemsWithImages
                          .OfType <Movie>()
                          .Randomize()
                          .Take(6)
                          .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                          .ToList();

            view.Series = itemsWithImages
                          .OfType <Series>()
                          .Randomize()
                          .Take(6)
                          .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                          .ToList();

            view.Songs = itemsWithImages
                         .OfType <Audio>()
                         .Randomize()
                         .Take(4)
                         .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                         .ToList();

            view.MiniSpotlights = itemsWithBackdrops
                                  .Except(spotlightItems)
                                  .Randomize()
                                  .Take(5)
                                  .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                                  .ToList();

            var artists = _libraryManager.GetAllArtists(allItems)
                          .Randomize()
                          .Select(i =>
            {
                try
                {
                    return(_libraryManager.GetArtist(i));
                }
                catch
                {
                    return(null);
                }
            })
                          .Where(i => i != null && _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite)
                          .Take(4)
                          .ToList();

            view.Artists = artists
                           .Select(i => _dtoService.GetBaseItemDto(i, fields, user))
                           .ToList();

            return(ToOptimizedSerializedResultUsingCache(view));
        }
コード例 #24
0
ファイル: ItemsService.cs プロジェクト: Ivan-L/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,
                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,
                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().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,
                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.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.Artists))
            {
                query.ArtistIds = request.Artists.Split('|').Select(i =>
                {
                    try
                    {
                        return(_libraryManager.GetArtist(i));
                    }
                    catch
                    {
                        return(null);
                    }
                }).Where(i => i != null).Select(i => i.Id.ToString("N")).ToArray();
            }

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

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

            // 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();
            }

            return(query);
        }