Ejemplo n.º 1
0
        private void FillImages(BaseItemDto dto, string seriesName, string programSeriesId)
        {
            var librarySeries = _libraryManager.GetItemList(new InternalItemsQuery
            {
                IncludeItemTypes = new string[] { typeof(Series).Name },
                Name             = seriesName,
                Limit            = 1,
                ImageTypes       = new ImageType[] { ImageType.Thumb }
            }).FirstOrDefault();

            if (librarySeries != null)
            {
                var image = librarySeries.GetImageInfo(ImageType.Thumb, 0);
                if (image != null)
                {
                    try
                    {
                        dto.ParentThumbImageTag = _imageProcessor.GetImageCacheTag(librarySeries, image);
                        dto.ParentThumbItemId   = librarySeries.Id.ToString("N");
                    }
                    catch (Exception ex)
                    {
                    }
                }
                image = librarySeries.GetImageInfo(ImageType.Backdrop, 0);
                if (image != null)
                {
                    try
                    {
                        dto.ParentBackdropImageTags = new List <string>
                        {
                            _imageProcessor.GetImageCacheTag(librarySeries, image)
                        };
                        dto.ParentBackdropItemId = librarySeries.Id.ToString("N");
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }

            if (!string.IsNullOrWhiteSpace(programSeriesId))
            {
                var program = _libraryManager.GetItemList(new InternalItemsQuery
                {
                    IncludeItemTypes = new string[] { typeof(LiveTvProgram).Name },
                    ExternalSeriesId = programSeriesId,
                    Limit            = 1,
                    ImageTypes       = new ImageType[] { ImageType.Primary }
                }).FirstOrDefault();

                if (program != null)
                {
                    var image = program.GetImageInfo(ImageType.Primary, 0);
                    if (image != null)
                    {
                        try
                        {
                            dto.ParentPrimaryImageTag    = _imageProcessor.GetImageCacheTag(program, image);
                            dto.ParentPrimaryImageItemId = program.Id.ToString("N");
                        }
                        catch (Exception ex)
                        {
                        }
                    }

                    if (dto.ParentBackdropImageTags == null || dto.ParentBackdropImageTags.Count == 0)
                    {
                        image = program.GetImageInfo(ImageType.Backdrop, 0);
                        if (image != null)
                        {
                            try
                            {
                                dto.ParentBackdropImageTags = new List <string>
                                {
                                    _imageProcessor.GetImageCacheTag(program, image)
                                };
                                dto.ParentBackdropItemId = program.Id.ToString("N");
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 2
0
        public Page GetSearchPage(BaseItemDto item)
        {
            var apiClient = _connectionManager.GetApiClient(item);

            return(new SearchPage(item, apiClient, _sessionManager, _imageManager, _presentationManager, _navService, _playbackManager, _logger));
        }
Ejemplo n.º 3
0
        private void UpdateItem(BaseItemDto request, BaseItem item)
        {
            item.Name           = request.Name;
            item.ForcedSortName = request.ForcedSortName;

            var hasBudget = item as IHasBudget;

            if (hasBudget != null)
            {
                hasBudget.Budget  = request.Budget;
                hasBudget.Revenue = request.Revenue;
            }

            var hasOriginalTitle = item as IHasOriginalTitle;

            if (hasOriginalTitle != null)
            {
                hasOriginalTitle.OriginalTitle = hasOriginalTitle.OriginalTitle;
            }

            var hasCriticRating = item as IHasCriticRating;

            if (hasCriticRating != null)
            {
                hasCriticRating.CriticRating        = request.CriticRating;
                hasCriticRating.CriticRatingSummary = request.CriticRatingSummary;
            }

            item.DisplayMediaType  = request.DisplayMediaType;
            item.CommunityRating   = request.CommunityRating;
            item.VoteCount         = request.VoteCount;
            item.HomePageUrl       = request.HomePageUrl;
            item.IndexNumber       = request.IndexNumber;
            item.ParentIndexNumber = request.ParentIndexNumber;
            item.Overview          = request.Overview;
            item.Genres            = request.Genres;

            var episode = item as Episode;

            if (episode != null)
            {
                episode.DvdSeasonNumber         = request.DvdSeasonNumber;
                episode.DvdEpisodeNumber        = request.DvdEpisodeNumber;
                episode.AirsAfterSeasonNumber   = request.AirsAfterSeasonNumber;
                episode.AirsBeforeEpisodeNumber = request.AirsBeforeEpisodeNumber;
                episode.AirsBeforeSeasonNumber  = request.AirsBeforeSeasonNumber;
                episode.AbsoluteEpisodeNumber   = request.AbsoluteEpisodeNumber;
            }

            var hasTags = item as IHasTags;

            if (hasTags != null)
            {
                hasTags.Tags = request.Tags;
            }

            var hasTaglines = item as IHasTaglines;

            if (hasTaglines != null)
            {
                hasTaglines.Taglines = request.Taglines;
            }

            var hasShortOverview = item as IHasShortOverview;

            if (hasShortOverview != null)
            {
                hasShortOverview.ShortOverview = request.ShortOverview;
            }

            var hasKeywords = item as IHasKeywords;

            if (hasKeywords != null)
            {
                hasKeywords.Keywords = request.Keywords;
            }

            if (request.Studios != null)
            {
                item.Studios = request.Studios.Select(x => x.Name).ToList();
            }

            if (request.DateCreated.HasValue)
            {
                item.DateCreated = NormalizeDateTime(request.DateCreated.Value);
            }

            item.EndDate        = request.EndDate.HasValue ? NormalizeDateTime(request.EndDate.Value) : (DateTime?)null;
            item.PremiereDate   = request.PremiereDate.HasValue ? NormalizeDateTime(request.PremiereDate.Value) : (DateTime?)null;
            item.ProductionYear = request.ProductionYear;
            item.OfficialRating = request.OfficialRating;
            item.CustomRating   = request.CustomRating;

            SetProductionLocations(item, request);

            item.PreferredMetadataCountryCode = request.PreferredMetadataCountryCode;
            item.PreferredMetadataLanguage    = request.PreferredMetadataLanguage;

            var hasDisplayOrder = item as IHasDisplayOrder;

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

            var hasAspectRatio = item as IHasAspectRatio;

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

            item.IsLocked = request.LockData ?? false;

            if (request.LockedFields != null)
            {
                item.LockedFields = request.LockedFields;
            }

            // Only allow this for series. Runtimes for media comes from ffprobe.
            if (item is Series)
            {
                item.RunTimeTicks = request.RunTimeTicks;
            }

            foreach (var pair in request.ProviderIds.ToList())
            {
                if (string.IsNullOrEmpty(pair.Value))
                {
                    request.ProviderIds.Remove(pair.Key);
                }
            }

            item.ProviderIds = request.ProviderIds;

            var video = item as Video;

            if (video != null)
            {
                video.Video3DFormat = request.Video3DFormat;
            }

            var hasMetascore = item as IHasMetascore;

            if (hasMetascore != null)
            {
                hasMetascore.Metascore = request.Metascore;
            }

            var hasAwards = item as IHasAwards;

            if (hasAwards != null)
            {
                hasAwards.AwardSummary = request.AwardSummary;
            }

            var game = item as Game;

            if (game != null)
            {
                game.PlayersSupported = request.Players;
            }

            if (request.AlbumArtists != null)
            {
                var hasAlbumArtists = item as IHasAlbumArtist;
                if (hasAlbumArtists != null)
                {
                    hasAlbumArtists.AlbumArtists = request
                                                   .AlbumArtists
                                                   .Select(i => i.Name)
                                                   .ToList();
                }
            }

            if (request.ArtistItems != null)
            {
                var hasArtists = item as IHasArtist;
                if (hasArtists != null)
                {
                    hasArtists.Artists = request
                                         .ArtistItems
                                         .Select(i => i.Name)
                                         .ToList();
                }
            }

            var song = item as Audio;

            if (song != null)
            {
                song.Album = request.Album;
            }

            var musicVideo = item as MusicVideo;

            if (musicVideo != null)
            {
                musicVideo.Album = request.Album;
            }

            var series = item as Series;

            if (series != null)
            {
                series.Status  = request.SeriesStatus;
                series.AirDays = request.AirDays;
                series.AirTime = request.AirTime;

                if (request.DisplaySpecialsWithSeasons.HasValue)
                {
                    series.DisplaySpecialsWithSeasons = request.DisplaySpecialsWithSeasons.Value;
                }
            }
        }
Ejemplo n.º 4
0
        /// <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="fields">The fields.</param>
        private void AttachBasicFields(BaseItemDto dto, BaseItem item, BaseItem owner, List <ItemFields> fields)
        {
            if (fields.Contains(ItemFields.DateCreated))
            {
                dto.DateCreated = item.DateCreated;
            }

            if (fields.Contains(ItemFields.DisplayMediaType))
            {
                dto.DisplayMediaType = item.DisplayMediaType;
            }

            dto.IsUnidentified = item.IsUnidentified;

            if (fields.Contains(ItemFields.Settings))
            {
                dto.LockedFields   = item.LockedFields;
                dto.LockData       = item.IsLocked;
                dto.ForcedSortName = item.ForcedSortName;
            }

            var hasBudget = item as IHasBudget;

            if (hasBudget != null)
            {
                if (fields.Contains(ItemFields.Budget))
                {
                    dto.Budget = hasBudget.Budget;
                }

                if (fields.Contains(ItemFields.Revenue))
                {
                    dto.Revenue = hasBudget.Revenue;
                }
            }

            dto.EndDate = item.EndDate;

            if (fields.Contains(ItemFields.HomePageUrl))
            {
                dto.HomePageUrl = item.HomePageUrl;
            }

            if (fields.Contains(ItemFields.ExternalUrls))
            {
                dto.ExternalUrls = _providerManager.GetExternalUrls(item).ToArray();
            }

            if (fields.Contains(ItemFields.Tags))
            {
                var hasTags = item as IHasTags;
                if (hasTags != null)
                {
                    dto.Tags = hasTags.Tags;
                }

                if (dto.Tags == null)
                {
                    dto.Tags = new List <string>();
                }
            }

            if (fields.Contains(ItemFields.Keywords))
            {
                var hasTags = item as IHasKeywords;
                if (hasTags != null)
                {
                    dto.Keywords = hasTags.Keywords;
                }

                if (dto.Keywords == null)
                {
                    dto.Keywords = new List <string>();
                }
            }

            if (fields.Contains(ItemFields.ProductionLocations))
            {
                SetProductionLocations(item, dto);
            }

            var hasAspectRatio = item as IHasAspectRatio;

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

            var hasMetascore = item as IHasMetascore;

            if (hasMetascore != null)
            {
                dto.Metascore = hasMetascore.Metascore;
            }

            if (fields.Contains(ItemFields.AwardSummary))
            {
                var hasAwards = item as IHasAwards;
                if (hasAwards != null)
                {
                    dto.AwardSummary = hasAwards.AwardSummary;
                }
            }

            dto.BackdropImageTags = GetBackdropImageTags(item);

            if (fields.Contains(ItemFields.ScreenshotImageTags))
            {
                dto.ScreenshotImageTags = GetScreenshotImageTags(item);
            }

            if (fields.Contains(ItemFields.Genres))
            {
                dto.Genres = item.Genres;
            }

            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)))
            {
                var tag = GetImageCacheTag(item, image);

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

            dto.Id           = GetDtoId(item);
            dto.IndexNumber  = item.IndexNumber;
            dto.IsFolder     = item.IsFolder;
            dto.MediaType    = item.MediaType;
            dto.LocationType = item.LocationType;

            var hasLang = item as IHasPreferredMetadataLanguage;

            if (hasLang != null)
            {
                dto.PreferredMetadataCountryCode = hasLang.PreferredMetadataCountryCode;
                dto.PreferredMetadataLanguage    = hasLang.PreferredMetadataLanguage;
            }

            var hasCriticRating = item as IHasCriticRating;

            if (hasCriticRating != null)
            {
                dto.CriticRating = hasCriticRating.CriticRating;

                if (fields.Contains(ItemFields.CriticRatingSummary))
                {
                    dto.CriticRatingSummary = hasCriticRating.CriticRatingSummary;
                }
            }

            var hasTrailers = item as IHasTrailers;

            if (hasTrailers != null)
            {
                dto.LocalTrailerCount = hasTrailers.LocalTrailerIds.Count;
            }

            var hasDisplayOrder = item as IHasDisplayOrder;

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

            var collectionFolder = item as ICollectionFolder;

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

            var userView = item as UserView;

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

            if (fields.Contains(ItemFields.RemoteTrailers))
            {
                dto.RemoteTrailers = hasTrailers != null ?
                                     hasTrailers.RemoteTrailers :
                                     new List <MediaUrl>();
            }

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

            if (fields.Contains(ItemFields.Overview))
            {
                dto.Overview = item.Overview;
            }

            if (fields.Contains(ItemFields.ShortOverview))
            {
                var hasShortOverview = item as IHasShortOverview;
                if (hasShortOverview != null)
                {
                    dto.ShortOverview = hasShortOverview.ShortOverview;
                }
            }

            // If there are no backdrops, indicate what parent has them in case the Ui wants to allow inheritance
            if (dto.BackdropImageTags.Count == 0)
            {
                var parentWithBackdrop = GetParentBackdropItem(item, owner);

                if (parentWithBackdrop != null)
                {
                    dto.ParentBackdropItemId    = GetDtoId(parentWithBackdrop);
                    dto.ParentBackdropImageTags = GetBackdropImageTags(parentWithBackdrop);
                }
            }

            if (item.Parent != null && fields.Contains(ItemFields.ParentId))
            {
                dto.ParentId = GetDtoId(item.Parent);
            }

            dto.ParentIndexNumber = item.ParentIndexNumber;

            // If there is no logo, indicate what parent has one in case the Ui wants to allow inheritance
            if (!dto.HasLogo)
            {
                var parentWithLogo = GetParentImageItem(item, ImageType.Logo, owner);

                if (parentWithLogo != null)
                {
                    dto.ParentLogoItemId = GetDtoId(parentWithLogo);

                    dto.ParentLogoImageTag = GetImageCacheTag(parentWithLogo, ImageType.Logo);
                }
            }

            // If there is no art, indicate what parent has one in case the Ui wants to allow inheritance
            if (!dto.HasArtImage)
            {
                var parentWithImage = GetParentImageItem(item, ImageType.Art, owner);

                if (parentWithImage != null)
                {
                    dto.ParentArtItemId = GetDtoId(parentWithImage);

                    dto.ParentArtImageTag = GetImageCacheTag(parentWithImage, ImageType.Art);
                }
            }

            // If there is no thumb, indicate what parent has one in case the Ui wants to allow inheritance
            if (!dto.HasThumb)
            {
                var parentWithImage = GetParentImageItem(item, ImageType.Thumb, owner);

                if (parentWithImage != null)
                {
                    dto.ParentThumbItemId = GetDtoId(parentWithImage);

                    dto.ParentThumbImageTag = GetImageCacheTag(parentWithImage, ImageType.Thumb);
                }
            }

            if (fields.Contains(ItemFields.Path))
            {
                dto.Path = GetMappedPath(item);
            }

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

            if (fields.Contains(ItemFields.ProviderIds))
            {
                dto.ProviderIds = item.ProviderIds;
            }

            dto.RunTimeTicks = item.RunTimeTicks;

            if (fields.Contains(ItemFields.SortName))
            {
                dto.SortName = item.SortName;
            }

            if (fields.Contains(ItemFields.CustomRating))
            {
                dto.CustomRating = item.CustomRating;
            }

            if (fields.Contains(ItemFields.Taglines))
            {
                var hasTagline = item as IHasTaglines;
                if (hasTagline != null)
                {
                    dto.Taglines = hasTagline.Taglines;
                }

                if (dto.Taglines == null)
                {
                    dto.Taglines = new List <string>();
                }
            }

            dto.Type            = item.GetClientTypeName();
            dto.CommunityRating = item.CommunityRating;
            dto.VoteCount       = item.VoteCount;

            if (item.IsFolder)
            {
                var folder = (Folder)item;

                if (fields.Contains(ItemFields.IndexOptions))
                {
                    dto.IndexOptions = folder.IndexByOptionStrings.ToArray();
                }
            }

            var supportsPlaceHolders = item as ISupportsPlaceHolders;

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

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

            if (audio != null)
            {
                dto.Album   = audio.Album;
                dto.Artists = audio.Artists;

                var albumParent = audio.FindParent <MusicAlbum>();

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

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

                dto.MediaSourceCount = 1;
            }

            var album = item as MusicAlbum;

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

                dto.SoundtrackIds = album.SoundtrackIds
                                    .Select(i => i.ToString("N"))
                                    .ToArray();
            }

            var hasAlbumArtist = item as IHasAlbumArtist;

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

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

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

                dto.PartCount        = video.AdditionalPartIds.Count + 1;
                dto.MediaSourceCount = video.MediaSourceCount;

                if (fields.Contains(ItemFields.Chapters))
                {
                    List <ChapterInfoDto> chapters;

                    if (dto.MediaSources != null && dto.MediaSources.Count > 0)
                    {
                        chapters = _itemRepo.GetChapters(item.Id).Select(c => GetChapterInfoDto(c, item)).ToList();
                    }
                    else
                    {
                        chapters = _itemRepo.GetChapters(video.Id)
                                   .Select(c => GetChapterInfoDto(c, item))
                                   .ToList();
                    }

                    dto.Chapters = chapters;
                }
            }

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

                if (iHasMediaSources != null)
                {
                    List <MediaStream> mediaStreams;

                    if (dto.MediaSources != null && dto.MediaSources.Count > 0)
                    {
                        mediaStreams = dto.MediaSources.Where(i => new Guid(i.Id) == item.Id)
                                       .SelectMany(i => i.MediaStreams)
                                       .ToList();
                    }
                    else
                    {
                        mediaStreams = iHasMediaSources.GetMediaSources(true).First().MediaStreams;
                    }

                    dto.MediaStreams = mediaStreams;
                }
            }

            // Add MovieInfo
            var movie = item as Movie;

            if (movie != null)
            {
                var specialFeatureCount = movie.SpecialFeatureIds.Count;

                if (specialFeatureCount > 0)
                {
                    dto.SpecialFeatureCount = specialFeatureCount;
                }

                if (fields.Contains(ItemFields.TmdbCollectionName))
                {
                    dto.TmdbCollectionName = movie.TmdbCollectionName;
                }
            }

            // Add EpisodeInfo
            var episode = item as Episode;

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

                dto.DvdSeasonNumber         = episode.DvdSeasonNumber;
                dto.DvdEpisodeNumber        = episode.DvdEpisodeNumber;
                dto.AirsAfterSeasonNumber   = episode.AirsAfterSeasonNumber;
                dto.AirsBeforeEpisodeNumber = episode.AirsBeforeEpisodeNumber;
                dto.AirsBeforeSeasonNumber  = episode.AirsBeforeSeasonNumber;
                dto.AbsoluteEpisodeNumber   = episode.AbsoluteEpisodeNumber;

                var seasonId = episode.SeasonId;
                if (seasonId.HasValue)
                {
                    dto.SeasonId = seasonId.Value.ToString("N");
                }
            }

            // Add SeriesInfo
            var series = item as Series;

            if (series != null)
            {
                dto.AirDays = series.AirDays;
                dto.AirTime = series.AirTime;
                dto.Status  = series.Status;

                dto.SpecialFeatureCount = series.SpecialFeatureIds.Count;

                dto.SeasonCount = series.SeasonCount;

                if (fields.Contains(ItemFields.Settings))
                {
                    dto.DisplaySpecialsWithSeasons = series.DisplaySpecialsWithSeasons;
                }

                dto.AnimeSeriesIndex = series.AnimeSeriesIndex;
            }

            if (episode != null)
            {
                series = episode.Series;

                if (series != null)
                {
                    dto.SeriesId              = GetDtoId(series);
                    dto.SeriesName            = series.Name;
                    dto.AirTime               = series.AirTime;
                    dto.SeriesStudio          = series.Studios.FirstOrDefault();
                    dto.SeriesThumbImageTag   = GetImageCacheTag(series, ImageType.Thumb);
                    dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
                }
            }

            // Add SeasonInfo
            var season = item as Season;

            if (season != null)
            {
                series = season.Series;

                if (series != null)
                {
                    dto.SeriesId     = GetDtoId(series);
                    dto.SeriesName   = series.Name;
                    dto.AirTime      = series.AirTime;
                    dto.SeriesStudio = series.Studios.FirstOrDefault();

                    dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
                }
            }

            var game = item as Game;

            if (game != null)
            {
                SetGameProperties(dto, game);
            }

            var gameSystem = item as GameSystem;

            if (gameSystem != null)
            {
                SetGameSystemProperties(dto, gameSystem);
            }

            var musicVideo = item as MusicVideo;

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

            var book = item as Book;

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

            var photo = item as Photo;

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

            var tvChannel = item as LiveTvChannel;

            if (tvChannel != null)
            {
                dto.MediaSources = tvChannel.GetMediaSources(true).ToList();
            }

            var channelItem = item as IChannelItem;

            if (channelItem != null)
            {
                dto.ChannelId   = channelItem.ChannelId;
                dto.ChannelName = _channelManagerFactory().GetChannel(channelItem.ChannelId).Name;
            }
        }
Ejemplo n.º 5
0
        public BaseItem GetItem(BaseItemDto mb3Item, string itemType)
        {
            var item = InstantiateItem(itemType, mb3Item);

            if (item != null)
            {
                item.Name = mb3Item.Name;
                //Logger.ReportVerbose("Item {0} is {1}", item.Name, item.GetType().Name);
                item.Path             = mb3Item.Path;
                item.DateCreated      = (mb3Item.DateCreated ?? DateTime.MinValue).ToLocalTime();
                item.DisplayMediaType = mb3Item.DisplayMediaType;
                item.Overview         = mb3Item.Overview;
                item.SortName         = mb3Item.SortName;
                item.TagLine          = mb3Item.Taglines != null && mb3Item.Taglines.Count > 0 ? mb3Item.Taglines[0] : null;
                item.UserData         = mb3Item.UserData;
                item.PremierDate      = mb3Item.PremiereDate ?? DateTime.MinValue;
                item.FirstAired       = mb3Item.PremiereDate != null?mb3Item.PremiereDate.Value.ToLocalTime().ToString("ddd d MMM, yyyy") : null;

                item.EndDate             = mb3Item.EndDate ?? DateTime.MinValue;
                item.ProductionYear      = mb3Item.ProductionYear ?? item.PremierDate.Year;
                item.ProductionLocations = mb3Item.ProductionLocations;
                //Logger.ReportInfo("*********** Premier Date for {0} is {1}",item.Name,item.PremierDate);
                item.ApiParentId = mb3Item.ParentId;
                //if (item.ApiParentId == null) Logger.ReportVerbose("Parent Id is null for {0}",item.Name);
                item.LocationType = mb3Item.LocationType;
                // recursive media count
                item.ApiRecursiveItemCount = mb3Item.RecursiveItemCount;
                item.ApiItemCount          = mb3Item.ChildCount;
                // disc status
                item.IsOffline      = mb3Item.LocationType == LocationType.Offline;
                item.IsExternalDisc = mb3Item.IsPlaceHolder ?? false;
                // playback access
                item.PlaybackAllowed = (mb3Item.PlayAccess == PlayAccess.Full) && !(mb3Item.IsPlaceHolder ?? false);
                // delete access
                item.CanDelete = mb3Item.CanDelete ?? false;

                //Ratings
                item.CriticRating        = mb3Item.CriticRating;
                item.CriticRatingSummary = mb3Item.CriticRatingSummary;
                item.MetaScore           = mb3Item.Metascore;

                //SpecialFeatures
                item.SpecialFeatureCount = mb3Item.SpecialFeatureCount ?? 0;

                //Counts
                item.MovieCount      = mb3Item.MovieCount ?? 0;
                item.SeriesCount     = mb3Item.SeriesCount ?? 0;
                item.EpisodeCount    = mb3Item.EpisodeCount ?? 0;
                item.TrailerCount    = mb3Item.LocalTrailerCount ?? 0;
                item.GameCount       = mb3Item.GameCount ?? 0;
                item.SongCount       = mb3Item.SongCount ?? 0;
                item.AlbumCount      = mb3Item.AlbumCount ?? 0;
                item.MusicVideoCount = mb3Item.MusicVideoCount ?? 0;


                var runTimeTicks = mb3Item.RunTimeTicks;
                item.RuntimeTicks = runTimeTicks ?? 0;

                var index = item as IndexFolder;
                if (index != null)
                {
                    index.Id      = mb3Item.Id.GetMD5();
                    index.IndexId = mb3Item.Id;
                }
                else
                {
                    item.Id = new Guid(mb3Item.Id);
                }

                if (mb3Item.ImageTags != null)
                {
                    foreach (var tag in mb3Item.ImageTags)
                    {
                        switch (tag.Key)
                        {
                        case ImageType.Primary:
                            if (mb3Item.HasPrimaryImage)
                            {
                                item.PrimaryImagePath = GetImageUrl(item, new ImageOptions {
                                    ImageType = tag.Key, Tag = tag.Value, Quality = Kernel.Instance.CommonConfigData.JpgImageQuality, MaxWidth = Kernel.Instance.CommonConfigData.MaxPrimaryWidth, CropWhitespace = false
                                });
                            }
                            break;

                        case ImageType.Logo:
                            if (mb3Item.HasLogo)
                            {
                                item.LogoImagePath = GetImageUrl(item, new ImageOptions {
                                    ImageType = tag.Key, Tag = tag.Value, Quality = Kernel.Instance.CommonConfigData.JpgImageQuality, MaxWidth = Kernel.Instance.CommonConfigData.MaxLogoWidth, CropWhitespace = false
                                });
                            }
                            break;

                        case ImageType.Art:
                            if (mb3Item.HasArtImage)
                            {
                                item.ArtImagePath = GetImageUrl(item, new ImageOptions {
                                    ImageType = tag.Key, Tag = tag.Value, Quality = Kernel.Instance.CommonConfigData.JpgImageQuality, MaxWidth = Kernel.Instance.CommonConfigData.MaxArtWidth, CropWhitespace = false
                                });
                            }
                            break;

                        case ImageType.Banner:
                            if (mb3Item.HasBanner)
                            {
                                item.BannerImagePath = GetImageUrl(item, new ImageOptions {
                                    ImageType = tag.Key, Tag = tag.Value, Quality = Kernel.Instance.CommonConfigData.JpgImageQuality, MaxWidth = Kernel.Instance.CommonConfigData.MaxBannerWidth, CropWhitespace = false
                                });
                            }
                            break;

                        case ImageType.Thumb:
                            if (mb3Item.HasThumb)
                            {
                                item.ThumbnailImagePath = GetImageUrl(item, new ImageOptions {
                                    ImageType = tag.Key, Tag = tag.Value, Quality = Kernel.Instance.CommonConfigData.JpgImageQuality, MaxWidth = Kernel.Instance.CommonConfigData.MaxThumbWidth, CropWhitespace = false
                                });
                            }
                            break;

                        case ImageType.Disc:
                            if (mb3Item.HasDiscImage)
                            {
                                item.DiscImagePath = GetImageUrl(item, new ImageOptions {
                                    ImageType = tag.Key, Tag = tag.Value, Quality = Kernel.Instance.CommonConfigData.JpgImageQuality, MaxWidth = Kernel.Instance.CommonConfigData.MaxDiscWidth, CropWhitespace = false
                                });
                            }
                            break;
                        }
                    }
                }

                if (mb3Item.BackdropImageTags != null && mb3Item.BackdropCount > 0)
                {
                    var ndx = 0;
                    item.BackdropImagePaths = new List <string>();
                    foreach (var bd in mb3Item.BackdropImageTags)
                    {
                        item.BackdropImagePaths.Add(Kernel.ApiClient.GetImageUrl(mb3Item.Id, new ImageOptions {
                            ImageType = ImageType.Backdrop, Quality = Kernel.Instance.CommonConfigData.JpgImageQuality, MaxWidth = Kernel.Instance.CommonConfigData.MaxBackgroundWidth, Tag = bd, ImageIndex = ndx
                        }));
                        ndx++;
                    }
                }

                var folder = item as Folder;
                if (folder != null)
                {
                    // Collection Type
                    folder.CollectionType = mb3Item.CollectionType;
                    // Fill in display prefs
                    folder.DisplayPreferencesId = mb3Item.DisplayPreferencesId ?? mb3Item.Id;

                    // cumulative runtime
                    if (mb3Item.CumulativeRunTimeTicks != null)
                    {
                        folder.RunTime = (int)(mb3Item.CumulativeRunTimeTicks / TimeSpan.TicksPerMinute);
                    }

                    // unwatched count
                    if (mb3Item.UserData != null && mb3Item.UserData.UnplayedItemCount.HasValue)
                    {
                        folder.UnwatchedCount = mb3Item.UserData.UnplayedItemCount.Value;
                    }
                    // it is just too slow to try and gather these as channels are dynamic and potentially large
                    else if (mb3Item.Type == "Channel" || mb3Item.Type == "ChannelFolder")
                    {
                        folder.UnwatchedCount = 0;
                    }

                    // we want our created date to be the date of last item we contain
                    folder.DateCreated = mb3Item.DateLastMediaAdded ?? folder.DateCreated;
                }

                var video = item as Video;
                if (video != null && video.Path != null)
                {
                    video.ContainsTrailers = mb3Item.LocalTrailerCount > 0;
                    if (mb3Item.Video3DFormat != null)
                    {
                        video.VideoFormat = mb3Item.Video3DFormat == Video3DFormat.FullSideBySide || mb3Item.Video3DFormat == Video3DFormat.HalfSideBySide ? "Sbs3D" : "Digital3D";
                        video.Is3D        = true;
                    }
                    else
                    {
                        video.VideoFormat = "Standard";
                    }

                    // Chapters
                    if (mb3Item.Chapters != null)
                    {
                        var ndx = 0;
                        video.Chapters = mb3Item.Chapters.Select(c => new Chapter {
                            ApiParentId = mb3Item.Id, PositionTicks = c.StartPositionTicks, Name = c.Name, PrimaryImagePath = c.HasImage ? GetImageUrl(video, new ImageOptions {
                                Tag = c.ImageTag, ImageType = ImageType.Chapter, ImageIndex = ndx++
                            }) : null
                        }).ToList();
                    }
                }

                var media = item as Media;
                if (media != null)
                {
                    media.PartCount    = mb3Item.PartCount ?? 1;
                    media.MediaSources = mb3Item.MediaSources;

                    if (mb3Item.MediaType == Model.Entities.MediaType.Video)
                    {
                        if (media.Path != null)
                        {
                            media.MediaType = MediaTypeResolver.DetermineType(media.Path);
                        }
                        else
                        {
                            media.MediaType = MediaType.Unknown;
                        }
                    }
                    else
                    {
                        media.MediaType = MediaTypeResolver.DetermineType(media.Path);
                    }

                    if (mb3Item.MediaStreams != null)
                    {
                        var vidStream   = mb3Item.MediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video);
                        var audStream   = mb3Item.MediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Audio && s.IsDefault) ?? mb3Item.MediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Audio);
                        var subtStreams = mb3Item.MediaStreams.Where(s => s.Type == MediaStreamType.Subtitle && !string.IsNullOrEmpty(s.Language)).Select(s => s.IsForced ? s.Language.ToUpper() : s.Language).ToArray();
                        media.MediaStreams = mb3Item.MediaStreams;
                        media.AspectRatio  = !string.IsNullOrEmpty(mb3Item.AspectRatio) ? mb3Item.AspectRatio : null;
                        media.SubTitle     = subtStreams.Any() ? string.Join(", ", subtStreams) : null;

                        media.MediaInfo = new MediaInfoData
                        {
                            OverrideData = new MediaInfoData.MIData
                            {
                                AudioStreamCount  = mb3Item.MediaStreams.Count(s => s.Type == MediaStreamType.Audio),
                                AudioBitRate      = audStream != null ? audStream.BitRate ?? 0 : 0,
                                AudioChannelCount = audStream != null?TranslateAudioChannels(audStream.Channels ?? 0) : "",
                                                        AudioFormat                              = audStream != null ? audStream.Codec == "dca" ? audStream.Profile : audStream.Codec : "",
                                                        VideoBitRate                             = vidStream != null ? vidStream.BitRate ?? 0 : 0,
                                                        VideoCodec                               = vidStream != null ? vidStream.Codec : "",
                                                        VideoFPS                                 = vidStream != null?vidStream.AverageFrameRate.ToString() : "",
                                                                                       Width     = vidStream != null ? vidStream.Width ?? 0 : 0,
                                                                                       Height    = vidStream != null ? vidStream.Height ?? 0 : 0,
                                                                                       Subtitles = subtStreams.Any() ? string.Join(", ", subtStreams) : null,
                                                                                       RunTime   = runTimeTicks != null?ConvertTicksToMinutes(runTimeTicks) : 0
                            }
                        };
                    }
                    if (mb3Item.UserData != null)
                    {
                        media.PlaybackStatus = PlaybackStatusFactory.Instance.Create(media.Id);
                        media.PlaybackStatus.PositionTicks = mb3Item.UserData.PlaybackPositionTicks;
                        media.PlaybackStatus.PlayCount     = mb3Item.UserData.PlayCount;
                        media.PlaybackStatus.WasPlayed     = mb3Item.UserData.Played || mb3Item.LocationType == LocationType.Virtual;
                        media.PlaybackStatus.LastPlayed    = (mb3Item.UserData.LastPlayedDate ?? DateTime.MinValue).ToLocalTime();
                    }
                }

                var show = item as IShow;
                if (show != null)
                {
                    show.MpaaRating  = mb3Item.OfficialRating;
                    show.ImdbRating  = mb3Item.CommunityRating;
                    show.RunningTime = runTimeTicks != null ? (int?)ConvertTicksToMinutes(runTimeTicks) : null;

                    if (mb3Item.Genres != null)
                    {
                        show.Genres = new List <string>(mb3Item.Genres);
                    }

                    if (mb3Item.People != null)
                    {
                        show.Actors    = new List <Actor>(mb3Item.People.Where(p => p.Type == PersonType.Actor || p.Type == PersonType.GuestStar).Select(a => new Actor(a)));
                        show.Directors = new List <string>(mb3Item.People.Where(p => p.Type == PersonType.Director).Select(a => a.Name));
                    }

                    if (mb3Item.Studios != null)
                    {
                        show.Studios = new List <string>(mb3Item.Studios.Select(s => s.Name));
                        foreach (var studio in mb3Item.Studios.Where(s => s != null))
                        {
                            Studio.AddToCache(studio);
                        }
                    }
                }

                var episode = item as Episode;
                if (episode != null)
                {
                    var indexDisplay = mb3Item.IndexNumber != null && mb3Item.IndexNumber > 0 ? mb3Item.IndexNumber + (mb3Item.IndexNumberEnd != null ? "-" + mb3Item.IndexNumberEnd : "") + " - " : "";
                    episode.Name          = indexDisplay != "" ? indexDisplay + episode.Name : episode.Name;
                    episode.EpisodeNumber = mb3Item.IndexNumber != null?mb3Item.IndexNumber.Value.ToString("#00") : null;

                    episode.SeasonNumber = mb3Item.ParentIndexNumber != null?mb3Item.ParentIndexNumber.Value.ToString("#00") : null;

                    episode.SeriesId = mb3Item.SeriesId;
                    episode.SeasonId = mb3Item.SeasonId;
                    if (mb3Item.AirsAfterSeasonNumber != null)
                    {
                        episode.SortName = mb3Item.AirsAfterSeasonNumber.Value.ToString("000") + "-999999" + mb3Item.SortName;
                    }
                    else
                    if (mb3Item.AirsBeforeSeasonNumber != null && mb3Item.AirsBeforeEpisodeNumber != null)
                    {
                        episode.SortName = mb3Item.AirsBeforeSeasonNumber.Value.ToString("000") + "-" + ((int)(mb3Item.AirsBeforeEpisodeNumber - 1)).ToString("0000") + ".5" + mb3Item.SortName;
                    }
                }

                var season = item as Season;
                if (season != null)
                {
                    season.SeasonNumber = (mb3Item.IndexNumber ?? 0).ToString("000");
                }
                else
                {
                    var series = item as Series;
                    if (series != null)
                    {
                        series.Status       = mb3Item.Status;
                        series.AirTime      = mb3Item.AirTime;
                        series.ImdbRating   = mb3Item.CommunityRating;
                        series.CriticRating = mb3Item.CriticRating;
                        series.AirDay       = mb3Item.AirDays != null?mb3Item.AirDays.FirstOrDefault().ToString() : null;
                    }
                }


                var song = item as Song;
                if (song != null)
                {
                    song.Album        = mb3Item.Album;
                    song.AlbumArtist  = mb3Item.AlbumArtist;
                    song.AlbumId      = mb3Item.AlbumId;
                    song.Artist       = mb3Item.Artists.FirstOrDefault();
                    song.CriticRating = mb3Item.CommunityRating;
                }

                var album = item as MusicAlbum;
                if (album != null)
                {
                    album.AlbumArtist = mb3Item.AlbumArtist ?? mb3Item.Artists.FirstOrDefault();
                }

                var photo = item as Photo;
                if (photo != null)
                {
                    if (mb3Item.HasPrimaryImage)
                    {
                        //Make the photo itself also the backdrop so it can preview large and play back at full-res
                        item.BackdropImagePaths = new List <string> {
                            Kernel.ApiClient.GetImageUrl(mb3Item.Id, new ImageOptions {
                                ImageType = ImageType.Primary, Quality = Kernel.Instance.CommonConfigData.JpgImageQuality, MaxWidth = Kernel.Instance.CommonConfigData.MaxBackgroundWidth, Tag = mb3Item.ImageTags[ImageType.Primary]
                            })
                        };
                    }

                    if (string.IsNullOrEmpty(photo.Overview))
                    {
                        if (photo.DateTaken != DateTime.MinValue || !string.IsNullOrEmpty(mb3Item.CameraMake) || !string.IsNullOrEmpty(mb3Item.CameraModel))
                        {
                            photo.Overview = string.Format("Taken {0} with a {1} {2}\n", photo.DateTaken > DateTime.MinValue ? photo.DateTaken.ToShortTimeString() : "", mb3Item.CameraMake, mb3Item.CameraModel);
                        }
                        photo.Overview += string.Format("Original Resolution {0}x{1}", mb3Item.Width, mb3Item.Height);
                        if (mb3Item.ShutterSpeed != null)
                        {
                            photo.Overview += string.Format(" Shutter Speed {0}\n", mb3Item.ShutterSpeed);
                        }
                    }
                }

                // Finally, any custom values
                item.FillCustomValues(mb3Item);
            }
            else
            {
                Logger.ReportWarning("Ignoring invalid item " + itemType + ".  Would not instantiate in current environment.");
            }


            return(item);
        }
