public Task <IEnumerable <RemoteImageInfo> > GetImages(BaseItem item, CancellationToken cancellationToken)
        {
            var episode = (Episode)item;
            var series  = episode.Series;

            if (series != null && TvdbSeriesProvider.IsValidSeries(series.ProviderIds))
            {
                // Process images
                var seriesDataPath = TvdbSeriesProvider.GetSeriesDataPath(_config.ApplicationPaths, series.ProviderIds);

                var nodes = TvdbEpisodeProvider.Current.GetEpisodeXmlNodes(seriesDataPath, episode.GetLookupInfo());

                var result = nodes.Select(i => GetImageInfo(i, cancellationToken))
                             .Where(i => i != null)
                             .ToList();

                return(Task.FromResult <IEnumerable <RemoteImageInfo> >(result));
            }

            return(Task.FromResult <IEnumerable <RemoteImageInfo> >(new RemoteImageInfo[] { }));
        }
        public async Task <IEnumerable <RemoteImageInfo> > GetImages(BaseItem item, CancellationToken cancellationToken)
        {
            var season = (Season)item;
            var series = season.Series;

            if (series == null || !season.IndexNumber.HasValue || !TvdbSeriesProvider.IsValidSeries(series.ProviderIds))
            {
                return(new RemoteImageInfo[] { });
            }

            var tvdbId       = Convert.ToInt32(series.GetProviderId(MetadataProviders.Tvdb));
            var seasonNumber = season.IndexNumber.Value;
            var language     = item.GetPreferredMetadataLanguage();
            var remoteImages = new List <RemoteImageInfo>();

            var keyTypes = new[] { KeyType.Season, KeyType.Seasonwide, KeyType.Fanart };

            foreach (var keyType in keyTypes)
            {
                var imageQuery = new ImagesQuery
                {
                    KeyType = keyType,
                    SubKey  = seasonNumber.ToString()
                };
                try
                {
                    var imageResults = await _tvDbClientManager
                                       .GetImagesAsync(tvdbId, imageQuery, language, cancellationToken).ConfigureAwait(false);

                    remoteImages.AddRange(GetImages(imageResults.Data, language));
                }
                catch (TvDbServerException)
                {
                    _logger.LogDebug("No images of type {KeyType} found for series {TvdbId}", keyType, tvdbId);
                }
            }

            return(remoteImages);
        }
示例#3
0
        public async Task <MetadataResult <Episode> > GetMetadata(EpisodeInfo searchInfo, CancellationToken cancellationToken)
        {
            var result = new MetadataResult <Episode>();

            result.QueriedById = true;

            if (TvdbSeriesProvider.IsValidSeries(searchInfo.SeriesProviderIds) &&
                (searchInfo.IndexNumber.HasValue || searchInfo.PremiereDate.HasValue))
            {
                var seriesDataPath = await TvdbSeriesProvider.Current.EnsureSeriesInfo(searchInfo.SeriesProviderIds, null, null, searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);

                if (string.IsNullOrEmpty(seriesDataPath))
                {
                    return(result);
                }

                try
                {
                    result = FetchEpisodeData(searchInfo, seriesDataPath, cancellationToken);
                }
                catch (FileNotFoundException)
                {
                    // Don't fail the provider because this will just keep on going and going.
                }
                catch (IOException)
                {
                    // Don't fail the provider because this will just keep on going and going.
                }
            }
            else
            {
                _logger.LogDebug("No series identity found for {0}", searchInfo.Name);
            }

            return(result);
        }
示例#4
0
        public async Task <IEnumerable <RemoteSearchResult> > GetSearchResults(EpisodeInfo searchInfo, CancellationToken cancellationToken)
        {
            var list = new List <RemoteSearchResult>();

            // The search query must either provide an episode number or date
            if (!searchInfo.IndexNumber.HasValue || !searchInfo.PremiereDate.HasValue)
            {
                return(list);
            }

            if (TvdbSeriesProvider.IsValidSeries(searchInfo.SeriesProviderIds))
            {
                try
                {
                    var episodeTvdbId = searchInfo.GetProviderId(MetadataProviders.Tvdb);
                    if (string.IsNullOrEmpty(episodeTvdbId))
                    {
                        searchInfo.SeriesProviderIds.TryGetValue(MetadataProviders.Tvdb.ToString(),
                                                                 out var seriesTvdbId);
                        episodeTvdbId = await _tvDbClientManager
                                        .GetEpisodeTvdbId(searchInfo, searchInfo.MetadataLanguage, cancellationToken)
                                        .ConfigureAwait(false);

                        if (string.IsNullOrEmpty(episodeTvdbId))
                        {
                            _logger.LogError("Episode {SeasonNumber}x{EpisodeNumber} not found for series {SeriesTvdbId}",
                                             searchInfo.ParentIndexNumber, searchInfo.IndexNumber, seriesTvdbId);
                            return(list);
                        }
                    }

                    var episodeResult = await _tvDbClientManager.GetEpisodesAsync(Convert.ToInt32(episodeTvdbId),
                                                                                  searchInfo.MetadataLanguage, cancellationToken).ConfigureAwait(false);

                    var metadataResult = MapEpisodeToResult(searchInfo, episodeResult.Data);

                    if (metadataResult.HasMetadata)
                    {
                        var item = metadataResult.Item;

                        list.Add(new RemoteSearchResult
                        {
                            IndexNumber        = item.IndexNumber,
                            Name               = item.Name,
                            ParentIndexNumber  = item.ParentIndexNumber,
                            PremiereDate       = item.PremiereDate,
                            ProductionYear     = item.ProductionYear,
                            ProviderIds        = item.ProviderIds,
                            SearchProviderName = Name,
                            IndexNumberEnd     = item.IndexNumberEnd
                        });
                    }
                }
                catch (TvDbServerException e)
                {
                    _logger.LogError(e, "Failed to retrieve episode with id {TvDbId}", searchInfo.IndexNumber);
                }
            }

            return(list);
        }
