Ejemplo n.º 1
0
        public static bool Filter(BaseItem item, User user, InternalItemsQuery query, IUserDataManager userDataManager, ILibraryManager libraryManager)
        {
            if (query.MediaTypes.Length > 0 && !query.MediaTypes.Contains(item.MediaType ?? string.Empty, StringComparer.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (query.IncludeItemTypes.Length > 0 && !query.IncludeItemTypes.Contains(item.GetClientTypeName(), StringComparer.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (query.ExcludeItemTypes.Length > 0 && query.ExcludeItemTypes.Contains(item.GetClientTypeName(), StringComparer.OrdinalIgnoreCase))
            {
                return(false);
            }

            if (query.IsVirtualItem.HasValue && item.IsVirtualItem != query.IsVirtualItem.Value)
            {
                return(false);
            }

            if (query.IsFolder.HasValue && query.IsFolder.Value != item.IsFolder)
            {
                return(false);
            }

            UserItemData userData = null;

            if (query.IsLiked.HasValue)
            {
                userData = userDataManager.GetUserData(user, item);

                if (!userData.Likes.HasValue || userData.Likes != query.IsLiked.Value)
                {
                    return(false);
                }
            }

            if (query.IsFavoriteOrLiked.HasValue)
            {
                userData = userData ?? userDataManager.GetUserData(user, item);
                var isFavoriteOrLiked = userData.IsFavorite || (userData.Likes ?? false);

                if (isFavoriteOrLiked != query.IsFavoriteOrLiked.Value)
                {
                    return(false);
                }
            }

            if (query.IsFavorite.HasValue)
            {
                userData = userData ?? userDataManager.GetUserData(user, item);

                if (userData.IsFavorite != query.IsFavorite.Value)
                {
                    return(false);
                }
            }

            if (query.IsResumable.HasValue)
            {
                userData = userData ?? userDataManager.GetUserData(user, item);
                var isResumable = userData.PlaybackPositionTicks > 0;

                if (isResumable != query.IsResumable.Value)
                {
                    return(false);
                }
            }

            if (query.IsPlayed.HasValue)
            {
                if (item.IsPlayed(user) != query.IsPlayed.Value)
                {
                    return(false);
                }
            }

            // Filter by Video3DFormat
            if (query.Is3D.HasValue)
            {
                var val   = query.Is3D.Value;
                var video = item as Video;

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

            /*
             * f**k - fix this
             * if (query.IsHD.HasValue)
             * {
             *  if (item.IsHD != query.IsHD.Value)
             *  {
             *      return false;
             *  }
             * }
             */

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

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

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

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

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

                var hasValue = !string.IsNullOrEmpty(item.GetProviderId(MetadataProvider.Imdb));

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

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

                var hasValue = !string.IsNullOrEmpty(item.GetProviderId(MetadataProvider.Tmdb));

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

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

                var hasValue = !string.IsNullOrEmpty(item.GetProviderId(MetadataProvider.Tvdb));

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

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

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

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

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

                var isPlaceHolder = false;

                if (item is ISupportsPlaceHolders hasPlaceHolder)
                {
                    isPlaceHolder = hasPlaceHolder.IsPlaceHolder;
                }

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

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

                if (item is IHasSpecialFeatures movie)
                {
                    var ok = filterValue
                        ? movie.SpecialFeatureIds.Count > 0
                        : movie.SpecialFeatureIds.Count == 0;

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

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

                var video = item as Video;

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

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

                var rating = item.CustomRating;

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

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

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

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

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

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

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

                var themeCount = item.ThemeSongIds.Length;
                var ok         = filterValue ? themeCount > 0 : themeCount == 0;

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

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

                var themeCount = item.ThemeVideoIds.Length;
                var ok         = filterValue ? themeCount > 0 : themeCount == 0;

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

            // Apply genre filter
            if (query.Genres.Count > 0 && !query.Genres.Any(v => item.Genres.Contains(v, StringComparer.OrdinalIgnoreCase)))
            {
                return(false);
            }

            // Filter by VideoType
            if (query.VideoTypes.Length > 0)
            {
                var video = item as Video;
                if (video == null || !query.VideoTypes.Contains(video.VideoType))
                {
                    return(false);
                }
            }

            if (query.ImageTypes.Length > 0 && !query.ImageTypes.Any(item.HasImage))
            {
                return(false);
            }

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

            // Apply genre filter
            if (query.GenreIds.Count > 0 && !query.GenreIds.Any(id =>
            {
                var genreItem = libraryManager.GetItemById(id);
                return(genreItem != null && item.Genres.Contains(genreItem.Name, StringComparer.OrdinalIgnoreCase));
            }))
            {
                return(false);
            }

            // Apply year filter
            if (query.Years.Length > 0)
            {
                if (!(item.ProductionYear.HasValue && query.Years.Contains(item.ProductionYear.Value)))
                {
                    return(false);
                }
            }

            // Apply official rating filter
            if (query.OfficialRatings.Length > 0 && !query.OfficialRatings.Contains(item.OfficialRating ?? string.Empty))
            {
                return(false);
            }

            if (query.ItemIds.Length > 0)
            {
                if (!query.ItemIds.Contains(item.Id))
                {
                    return(false);
                }
            }

            // Apply tag filter
            var tags = query.Tags;

            if (tags.Length > 0)
            {
                if (!tags.Any(v => item.Tags.Contains(v, StringComparer.OrdinalIgnoreCase)))
                {
                    return(false);
                }
            }

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

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

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

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

            if (query.MinIndexNumber.HasValue)
            {
                var val = query.MinIndexNumber.Value;

                if (!(item.IndexNumber.HasValue && item.IndexNumber.Value >= val))
                {
                    return(false);
                }
            }

            if (query.MinPremiereDate.HasValue)
            {
                var val = query.MinPremiereDate.Value;

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

            if (query.MaxPremiereDate.HasValue)
            {
                var val = query.MaxPremiereDate.Value;

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

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

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

            if (query.SeriesStatuses.Length > 0)
            {
                var ok = new[] { item }.OfType <Series>().Any(p => p.Status.HasValue && query.SeriesStatuses.Contains(p.Status.Value));
                if (!ok)
                {
                    return(false);
                }
            }

            if (query.AiredDuringSeason.HasValue)
            {
                var episode = item as Episode;

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

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

            return(true);
        }
Ejemplo n.º 2
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;
            }

            dto.ImageBlurHashes = new Dictionary <ImageType, Dictionary <string, string> >();

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

            if (backdropLimit > 0)
            {
                dto.BackdropImageTags = GetTagsAndFillBlurhashes(dto, item, ImageType.Backdrop, backdropLimit);
            }

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

            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)))
                {
                    if (options.GetImageLimit(image.Type) > 0)
                    {
                        var tag = GetTagAndFillBlurhash(dto, 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 = GetTagAndFillBlurhash(dto, 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))
            {
                allExtras = item.GetExtras().ToArray();
                dto.SpecialFeatureCount = allExtras.Count(i => i.ExtraType.HasValue && BaseItem.DisplayExtraTypes.Contains(i.ExtraType.Value));
            }

            if (options.ContainsField(ItemFields.LocalTrailerCount))
            {
                allExtras ??= item.GetExtras().ToArray();
                dto.LocalTrailerCount = allExtras.Count(i => i.ExtraType == ExtraType.Trailer);

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

            // 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 = GetTagAndFillBlurhash(dto, 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 = GetTagAndFillBlurhash(dto, 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.º 3
0
 private static string GetUniqueSeriesKey(Series series)
 {
     return(series.GetPresentationUniqueKey());
 }
Ejemplo n.º 4
0
        public static Task<Model.Epg> GetMetadata(Model.Epg epg, CancellationToken cancellationToken)
        {
            return Task.Run(async () =>
            {
                var seriesItem = new MediaBrowser.Controller.Entities.TV.Series();
                var seriesDataPath = "";
                var seriesId = "";
                var language = String.IsNullOrWhiteSpace(Plugin.Instance.Configuration.Provider) ? "en" : "pt";
                var country = String.IsNullOrWhiteSpace(Plugin.Instance.Configuration.Provider) ? "us" : "br";

                if (Plugin.Instance.Configuration.Provider == "CLARO" && (epg.IsMovie || epg.IsShopping || epg.IsSports || epg.IsNews)) return epg;

                try
                {
                    var seriesInfo = new SeriesInfo
                    {
                        Name = epg.Title,
                        ParentIndexNumber = epg.SeasonNumber,
                        IndexNumber = epg.EpisodeNumber,
                        MetadataLanguage = language,
                        MetadataCountryCode = country
                    };

                    if (Cache[epg.Title] == null)
                    {
                        MetadataResult<MediaBrowser.Controller.Entities.TV.Series> omdbSeries;

                        var omdbItemProvider = new OmdbItemProvider(LiveTvService.JsonSerializer,
                            LiveTvService.HttpClient, LiveTvService.Logger, LiveTvService.LibraryManager, LiveTvService.FileSystem, LiveTvService.Config);

                        omdbSeries = await omdbItemProvider.GetMetadata(seriesInfo, cancellationToken);

                        var imdbId = omdbSeries.Item.GetProviderId(MetadataProviders.Imdb);

                        if (!String.IsNullOrWhiteSpace(imdbId))
                        {
                            using (var result = await LiveTvService.HttpClient.Get(new HttpRequestOptions
                            {
                                Url = "http://www.thetvdb.com/api/GetSeriesByRemoteID.php?imdbid=" + imdbId  + "&language=" + language,
                                ResourcePool = new SemaphoreSlim(2, 2),
                                CancellationToken = cancellationToken

                            }).ConfigureAwait(false))
                            {
                                var doc = new XmlDocument();
                                doc.Load(result);

                                if (doc.HasChildNodes)
                                {
                                    var node = doc.SelectSingleNode("//Series/seriesid");

                                    if (node != null)
                                    {
                                        seriesId = node.InnerText;
                                    }
                                }
                            }

                            seriesInfo.ProviderIds = new Dictionary<string, string>
                            {
                                {
                                    MetadataProviders.Tvdb.ToString(),
                                    seriesId
                                },
                                {
                                    MetadataProviders.Imdb.ToString(),
                                    imdbId
                                }
                            };
                        }

                        var tvdbSeries = await TvdbSeriesProvider.Current.GetMetadata(seriesInfo, cancellationToken);

                        seriesItem = tvdbSeries.Item;

                        Cache.Add(epg.Title, seriesItem, DateTimeOffset.Now.AddDays(1));
                    }
                    else seriesItem = Cache[epg.Title] as MediaBrowser.Controller.Entities.TV.Series;

                    seriesId = seriesItem.GetProviderId(MetadataProviders.Tvdb);

                    seriesDataPath = TvdbSeriesProvider.GetSeriesDataPath(
                        LiveTvService.Config.ApplicationPaths,
                        new Dictionary<string, string>
                        {
                            {
                                MetadataProviders.Tvdb.ToString(),
                                seriesId
                            }
                        });

                    Logger.Debug("seriesDataPath: " + seriesDataPath);

                    foreach (var providerId in seriesItem.ProviderIds)
                    {
                        Logger.Debug("providerId: " + providerId);
                    }

                    epg.EpisodeId = seriesItem.Id.ToString();
                    epg.Etag = seriesItem.ExternalEtag;
                    epg.Name = !String.IsNullOrEmpty(seriesItem.Name) ? seriesItem.Name : epg.Title;
                    epg.Name = !String.IsNullOrEmpty(seriesItem.OriginalTitle) ? seriesItem.OriginalTitle : epg.Name;
                    epg.OriginalAirDate = seriesItem.PremiereDate;
                    epg.ProductionYear = seriesItem.ProductionYear;
                    epg.SeriesId = seriesId;
                    epg.Overview = seriesItem.Overview;
                    epg.Genres = seriesItem.Genres;
                    epg.OfficialRating = seriesItem.OfficialRating;
                    epg.CommunityRating = seriesItem.CommunityRating;
                    epg.ProviderIds = seriesItem.ProviderIds;

                    epg.IsSeries = true;
                    epg.IsMovie = false;
                    epg.IsSports = false;
                    epg.IsNews = false;
                    epg.IsKids = seriesItem.Genres.Any(a => a.Contains(Constant.Genre.Kids) || a.Contains(Constant.Genre.Children));
                    epg.IsSports = seriesItem.Genres.Any(a => a.Contains(Constant.Genre.Sports));
                    epg.IsRepeat = seriesItem.PremiereDate == null || seriesItem.PremiereDate < DateTime.UtcNow.AddDays(-7);
                }
                catch (Exception exception)
                {
                    //Logger.Error("Series provider error: " + exception.Message);
                    //Logger.ErrorException("Series provider error", exception);
                }

                try
                {
                    if (seriesItem != null && epg != null && epg.SeasonNumber > 0 && epg.EpisodeNumber > 0)
                    {
                        var episodeInfo = new EpisodeInfo
                        {
                            ParentIndexNumber = epg.SeasonNumber,
                            IndexNumber = epg.EpisodeNumber,
                            SeriesProviderIds = seriesItem.ProviderIds,
                            MetadataLanguage = seriesItem.GetPreferredMetadataLanguage(),
                            MetadataCountryCode = seriesItem.GetPreferredMetadataCountryCode()
                        };

                        var tvdbEpisode = await TvdbEpisodeProvider.Current.GetMetadata(episodeInfo, cancellationToken);
                        var episode = tvdbEpisode.Item;

                        if (episode != null)
                        {
                            epg.EpisodeId = episode.Id.ToString();
                            epg.Etag = episode.ExternalEtag;
                            epg.EpisodeTitle = episode.Name;
                            epg.OriginalAirDate = episode.PremiereDate;
                            epg.Overview = episode.Overview;
                            epg.ProviderIds = episode.ProviderIds;

                            epg.IsRepeat = episode.PremiereDate == null || episode.PremiereDate < DateTime.UtcNow.AddDays(-7);
                        }
                        else
                        {
                            Logger.Debug("episode null");
                        }
                    }
                }
                catch (Exception exception)
                {
                    //Logger.Error("Series episode error: " + exception.Message);
                    //Logger.ErrorException("Series episode provider error", exception);
                }

                try
                {
                    if (seriesItem != null && epg != null && !String.IsNullOrWhiteSpace(seriesId))
                    {
                        var imageProvider = new FanartSeriesProvider(LiveTvService.Config, LiveTvService.HttpClient, LiveTvService.FileSystem, LiveTvService.JsonSerializer);

                        var images = await imageProvider.GetImages(seriesItem, cancellationToken);

                        if (images.Count(c => c.Type == ImageType.Primary) == 0)
                        {
                            var tvdbSeriesImageProvider = new TvdbSeriesImageProvider(LiveTvService.Config, LiveTvService.HttpClient, LiveTvService.FileSystem);

                            images = await tvdbSeriesImageProvider.GetImages(seriesItem, cancellationToken);
                        }

                        var image = images.OrderByDescending(o => o.VoteCount).FirstOrDefault(q => q.Type == ImageType.Primary && q.Language == language);

                        epg.ImageUrl = image != null ? image.Url : null;
                    }
                }
                catch (Exception exception)
                {
                    //Logger.Error("Series image error: " + exception.Message);
                    //Logger.ErrorException("Series image provider error", exception);
                }

                return epg;
            }, cancellationToken);
        }