Ejemplo n.º 6
0
 private void SetBookProperties(BaseItemDto dto, Book item)
 {
     dto.SeriesName = item.SeriesName;
 }
Ejemplo n.º 7
0
 private void SetGameSystemProperties(BaseItemDto dto, GameSystem item)
 {
     dto.GameSystem = item.GameSystemName;
 }
Ejemplo n.º 8
0
        private void UpdateItem(BaseItemDto request, BaseItem item)
        {
            item.Name           = request.Name;
            item.ForcedSortName = request.ForcedSortName;

            item.OriginalTitle = string.IsNullOrWhiteSpace(request.OriginalTitle) ? null : request.OriginalTitle;

            item.CriticRating = request.CriticRating;

            item.CommunityRating   = request.CommunityRating;
            item.HomePageUrl       = request.HomePageUrl;
            item.IndexNumber       = request.IndexNumber;
            item.ParentIndexNumber = request.ParentIndexNumber;
            item.Overview          = request.Overview;
            item.Genres            = request.Genres;

            var episode = item as Episode;

            if (episode != null)
            {
                episode.DvdSeasonNumber         = request.DvdSeasonNumber;
                episode.DvdEpisodeNumber        = request.DvdEpisodeNumber;
                episode.AirsAfterSeasonNumber   = request.AirsAfterSeasonNumber;
                episode.AirsBeforeEpisodeNumber = request.AirsBeforeEpisodeNumber;
                episode.AirsBeforeSeasonNumber  = request.AirsBeforeSeasonNumber;
                episode.AbsoluteEpisodeNumber   = request.AbsoluteEpisodeNumber;
            }

            item.Tags = request.Tags;

            if (request.Taglines != null)
            {
                item.Tagline = request.Taglines.FirstOrDefault();
            }

            if (request.Studios != null)
            {
                item.Studios = request.Studios.Select(x => x.Name).ToArray();
            }

            if (request.DateCreated.HasValue)
            {
                item.DateCreated = NormalizeDateTime(request.DateCreated.Value);
            }

            item.EndDate        = request.EndDate.HasValue ? NormalizeDateTime(request.EndDate.Value) : (DateTime?)null;
            item.PremiereDate   = request.PremiereDate.HasValue ? NormalizeDateTime(request.PremiereDate.Value) : (DateTime?)null;
            item.ProductionYear = request.ProductionYear;
            item.OfficialRating = string.IsNullOrWhiteSpace(request.OfficialRating) ? null : request.OfficialRating;
            item.CustomRating   = request.CustomRating;

            if (request.ProductionLocations != null)
            {
                item.ProductionLocations = request.ProductionLocations;
            }

            item.PreferredMetadataCountryCode = request.PreferredMetadataCountryCode;
            item.PreferredMetadataLanguage    = request.PreferredMetadataLanguage;

            var hasDisplayOrder = item as IHasDisplayOrder;

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

            var hasAspectRatio = item as IHasAspectRatio;

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

            item.IsLocked = request.LockData ?? false;

            if (request.LockedFields != null)
            {
                item.LockedFields = request.LockedFields;
            }

            // Only allow this for series. Runtimes for media comes from ffprobe.
            if (item is Series)
            {
                item.RunTimeTicks = request.RunTimeTicks;
            }

            foreach (var pair in request.ProviderIds.ToList())
            {
                if (string.IsNullOrEmpty(pair.Value))
                {
                    request.ProviderIds.Remove(pair.Key);
                }
            }

            item.ProviderIds = request.ProviderIds;

            var video = item as Video;

            if (video != null)
            {
                video.Video3DFormat = request.Video3DFormat;
            }

            if (request.AlbumArtists != null)
            {
                var hasAlbumArtists = item as IHasAlbumArtist;
                if (hasAlbumArtists != null)
                {
                    hasAlbumArtists.AlbumArtists = request
                                                   .AlbumArtists
                                                   .Select(i => i.Name)
                                                   .ToArray();
                }
            }

            if (request.ArtistItems != null)
            {
                var hasArtists = item as IHasArtist;
                if (hasArtists != null)
                {
                    hasArtists.Artists = request
                                         .ArtistItems
                                         .Select(i => i.Name)
                                         .ToArray();
                }
            }

            var song = item as Audio;

            if (song != null)
            {
                song.Album = request.Album;
            }

            var musicVideo = item as MusicVideo;

            if (musicVideo != null)
            {
                musicVideo.Album = request.Album;
            }

            var series = item as Series;

            if (series != null)
            {
                series.Status = GetSeriesStatus(request);

                if (request.AirDays != null)
                {
                    series.AirDays = request.AirDays;
                    series.AirTime = request.AirTime;
                }
            }
        }