示例#5
0
        /// <summary>
        /// Runs the specified progress.
        /// </summary>
        /// <param name="progress">The progress.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        public async Task Run(IProgress <double> progress, CancellationToken cancellationToken)
        {
            var path = TvdbSeriesProvider.GetSeriesDataPath(_config.CommonApplicationPaths);

            Directory.CreateDirectory(path);

            var timestampFile = Path.Combine(path, "time.txt");

            var timestampFileInfo = _fileSystem.GetFileInfo(timestampFile);

            // Don't check for tvdb updates anymore frequently than 24 hours
            if (timestampFileInfo.Exists && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(timestampFileInfo)).TotalDays < 1)
            {
                return;
            }

            // Find out the last time we queried tvdb for updates
            var lastUpdateTime = timestampFileInfo.Exists ? File.ReadAllText(timestampFile, Encoding.UTF8) : string.Empty;

            string newUpdateTime;

            var existingDirectories = _fileSystem.GetDirectoryPaths(path)
                                      .Select(Path.GetFileName)
                                      .ToList();

            var seriesList = _libraryManager.GetItemList(new InternalItemsQuery()
            {
                IncludeItemTypes             = new[] { typeof(Series).Name },
                Recursive                    = true,
                GroupByPresentationUniqueKey = false,
                DtoOptions                   = new DtoOptions(false)
                {
                    EnableImages = false
                }
            }).Cast <Series>()
                             .ToList();

            var seriesIdsInLibrary = seriesList
                                     .Where(i => !string.IsNullOrEmpty(i.GetProviderId(MetadataProviders.Tvdb)))
                                     .Select(i => i.GetProviderId(MetadataProviders.Tvdb))
                                     .ToList();

            var missingSeries = seriesIdsInLibrary.Except(existingDirectories, StringComparer.OrdinalIgnoreCase)
                                .ToList();

            var enableInternetProviders = seriesList.Count == 0 ? false : seriesList[0].IsMetadataFetcherEnabled(_libraryManager.GetLibraryOptions(seriesList[0]), TvdbSeriesProvider.Current.Name);

            if (!enableInternetProviders)
            {
                progress.Report(100);
                return;
            }

            // If this is our first time, update all series
            if (string.IsNullOrEmpty(lastUpdateTime))
            {
                // First get tvdb server time
                using (var response = await _httpClient.SendAsync(new HttpRequestOptions
                {
                    Url = ServerTimeUrl,
                    CancellationToken = cancellationToken,
                    EnableHttpCompression = true,
                    BufferContent = false
                }, "GET").ConfigureAwait(false))
                {
                    // First get tvdb server time
                    using (var stream = response.Content)
                    {
                        newUpdateTime = GetUpdateTime(stream);
                    }
                }

                existingDirectories.AddRange(missingSeries);

                await UpdateSeries(existingDirectories, path, null, progress, cancellationToken).ConfigureAwait(false);
            }
            else
            {
                var seriesToUpdate = await GetSeriesIdsToUpdate(existingDirectories, lastUpdateTime, cancellationToken).ConfigureAwait(false);

                newUpdateTime = seriesToUpdate.Item2;

                long.TryParse(lastUpdateTime, NumberStyles.Any, UsCulture, out var lastUpdateValue);

                var nullableUpdateValue = lastUpdateValue == 0 ? (long?)null : lastUpdateValue;

                var listToUpdate = seriesToUpdate.Item1.ToList();
                listToUpdate.AddRange(missingSeries);

                await UpdateSeries(listToUpdate, path, nullableUpdateValue, progress, cancellationToken).ConfigureAwait(false);
            }

            File.WriteAllText(timestampFile, newUpdateTime, Encoding.UTF8);
            progress.Report(100);
        }