Ejemplo n.º 9
0
        public void Play(string path, long startPositionTicks, bool isVideo, BaseItemDto item, MediaSourceInfo mediaSource, bool enableFullScreen, IntPtr videoWindowHandle, DirectShowPlayerConfiguration config)
        {
            var playableItem = new PlayableItem
            {
                MediaSource  = mediaSource,
                PlayablePath = path,
                OriginalItem = item
            };

            try
            {
                InvokeOnPlayerThread(() =>
                {
                    //create a fresh DS Player everytime we want one
                    DisposePlayerInternal();

                    _mediaPlayer = new DirectShowPlayer(this, _logger, config, _httpClient, videoWindowHandle);
                    _mediaPlayer.Play(playableItem, enableFullScreen);

                    try
                    {
                        Standby.PreventSleepAndMonitorOff();
                    }
                    catch
                    {
                    }

                    try
                    {
                        if (startPositionTicks > 0)
                        {
                            _mediaPlayer.Seek(startPositionTicks);
                        }
                    }
                    catch
                    {
                    }

                    if (playableItem.IsVideo)
                    {
                        var audioIndex    = playableItem.MediaSource.DefaultAudioStreamIndex;
                        var subtitleIndex = playableItem.MediaSource.DefaultSubtitleStreamIndex;

                        if (audioIndex.HasValue && audioIndex.Value != -1)
                        {
                            try
                            {
                                SetAudioStreamIndexInternal(audioIndex.Value);
                            }
                            catch
                            {
                            }
                        }
                        try
                        {
                            SetSubtitleStreamIndexInternal(subtitleIndex ?? -1);
                        }
                        catch
                        {
                        }
                    }
                }, true);
            }
            catch (Exception ex)
            {
                OnPlaybackStopped(playableItem, null, TrackCompletionReason.Failure, null);

                throw;
            }
        }
Ejemplo n.º 10
0
        /// <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;

            if (item is IHasDisplayOrder hasDisplayOrder)
            {
                dto.DisplayOrder = hasDisplayOrder.DisplayOrder;
            }

            if (item is IHasCollectionType hasCollectionType)
            {
                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
                //}
            }

            if (item is IHasArtist hasArtist)
            {
                dto.Artists = hasArtist.Artists;

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

                //dto.ArtistItems = artistItems.Items
                //    .Select(i =>
                //    {
                //        var artist = i.Item1;
                //        return new NameIdPair
                //        {
                //            Name = artist.Name,
                //            Id = artist.Id.ToString("N", CultureInfo.InvariantCulture)
                //        };
                //    })
                //    .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", CultureInfo.InvariantCulture) }
                //});

                //dto.AlbumArtists = artistItems.Items
                //    .Select(i =>
                //    {
                //        var artist = i.Item1;
                //        return new NameIdPair
                //        {
                //            Name = artist.Name,
                //            Id = artist.Id.ToString("N", CultureInfo.InvariantCulture)
                //        };
                //    })
                //    .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
                        {
                            string id = item.Id.ToString("N", CultureInfo.InvariantCulture);
                            mediaStreams = dto.MediaSources.Where(i => string.Equals(i.Id, id, StringComparison.OrdinalIgnoreCase))
                                           .SelectMany(i => i.MediaStreams)
                                           .ToArray();
                        }
                    }
                    else
                    {
                        mediaStreams = _mediaSourceManager().GetStaticMediaSources(item, true)[0].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))
            {
                int trailerCount = 0;
                if (allExtras == null)
                {
                    allExtras = item.GetExtras().ToArray();
                }

                trailerCount += allExtras.Count(i => i.ExtraType.HasValue && i.ExtraType.Value == ExtraType.Trailer);

                if (item is IHasTrailers hasTrailers)
                {
                    trailerCount += hasTrailers.GetTrailerCount();
                }

                dto.LocalTrailerCount = trailerCount;
            }

            // Add EpisodeInfo
            if (item is Episode episode)
            {
                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;

                // this block will add the series poster for episodes without a poster
                // TODO maybe remove the if statement entirely
                //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
            if (item is Series series)
            {
                dto.AirDays = series.AirDays;
                dto.AirTime = series.AirTime;
                dto.Status  = series.Status.HasValue ? series.Status.Value.ToString() : null;
            }

            // Add SeasonInfo
            if (item is Season season)
            {
                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();
                    }
                }

                // this block will add the series poster for seasons without a poster
                // TODO maybe remove the if statement entirely
                //if (options.ContainsField(ItemFields.SeriesPrimaryImage))
                {
                    series = series ?? season.Series;
                    if (series != null)
                    {
                        dto.SeriesPrimaryImageTag = GetImageCacheTag(series, ImageType.Primary);
                    }
                }
            }

            if (item is MusicVideo musicVideo)
            {
                SetMusicVideoProperties(dto, musicVideo);
            }

            if (item is Book book)
            {
                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;
                }
            }

            if (item is Photo photo)
            {
                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;
                }
            }
        }
Ejemplo n.º 11
0
        private IEnumerable <TabItem> GetMenuList(BaseItemDto item, QueryResult <ItemReview> reviewsResult)
        {
            var views = new List <TabItem>
            {
                new TabItem
                {
                    Name        = "overview",
                    DisplayName = "Overview"
                }
            };

            if (item.ChildCount > 0)
            {
                if (item.IsType("series"))
                {
                    views.Add(new TabItem
                    {
                        Name        = "seasons",
                        DisplayName = "Seasons"
                    });
                }
                else if (item.IsType("season"))
                {
                    views.Add(new TabItem
                    {
                        Name        = "episodes",
                        DisplayName = "Episodes"
                    });
                }
                else if (item.IsType("musicalbum"))
                {
                    views.Add(new TabItem
                    {
                        Name        = "songs",
                        DisplayName = "Songs"
                    });
                }
            }

            if (item.People.Any(i => i.HasPrimaryImage))
            {
                views.Add(new TabItem
                {
                    Name        = "cast",
                    DisplayName = "Cast"
                });
            }

            if (item.LocalTrailerCount > 1)
            {
                views.Add(new TabItem
                {
                    Name        = "trailers",
                    DisplayName = "Trailers"
                });
            }

            if (item.Chapters != null && item.Chapters.Count > 0)
            {
                views.Add(new TabItem
                {
                    Name        = "scenes",
                    DisplayName = "Scenes"
                });
            }

            //if (item.MediaStreams != null && item.MediaStreams.Count > 0)
            //{
            //    views.Add(new TabItem
            //    {
            //        Name = "media info",
            //        DisplayName = "Media Info"
            //    });
            //}

            if (item.SpecialFeatureCount > 0)
            {
                if (item.IsType("series"))
                {
                    views.Add(new TabItem
                    {
                        Name        = "special features",
                        DisplayName = "Specials"
                    });
                }
                else
                {
                    views.Add(new TabItem
                    {
                        Name        = "special features",
                        DisplayName = "Special Features"
                    });
                }
            }

            if (reviewsResult.TotalRecordCount > 0 || !string.IsNullOrEmpty(item.CriticRatingSummary))
            {
                views.Add(new TabItem
                {
                    Name        = "reviews",
                    DisplayName = "Reviews"
                });
            }

            if (item.SoundtrackIds != null)
            {
                if (item.SoundtrackIds.Length > 1)
                {
                    views.Add(new TabItem
                    {
                        Name        = "soundtracks",
                        DisplayName = "Soundtracks"
                    });
                }
                else if (item.SoundtrackIds.Length > 0)
                {
                    views.Add(new TabItem
                    {
                        Name        = "soundtrack",
                        DisplayName = "Soundtrack"
                    });
                }
            }

            if (item.IsType("movie") || item.IsType("trailer") || item.IsType("series") || item.IsType("musicalbum") || item.IsGame)
            {
                views.Add(new TabItem
                {
                    Name        = "similar",
                    DisplayName = "Similar"
                });
            }

            if (item.IsArtist || item.IsGameGenre || item.IsGenre || item.IsMusicGenre || item.IsPerson || item.IsStudio)
            {
                if (item.MovieCount.HasValue && item.MovieCount.Value > 0)
                {
                    views.Add(new TabItem
                    {
                        Name        = "itemmovies",
                        DisplayName = string.Format("Movies ({0})", item.MovieCount.Value)
                    });
                }

                if (item.SeriesCount.HasValue && item.SeriesCount.Value > 0)
                {
                    views.Add(new TabItem
                    {
                        Name        = "itemseries",
                        DisplayName = string.Format("Series ({0})", item.SeriesCount.Value)
                    });
                }

                if (item.EpisodeCount.HasValue && item.EpisodeCount.Value > 0)
                {
                    views.Add(new TabItem
                    {
                        Name        = "itemepisodes",
                        DisplayName = string.Format("Episodes ({0})", item.EpisodeCount.Value)
                    });
                }

                if (item.GameCount.HasValue && item.GameCount.Value > 0)
                {
                    views.Add(new TabItem
                    {
                        Name        = "itemgames",
                        DisplayName = string.Format("Games ({0})", item.GameCount.Value)
                    });
                }

                if (item.AlbumCount.HasValue && item.AlbumCount.Value > 0)
                {
                    views.Add(new TabItem
                    {
                        Name        = "itemalbums",
                        DisplayName = string.Format("Albums ({0})", item.AlbumCount.Value)
                    });
                }

                if (item.SongCount.HasValue && item.SongCount.Value > 0)
                {
                    views.Add(new TabItem
                    {
                        Name        = "itemsongs",
                        DisplayName = string.Format("Songs ({0})", item.SongCount.Value)
                    });
                }

                if (item.MusicVideoCount.HasValue && item.MusicVideoCount.Value > 0)
                {
                    views.Add(new TabItem
                    {
                        Name        = "itemmusicvideos",
                        DisplayName = string.Format("Music Videos ({0})", item.MusicVideoCount.Value)
                    });
                }
            }

            if (GalleryViewModel.GetImages(item, _apiClient, null, null, true).Any())
            {
                views.Add(new TabItem
                {
                    Name        = "gallery",
                    DisplayName = "Gallery"
                });
            }

            //if (themeMediaResult.ThemeVideosResult.TotalRecordCount > 0 || themeMediaResult.ThemeSongsResult.TotalRecordCount > 0)
            //{
            //    views.Add(new TabItem
            //    {
            //        Name = "themes",
            //        DisplayName = "Themes"
            //    });
            //}

            return(views);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Attaches People DTO's to a DTOBaseItem
        /// </summary>
        /// <param name="dto">The dto.</param>
        /// <param name="item">The item.</param>
        /// <returns>Task.</returns>
        private void AttachPeople(BaseItemDto dto, BaseItem item)
        {
            // Ordering by person type to ensure actors and artists are at the front.
            // This is taking advantage of the fact that they both begin with A
            // This should be improved in the future
            var people = _libraryManager.GetPeople(item).OrderBy(i => i.SortOrder ?? int.MaxValue)
                         .ThenBy(i =>
            {
                if (i.IsType(PersonType.Actor))
                {
                    return(0);
                }
                if (i.IsType(PersonType.GuestStar))
                {
                    return(1);
                }
                if (i.IsType(PersonType.Director))
                {
                    return(2);
                }
                if (i.IsType(PersonType.Writer))
                {
                    return(3);
                }
                if (i.IsType(PersonType.Producer))
                {
                    return(4);
                }
                if (i.IsType(PersonType.Composer))
                {
                    return(4);
                }

                return(10);
            })
                         .ToList();

            var list = new List <BaseItemPerson>();

            var dictionary = people.Select(p => p.Name)
                             .Distinct(StringComparer.OrdinalIgnoreCase).Select(c =>
            {
                try
                {
                    return(_libraryManager.GetPerson(c));
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error getting person {Name}", c);
                    return(null);
                }
            }).Where(i => i != null)
                             .GroupBy(i => i.Name, StringComparer.OrdinalIgnoreCase)
                             .Select(x => x.First())
                             .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);

            for (var i = 0; i < people.Count; i++)
            {
                var person = people[i];

                var baseItemPerson = new BaseItemPerson
                {
                    Name = person.Name,
                    Role = person.Role,
                    Type = person.Type
                };

                if (dictionary.TryGetValue(person.Name, out Person entity))
                {
                    baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
                    baseItemPerson.Id = entity.Id.ToString("N", CultureInfo.InvariantCulture);
                    list.Add(baseItemPerson);
                }
            }

            dto.People = list.ToArray();
        }
Ejemplo n.º 13
0
        private BaseItemDto GetBaseItemDtoInternal(BaseItem item, DtoOptions options, User user = null, BaseItem owner = null)
        {
            var dto = new BaseItemDto
            {
                ServerId = _appHost.SystemId
            };

            if (item.SourceType == SourceType.Channel)
            {
                dto.SourceType = item.SourceType.ToString();
            }

            if (options.ContainsField(ItemFields.People))
            {
                AttachPeople(dto, item);
            }

            if (options.ContainsField(ItemFields.PrimaryImageAspectRatio))
            {
                try
                {
                    AttachPrimaryImageAspectRatio(dto, item);
                }
                catch (Exception ex)
                {
                    // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
                    _logger.LogError(ex, "Error generating PrimaryImageAspectRatio for {itemName}", item.Name);
                }
            }

            if (options.ContainsField(ItemFields.DisplayPreferencesId))
            {
                dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N", CultureInfo.InvariantCulture);
            }

            if (user != null)
            {
                AttachUserSpecificInfo(dto, item, user, options);
            }

            if (item is IHasMediaSources &&
                options.ContainsField(ItemFields.MediaSources))
            {
                dto.MediaSources = _mediaSourceManager().GetStaticMediaSources(item, true, user).ToArray();

                NormalizeMediaSourceContainers(dto);
            }

            if (options.ContainsField(ItemFields.Studios))
            {
                AttachStudios(dto, item);
            }

            AttachBasicFields(dto, item, owner, options);

            if (options.ContainsField(ItemFields.CanDelete))
            {
                dto.CanDelete = user == null
                    ? item.CanDelete()
                    : item.CanDelete(user);
            }

            if (options.ContainsField(ItemFields.CanDownload))
            {
                dto.CanDownload = user == null
                    ? item.CanDownload()
                    : item.CanDownload(user);
            }

            if (options.ContainsField(ItemFields.Etag))
            {
                dto.Etag = item.GetEtag(user);
            }

            var liveTvManager   = _livetvManager();
            var activeRecording = liveTvManager.GetActiveRecordingInfo(item.Path);

            if (activeRecording != null)
            {
                dto.Type         = "Recording";
                dto.CanDownload  = false;
                dto.RunTimeTicks = null;

                if (!string.IsNullOrEmpty(dto.SeriesName))
                {
                    dto.EpisodeTitle = dto.Name;
                    dto.Name         = dto.SeriesName;
                }
                liveTvManager.AddInfoToRecordingDto(item, dto, activeRecording, user);
            }

            return(dto);
        }
Ejemplo n.º 14
0
        private void AddInheritedImages(BaseItemDto dto, BaseItem item, DtoOptions options, BaseItem owner)
        {
            if (!item.SupportsInheritedParentImages)
            {
                return;
            }

            var logoLimit     = options.GetImageLimit(ImageType.Logo);
            var artLimit      = options.GetImageLimit(ImageType.Art);
            var thumbLimit    = options.GetImageLimit(ImageType.Thumb);
            var backdropLimit = options.GetImageLimit(ImageType.Backdrop);

            // For now. Emby apps are not using this
            artLimit = 0;

            if (logoLimit == 0 && artLimit == 0 && thumbLimit == 0 && backdropLimit == 0)
            {
                return;
            }

            BaseItem parent  = null;
            var      isFirst = true;

            var imageTags = dto.ImageTags;

            while (((!(imageTags != null && imageTags.ContainsKey(ImageType.Logo)) && logoLimit > 0) || (!(imageTags != null && imageTags.ContainsKey(ImageType.Art)) && artLimit > 0) || (!(imageTags != null && imageTags.ContainsKey(ImageType.Thumb)) && thumbLimit > 0) || parent is Series) &&
                   (parent = parent ?? (isFirst ? GetImageDisplayParent(item, item) ?? owner : parent)) != null)
            {
                if (parent == null)
                {
                    break;
                }

                var allImages = parent.ImageInfos;

                if (logoLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Logo)) && dto.ParentLogoItemId == null)
                {
                    var image = allImages.FirstOrDefault(i => i.Type == ImageType.Logo);

                    if (image != null)
                    {
                        dto.ParentLogoItemId   = GetDtoId(parent);
                        dto.ParentLogoImageTag = GetImageCacheTag(parent, image);
                    }
                }
                if (artLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Art)) && dto.ParentArtItemId == null)
                {
                    var image = allImages.FirstOrDefault(i => i.Type == ImageType.Art);

                    if (image != null)
                    {
                        dto.ParentArtItemId   = GetDtoId(parent);
                        dto.ParentArtImageTag = GetImageCacheTag(parent, image);
                    }
                }
                if (thumbLimit > 0 && !(imageTags != null && imageTags.ContainsKey(ImageType.Thumb)) && (dto.ParentThumbItemId == null || parent is Series) && !(parent is ICollectionFolder) && !(parent is UserView))
                {
                    var image = allImages.FirstOrDefault(i => i.Type == ImageType.Thumb);

                    if (image != null)
                    {
                        dto.ParentThumbItemId   = GetDtoId(parent);
                        dto.ParentThumbImageTag = GetImageCacheTag(parent, image);
                    }
                }
                if (backdropLimit > 0 && !((dto.BackdropImageTags != null && dto.BackdropImageTags.Length > 0) || (dto.ParentBackdropImageTags != null && dto.ParentBackdropImageTags.Length > 0)))
                {
                    var images = allImages.Where(i => i.Type == ImageType.Backdrop).Take(backdropLimit).ToList();

                    if (images.Count > 0)
                    {
                        dto.ParentBackdropItemId    = GetDtoId(parent);
                        dto.ParentBackdropImageTags = GetImageTags(parent, images);
                    }
                }

                isFirst = false;

                if (!parent.SupportsInheritedParentImages)
                {
                    break;
                }

                parent = GetImageDisplayParent(parent, item);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Get history from file name.
        /// </summary>
        /// <param name="item">Item.</param>
        /// <param name="fullpath">Full path.</param>
        /// <returns>Srobble history.</returns>
        private async Task <(SimklHistory history, BaseItemDto item)> GetHistoryFromFileName(BaseItemDto item, bool fullpath = true)
        {
            var fname = fullpath ? item.Path : Path.GetFileName(item.Path);
            var mo    = await GetFromFile(fname);

            if (mo == null)
            {
                throw new InvalidDataException("Search file response is null");
            }

            var history = new SimklHistory();

            if (mo.Movie != null &&
                (item.IsMovie == true || item.Type == BaseItemKind.Movie))
            {
                if (!string.Equals(mo.Type, "movie", StringComparison.OrdinalIgnoreCase))
                {
                    throw new InvalidDataException("type != movie (" + mo.Type + ")");
                }

                item.Name           = mo.Movie.Title;
                item.ProductionYear = mo.Movie.Year;
                history.Movies.Add(mo.Movie);
            }
            else if (mo.Episode != null &&
                     mo.Show != null &&
                     (item.IsSeries == true || item.Type == BaseItemKind.Episode))
            {
                if (!string.Equals(mo.Type, "episode", StringComparison.OrdinalIgnoreCase))
                {
                    throw new InvalidDataException("type != episode (" + mo.Type + ")");
                }

                item.Name              = mo.Episode.Title;
                item.SeriesName        = mo.Show.Title;
                item.IndexNumber       = mo.Episode.Episode;
                item.ParentIndexNumber = mo.Episode.Season;
                item.ProductionYear    = mo.Show.Year;
                history.Episodes.Add(mo.Episode);
            }

            return(history, item);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Determines whether [is configured to play] [the specified configuration].
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="item">The item.</param>
        /// <returns><c>true</c> if [is configured to play] [the specified configuration]; otherwise, <c>false</c>.</returns>
        private bool IsConfiguredToPlay(PlayerConfiguration configuration, BaseItemDto item)
        {
            // Make this configurable if/when needed
            if (item.LocationType != LocationType.FileSystem)
            {
                return(false);
            }

            // If it's configured for specific item types
            if (!string.Equals(configuration.MediaType, item.MediaType, StringComparison.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (string.Equals(configuration.MediaType, MediaType.Video))
            {
                if (!item.VideoType.HasValue)
                {
                    return(false);
                }

                if (item.VideoType.Value == VideoType.VideoFile)
                {
                    // If it's configured for specific file extensions
                    if (!IsConfiguredForFileExtension(configuration, item.Path))
                    {
                        return(false);
                    }
                }

                if (item.VideoType.Value == VideoType.BluRay && !configuration.PlayBluray)
                {
                    return(false);
                }
                if (item.VideoType.Value == VideoType.Dvd && !configuration.PlayDvd)
                {
                    return(false);
                }

                if (!configuration.Play3DVideo && item.Video3DFormat.HasValue)
                {
                    return(false);
                }

                if (item.VideoType.Value == VideoType.Iso & configuration.IsoMethod == IsoConfiguration.None)
                {
                    return(false);
                }
            }

            else if (string.Equals(configuration.MediaType, MediaType.Book))
            {
                // If it's configured for specific file extensions
                if (!IsConfiguredForFileExtension(configuration, item.Path))
                {
                    return(false);
                }
            }

            else if (string.Equals(configuration.MediaType, MediaType.Audio))
            {
                // If it's configured for specific file extensions
                if (!IsConfiguredForFileExtension(configuration, item.Path))
                {
                    return(false);
                }
            }

            else if (string.Equals(configuration.MediaType, MediaType.Game))
            {
                // If it's configured for specific file extensions
                if (!string.Equals(item.GameSystem, configuration.GameSystem, StringComparison.OrdinalIgnoreCase))
                {
                    return(false);
                }
            }

            return(true);
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Since it can be slow to make all of these calculations independently, this method will provide a way to do them all at once
        /// </summary>
        /// <param name="folder">The folder.</param>
        /// <param name="user">The user.</param>
        /// <param name="dto">The dto.</param>
        /// <param name="fields">The fields.</param>
        /// <returns>Task.</returns>
        private void SetSpecialCounts(Folder folder, User user, BaseItemDto dto, List <ItemFields> fields)
        {
            var  recursiveItemCount = 0;
            var  unplayed           = 0;
            long runtime            = 0;

            DateTime?dateLastMediaAdded = null;
            double   totalPercentPlayed = 0;

            IEnumerable <BaseItem> children;

            var season = folder as Season;

            if (season != null)
            {
                children = season.GetEpisodes(user).Where(i => i.LocationType != LocationType.Virtual);
            }
            else
            {
                children = folder.GetRecursiveChildren(user)
                           .Where(i => !i.IsFolder && i.LocationType != LocationType.Virtual);
            }

            // Loop through each recursive child
            foreach (var child in children)
            {
                if (!dateLastMediaAdded.HasValue)
                {
                    dateLastMediaAdded = child.DateCreated;
                }
                else
                {
                    dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max();
                }

                var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey());

                recursiveItemCount++;

                var isUnplayed = true;

                // Incrememt totalPercentPlayed
                if (userdata != null)
                {
                    if (userdata.Played)
                    {
                        totalPercentPlayed += 100;

                        isUnplayed = false;
                    }
                    else if (userdata.PlaybackPositionTicks > 0 && child.RunTimeTicks.HasValue && child.RunTimeTicks.Value > 0)
                    {
                        double itemPercent = userdata.PlaybackPositionTicks;
                        itemPercent        /= child.RunTimeTicks.Value;
                        totalPercentPlayed += itemPercent;
                    }
                }

                if (isUnplayed)
                {
                    unplayed++;
                }

                runtime += child.RunTimeTicks ?? 0;
            }

            dto.RecursiveItemCount         = recursiveItemCount;
            dto.UserData.UnplayedItemCount = unplayed;
            dto.RecursiveUnplayedItemCount = unplayed;

            if (recursiveItemCount > 0)
            {
                dto.UserData.PlayedPercentage = totalPercentPlayed / recursiveItemCount;
            }

            if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks))
            {
                dto.CumulativeRunTimeTicks = runtime;
            }

            if (fields.Contains(ItemFields.DateLastMediaAdded))
            {
                dto.DateLastMediaAdded = dateLastMediaAdded;
            }
        }
Ejemplo n.º 18
0
 public bool HasArtImage(BaseItemDto item)
 {
     return(item.ImageTags != null && item.ImageTags.ContainsKey(ImageType.Art));
 }
Ejemplo n.º 19
0
 private void SetGameProperties(BaseItemDto dto, Game item)
 {
     dto.Players            = item.PlayersSupported;
     dto.GameSystem         = item.GameSystem;
     dto.MultiPartGameFiles = item.MultiPartGameFiles;
 }
Ejemplo n.º 20
0
 public bool HasLogo(BaseItemDto item)
 {
     return(item.ImageTags != null && item.ImageTags.ContainsKey(ImageType.Logo));
 }
Ejemplo n.º 21
0
        /// <summary>
        /// Attaches People DTO's to a DTOBaseItem
        /// </summary>
        /// <param name="dto">The dto.</param>
        /// <param name="item">The item.</param>
        /// <returns>Task.</returns>
        private void AttachPeople(BaseItemDto dto, BaseItem item)
        {
            // Ordering by person type to ensure actors and artists are at the front.
            // This is taking advantage of the fact that they both begin with A
            // This should be improved in the future
            var people = item.People.OrderBy(i => i.SortOrder ?? int.MaxValue)
                         .ThenBy(i =>
            {
                if (i.IsType(PersonType.Actor))
                {
                    return(0);
                }
                if (i.IsType(PersonType.GuestStar))
                {
                    return(1);
                }
                if (i.IsType(PersonType.Director))
                {
                    return(2);
                }
                if (i.IsType(PersonType.Writer))
                {
                    return(3);
                }
                if (i.IsType(PersonType.Producer))
                {
                    return(4);
                }
                if (i.IsType(PersonType.Composer))
                {
                    return(4);
                }

                return(10);
            })
                         .ToList();

            // Attach People by transforming them into BaseItemPerson (DTO)
            dto.People = new BaseItemPerson[people.Count];

            var dictionary = people.Select(p => p.Name)
                             .Distinct(StringComparer.OrdinalIgnoreCase).Select(c =>
            {
                try
                {
                    return(_libraryManager.GetPerson(c));
                }
                catch (Exception ex)
                {
                    _logger.ErrorException("Error getting person {0}", ex, c);
                    return(null);
                }
            }).Where(i => i != null)
                             .DistinctBy(i => i.Name)
                             .ToDictionary(i => i.Name, StringComparer.OrdinalIgnoreCase);

            for (var i = 0; i < people.Count; i++)
            {
                var person = people[i];

                var baseItemPerson = new BaseItemPerson
                {
                    Name = person.Name,
                    Role = person.Role,
                    Type = person.Type
                };

                Person entity;

                if (dictionary.TryGetValue(person.Name, out entity))
                {
                    baseItemPerson.PrimaryImageTag = GetImageCacheTag(entity, ImageType.Primary);
                    baseItemPerson.Id = entity.Id.ToString("N");
                }

                dto.People[i] = baseItemPerson;
            }
        }
Ejemplo n.º 22
0
 public bool HasThumb(BaseItemDto item)
 {
     return(item.ImageTags != null && item.ImageTags.ContainsKey(ImageType.Thumb));
 }
Ejemplo n.º 23
0
        private BaseItemDto GetBaseItemDtoInternal(BaseItem item, List <ItemFields> fields, User user = null, BaseItem owner = null)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            if (fields == null)
            {
                throw new ArgumentNullException("fields");
            }

            var dto = new BaseItemDto();

            dto.SupportsPlaylists = item.SupportsAddingToPlaylist;

            if (fields.Contains(ItemFields.People))
            {
                AttachPeople(dto, item);
            }

            if (fields.Contains(ItemFields.PrimaryImageAspectRatio))
            {
                try
                {
                    AttachPrimaryImageAspectRatio(dto, item);
                }
                catch (Exception ex)
                {
                    // Have to use a catch-all unfortunately because some .net image methods throw plain Exceptions
                    _logger.ErrorException("Error generating PrimaryImageAspectRatio for {0}", ex, item.Name);
                }
            }

            if (fields.Contains(ItemFields.DisplayPreferencesId))
            {
                dto.DisplayPreferencesId = item.DisplayPreferencesId.ToString("N");
            }

            if (user != null)
            {
                AttachUserSpecificInfo(dto, item, user, fields);
            }

            var hasMediaSources = item as IHasMediaSources;

            if (hasMediaSources != null)
            {
                if (fields.Contains(ItemFields.MediaSources))
                {
                    if (user == null)
                    {
                        dto.MediaSources = hasMediaSources.GetMediaSources(true).ToList();
                    }
                    else
                    {
                        dto.MediaSources = hasMediaSources.GetMediaSources(true, user).ToList();
                    }
                }
            }

            if (fields.Contains(ItemFields.Studios))
            {
                AttachStudios(dto, item);
            }

            AttachBasicFields(dto, item, owner, fields);

            if (fields.Contains(ItemFields.SyncInfo))
            {
                dto.SupportsSync = _syncManager.SupportsSync(item);
            }

            if (fields.Contains(ItemFields.SoundtrackIds))
            {
                var hasSoundtracks = item as IHasSoundtracks;

                if (hasSoundtracks != null)
                {
                    dto.SoundtrackIds = hasSoundtracks.SoundtrackIds
                                        .Select(i => i.ToString("N"))
                                        .ToArray();
                }
            }

            if (item is Playlist)
            {
                AttachLinkedChildImages(dto, (Folder)item, user);
            }

            return(dto);
        }
Ejemplo n.º 24
0
        public void Play(string path, long startPositionTicks, bool isVideo, MediaSourceInfo mediaSource, BaseItemDto item, bool isFullScreen)
        {
            _isFadingOut = false;
            _isVideo     = isVideo;

            if (mediaSource.Protocol == MediaProtocol.File && mediaSource.VideoType.HasValue)
            {
                if (mediaSource.VideoType.Value == VideoType.VideoFile)
                {
                    if (File.Exists(mediaSource.Path) && !string.Equals(Path.GetExtension(mediaSource.Path), "dvr-ms", StringComparison.OrdinalIgnoreCase))
                    {
                        path = mediaSource.Path;
                    }
                }
                else if (mediaSource.VideoType.Value == VideoType.Iso)
                {
                    if (File.Exists(mediaSource.Path))
                    {
                        path = mediaSource.Path;
                    }
                }
                else
                {
                    if (Directory.Exists(mediaSource.Path))
                    {
                        path = GetFolderRipPath(mediaSource.VideoType.Value, mediaSource.Path);
                    }
                }
            }

            if (_player.PlayState != PlayState.Idle)
            {
                _player.Stop();
            }

            _logger.Info("Playing media source {0}", _json.SerializeToString(mediaSource));

            _player.Play(path, startPositionTicks, isVideo, item, mediaSource, isFullScreen);
        }
Ejemplo n.º 25
0
        private ListPageConfig GetListPageConfig(BaseItemDto item, ViewType context)
        {
            var apiClient = _connectionManager.GetApiClient(item);

            var config = new ListPageConfig();

            if (item.IsType("playlist"))
            {
                config.DefaultViewType = ListViewTypes.List;
            }
            if (context == ViewType.Tv || item.IsType("season"))
            {
                TvViewModel.SetDefaults(config);

                if (item.IsType("season"))
                {
                    config.DefaultViewType = ListViewTypes.List;

                    config.PosterImageWidth      = 480;
                    config.PosterStripImageWidth = 592;
                    config.ThumbImageWidth       = 592;
                }
            }
            else if (context == ViewType.Movies)
            {
                MoviesViewModel.SetDefaults(config);
            }
            else if (context == ViewType.Games)
            {
                GamesViewModel.SetDefaults(config, item.GameSystem);
            }

            if (item.IsFolder)
            {
                config.CustomItemQuery = (vm, displayPreferences) =>
                {
                    if (item.IsType("series"))
                    {
                        return(apiClient.GetSeasonsAsync(new SeasonQuery
                        {
                            UserId = _sessionManager.LocalUserId,
                            SeriesId = item.Id,
                            Fields = FolderPage.QueryFields
                        }, CancellationToken.None));
                    }


                    if (item.IsType("season"))
                    {
                        return(apiClient.GetEpisodesAsync(new EpisodeQuery
                        {
                            UserId = _sessionManager.LocalUserId,
                            SeriesId = item.SeriesId,
                            SeasonId = item.Id,
                            Fields = FolderPage.QueryFields
                        }, CancellationToken.None));
                    }

                    var query = new ItemQuery
                    {
                        UserId = _sessionManager.LocalUserId,

                        ParentId = item.Id,

                        Fields = FolderPage.QueryFields
                    };

                    // Server will sort boxset titles based on server settings
                    if (!item.IsType("boxset"))
                    {
                        query.SortBy    = new[] { ItemSortBy.SortName };
                        query.SortOrder = displayPreferences.SortOrder;
                    }

                    return(apiClient.GetItemsAsync(query, CancellationToken.None));
                };

                if (item.IsType("season") && item.IndexNumber.HasValue && item.IndexNumber.Value > 0)
                {
                    config.DisplayNameGenerator = FolderPage.GetDisplayNameWithAiredSpecial;
                }
            }

            return(config);
        }
        /// <summary>
        /// Initializes a new instance of the MovieCollectionViewModel class.
        /// </summary>
        public MovieCollectionViewModel(INavigationService navigationService, IConnectionManager connectionManager)
            : base(navigationService, connectionManager)
        {
            CreateCollections();
            if (IsInDesignMode)
            {
                UnseenHeader = new BaseItemDto
                {
                    Id       = "6536a66e10417d69105bae71d41a6e6f",
                    Name     = "Jurassic Park",
                    SortName = "Jurassic Park",
                    Overview = "Lots of dinosaurs eating people!",
                    People   = new[]
                    {
                        new BaseItemPerson {
                            Name = "Steven Spielberg", Type = "Director"
                        },
                        new BaseItemPerson {
                            Name = "Sam Neill", Type = "Actor"
                        },
                        new BaseItemPerson {
                            Name = "Richard Attenborough", Type = "Actor"
                        },
                        new BaseItemPerson {
                            Name = "Laura Dern", Type = "Actor"
                        }
                    }
                };

                LatestUnwatched = new List <BaseItemDto>
                {
                    new BaseItemDto
                    {
                        Id       = "6536a66e10417d69105bae71d41a6e6f",
                        Name     = "Jurassic Park",
                        SortName = "Jurassic Park",
                        Overview = "Lots of dinosaurs eating people!",
                        People   = new[]
                        {
                            new BaseItemPerson {
                                Name = "Steven Spielberg", Type = "Director"
                            },
                            new BaseItemPerson {
                                Name = "Sam Neill", Type = "Actor"
                            },
                            new BaseItemPerson {
                                Name = "Richard Attenborough", Type = "Actor"
                            },
                            new BaseItemPerson {
                                Name = "Laura Dern", Type = "Actor"
                            }
                        }
                    },
                    new BaseItemDto
                    {
                        Id       = "6536a66e10417d69105bae71d41a6e6f",
                        Name     = "Jurassic Park",
                        SortName = "Jurassic Park",
                        Overview = "Lots of dinosaurs eating people!",
                        People   = new[]
                        {
                            new BaseItemPerson {
                                Name = "Steven Spielberg", Type = "Director"
                            },
                            new BaseItemPerson {
                                Name = "Sam Neill", Type = "Actor"
                            },
                            new BaseItemPerson {
                                Name = "Richard Attenborough", Type = "Actor"
                            },
                            new BaseItemPerson {
                                Name = "Laura Dern", Type = "Actor"
                            }
                        }
                    }
                };

                Movies = Utils.GroupItemsByName(LatestUnwatched).Result;
            }
        }
Ejemplo n.º 27
0
        private void FillImages(BaseItemDto dto, string seriesName, string programSeriesId)
        {
            var librarySeries = _libraryManager.GetItemList(new InternalItemsQuery
            {
                IncludeItemTypes = new string[] { nameof(Series) },
                Name             = seriesName,
                Limit            = 1,
                ImageTypes       = new ImageType[] { ImageType.Thumb },
                DtoOptions       = new DtoOptions(false)
            }).FirstOrDefault();

            if (librarySeries != null)
            {
                var image = librarySeries.GetImageInfo(ImageType.Thumb, 0);
                if (image != null)
                {
                    try
                    {
                        dto.ParentThumbImageTag = _imageProcessor.GetImageCacheTag(librarySeries, image);
                        dto.ParentThumbItemId   = librarySeries.Id.ToString("N", CultureInfo.InvariantCulture);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error");
                    }
                }

                image = librarySeries.GetImageInfo(ImageType.Backdrop, 0);
                if (image != null)
                {
                    try
                    {
                        dto.ParentBackdropImageTags = new string[]
                        {
                            _imageProcessor.GetImageCacheTag(librarySeries, image)
                        };
                        dto.ParentBackdropItemId = librarySeries.Id.ToString("N", CultureInfo.InvariantCulture);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error");
                    }
                }
            }

            var program = _libraryManager.GetItemList(new InternalItemsQuery
            {
                IncludeItemTypes = new string[] { nameof(LiveTvProgram) },
                ExternalSeriesId = programSeriesId,
                Limit            = 1,
                ImageTypes       = new ImageType[] { ImageType.Primary },
                DtoOptions       = new DtoOptions(false),
                Name             = string.IsNullOrEmpty(programSeriesId) ? seriesName : null
            }).FirstOrDefault();

            if (program != null)
            {
                var image = program.GetImageInfo(ImageType.Primary, 0);
                if (image != null)
                {
                    try
                    {
                        dto.ParentPrimaryImageTag    = _imageProcessor.GetImageCacheTag(program, image);
                        dto.ParentPrimaryImageItemId = program.Id.ToString("N", CultureInfo.InvariantCulture);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, "Error");
                    }
                }

                if (dto.ParentBackdropImageTags == null || dto.ParentBackdropImageTags.Length == 0)
                {
                    image = program.GetImageInfo(ImageType.Backdrop, 0);
                    if (image != null)
                    {
                        try
                        {
                            dto.ParentBackdropImageTags = new string[]
                            {
                                _imageProcessor.GetImageCacheTag(program, image)
                            };

                            dto.ParentBackdropItemId = program.Id.ToString("N", CultureInfo.InvariantCulture);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex, "Error");
                        }
                    }
                }
            }
        }
        internal static async Task <List <PlaylistItem> > GetInstantMixPlaylist(this IApiClient apiClient, BaseItemDto item, IPlaybackManager playbackManager)
        {
            ItemsResult result;
            var         query = new SimilarItemsQuery {
                UserId = AuthenticationService.Current.LoggedInUserId, Id = item.Id, Fields = new [] { ItemFields.MediaSources }
            };

            switch (item.Type)
            {
            case "Audio":
                result = await apiClient.GetInstantMixFromSongAsync(query);

                break;

            case "MusicArtist":
                result = await apiClient.GetInstantMixFromArtistAsync(query);

                break;

            case "MusicAlbum":
                result = await apiClient.GetInstantMixFromAlbumAsync(query);

                break;

            case "Genre":
                result = await apiClient.GetInstantMixFromMusicGenreAsync(query);

                break;

            default:
                return(new List <PlaylistItem>());
            }

            if (result == null || result.Items.IsNullOrEmpty())
            {
                return(new List <PlaylistItem>());
            }

            return(await result.Items.ToList().ToPlayListItems(apiClient, playbackManager));
        }
 public static string EpisodeString(this BaseItemDto item)
 {
     return(string.Format("{0} - {1}x{2} - {3}", item.SeriesName, item.ParentIndexNumber, item.IndexNumber, item.Name));
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Gets the item page.
 /// </summary>
 /// <param name="item">The item.</param>
 /// <param name="context">The context.</param>
 /// <returns>Page.</returns>
 public Page GetItemPage(BaseItemDto item, string context)
 {
     return(null);
 }