Beispiel #1
0
        static void Main(string[] args)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(Directory.GetCurrentDirectory())
                         .AddJsonFile("appsettings.json", false, false)
                         .Build();
            var loggerFactory = new LoggerFactory().AddConsole().AddFile("logs/ts-{Date}.txt");;
            var logger        = loggerFactory.CreateLogger <Program>();

            var httpClient = new HttpClient();

            ServicePointManager.UseNagleAlgorithm      = false;
            ServicePointManager.Expect100Continue      = false;
            ServicePointManager.DefaultConnectionLimit = 100;

            var retryPolicy =
                Policy
                .HandleResult <HttpResponseMessage>(e => e.StatusCode == (System.Net.HttpStatusCode) 429)
                .WaitAndRetryForeverAsync(attempt => TimeSpan.FromSeconds(5));

            var tvMazeClient    = new TvMazeClient(httpClient, retryPolicy);
            var storageDbClient = new DocumentClient(new Uri(config["StorageEndpoint"]), config["StorageKey"]);

            logger.LogInformation($"Storage db URI {config["StorageEndpoint"]}");
            var storage  = new Storage(config, storageDbClient);
            var scrapper = new Scrapper(tvMazeClient, storage, loggerFactory, int.Parse(config["DegreeOfParallelism"]));

            logger.LogInformation("Initialized all objects. Starting process of grabbing info.");

            MainAsync(scrapper, logger).GetAwaiter().GetResult();
        }
Beispiel #2
0
        public async Task ShowSearch()
        {
            var sut    = new TvMazeClient();
            var result = await sut.ShowSearch("star trek");

            result.Count.Should().Be(9);
        }
Beispiel #3
0
        public async Task WhenApiCallSucceeds_AndContainsShowInformation_ReturnsShowEntity()
        {
            const int    showId           = 1;
            const string mockShowResponse =
                "{\"id\":1,\"url\":\"http://www.tvmaze.com/shows/1/under-the-dome\",\"name\":\"Under the Dome\",\"type\":\"Scripted\",\"language\":\"English\",\"genres\":[\"Drama\",\"Science-Fiction\",\"Thriller\"],\"status\":\"Ended\",\"runtime\":60,\"premiered\":\"2013-06-24\",\"officialSite\":\"http://www.cbs.com/shows/under-the-dome/\",\"schedule\":{\"time\":\"22:00\",\"days\":[\"Thursday\"]},\"rating\":{\"average\":6.5},\"weight\":92,\"network\":{\"id\":2,\"name\":\"CBS\",\"country\":{\"name\":\"United States\",\"code\":\"US\",\"timezone\":\"America/New_York\"}},\"webChannel\":null,\"externals\":{\"tvrage\":25988,\"thetvdb\":264492,\"imdb\":\"tt1553656\"},\"image\":{\"medium\":\"http://static.tvmaze.com/uploads/images/medium_portrait/81/202627.jpg\",\"original\":\"http://static.tvmaze.com/uploads/images/original_untouched/81/202627.jpg\"},\"summary\":\"<p><b>Under the Dome</b> is the story of a small town that is suddenly and inexplicably sealed off from the rest of the world by an enormous transparent dome. The town's inhabitants must deal with surviving the post-apocalyptic conditions while searching for answers about the dome, where it came from and if and when it will go away.</p>\",\"updated\":1562326291,\"_links\":{\"self\":{\"href\":\"http://api.tvmaze.com/shows/1\"},\"previousepisode\":{\"href\":\"http://api.tvmaze.com/episodes/185054\"}}}";
            const string mockClientResponse =
                @"[{""person"":{""id"":1,""url"":""http://www.tvmaze.com/people/1/mike-vogel"",""name"":""Mike Vogel"",""country"":{""name"":""United States"",""code"":""US"",""timezone"":""America/New_York""},""birthday"":""1979-07-17"",""deathday"":null,""gender"":""Male"",""image"":{""medium"":""http://static.tvmaze.com/uploads/images/medium_portrait/0/1815.jpg"",""original"":""http://static.tvmaze.com/uploads/images/original_untouched/0/1815.jpg""},""_links"":{""self"":{""href"":""http://api.tvmaze.com/people/1""}}},""character"":{""id"":1,""url"":""http://www.tvmaze.com/characters/1/under-the-dome-dale-barbie-barbara"",""name"":""Dale \""Barbie\"" Barbara"",""image"":{""medium"":""http://static.tvmaze.com/uploads/images/medium_portrait/0/3.jpg"",""original"":""http://static.tvmaze.com/uploads/images/original_untouched/0/3.jpg""},""_links"":{""self"":{""href"":""http://api.tvmaze.com/characters/1""}}},""self"":false,""voice"":false},{""person"":{""id"":2,""url"":""http://www.tvmaze.com/people/2/rachelle-lefevre"",""name"":""Rachelle Lefevre"",""country"":{""name"":""Canada"",""code"":""CA"",""timezone"":""America/Halifax""},""birthday"":""1979-02-01"",""deathday"":null,""gender"":""Female"",""image"":{""medium"":""http://static.tvmaze.com/uploads/images/medium_portrait/82/207417.jpg"",""original"":""http://static.tvmaze.com/uploads/images/original_untouched/82/207417.jpg""},""_links"":{""self"":{""href"":""http://api.tvmaze.com/people/2""}}},""character"":{""id"":2,""url"":""http://www.tvmaze.com/characters/2/under-the-dome-julia-shumway"",""name"":""Julia Shumway"",""image"":{""medium"":""http://static.tvmaze.com/uploads/images/medium_portrait/0/6.jpg"",""original"":""http://static.tvmaze.com/uploads/images/original_untouched/0/6.jpg""},""_links"":{""self"":{""href"":""http://api.tvmaze.com/characters/2""}}},""self"":false,""voice"":false}]";

            var mockShowResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(mockShowResponse)
            };

            var mockCastResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(mockClientResponse)
            };

            var handler = new HttpMessageHandlerStub();

            handler.EndpointResponses.Add($"/shows/{showId}", mockShowResponseMessage);
            handler.EndpointResponses.Add($"/shows/{showId}/cast", mockCastResponseMessage);

            var client = CreateClient(handler);

            _clientFactoryMock.Setup(m => m.CreateClient(It.IsAny <string>()))
            .Returns(client);

            var sut = new TvMazeClient(_clientFactoryMock.Object);

            var result = await sut.GetShowById(showId);

            result.Should().BeSuccess();
        }
Beispiel #4
0
        public async Task GetShowWithEpisodes()
        {
            var sut    = new TvMazeClient();
            var result = await sut.GetShowWithEpisodes("survivors");

            result.Name.Should().Be("Survivors");
            result.Embedded.Episodes.Count.Should().Be(12);
        }
Beispiel #5
0
        /// <inheritdoc />
        public async Task <IEnumerable <RemoteImageInfo> > GetImages(BaseItem item, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogDebug("[GetImages] {name}", item.Name);
                var episode = (Episode)item;
                var series  = episode.Series;
                if (series == null)
                {
                    // Episode or series is null.
                    return(Enumerable.Empty <RemoteImageInfo>());
                }

                var tvMazeId = TvHelpers.GetTvMazeId(episode.Series.ProviderIds);
                if (tvMazeId == null)
                {
                    // Requires series TVMaze id.
                    return(Enumerable.Empty <RemoteImageInfo>());
                }

                if (episode.IndexNumber == null || episode.ParentIndexNumber == null)
                {
                    // Missing episode or season number.
                    return(Enumerable.Empty <RemoteImageInfo>());
                }

                var tvMazeClient  = new TvMazeClient(_httpClientFactory.CreateClient(NamedClient.Default));
                var tvMazeEpisode = await tvMazeClient.Shows.GetEpisodeByNumberAsync(tvMazeId.Value, episode.ParentIndexNumber.Value, episode.IndexNumber.Value).ConfigureAwait(false);

                if (tvMazeEpisode == null)
                {
                    return(Enumerable.Empty <RemoteImageInfo>());
                }

                var imageResults = new List <RemoteImageInfo>();
                if (tvMazeEpisode.Image?.Original != null)
                {
                    imageResults.Add(new RemoteImageInfo
                    {
                        Url          = tvMazeEpisode.Image.Original,
                        ProviderName = TvMazePlugin.ProviderName,
                        Language     = "en",
                        Type         = ImageType.Primary
                    });
                }

                _logger.LogInformation("[GetImages] Images found for {name}: {@images}", item.Name, imageResults);
                return(imageResults);
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "[GetImages]");
                return(Enumerable.Empty <RemoteImageInfo>());
            }
        }
        /// <inheritdoc />
        public async Task <IEnumerable <RemoteImageInfo> > GetImages(BaseItem item, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogDebug("[GetImages] {name}", item.Name);
                var series   = (Series)item;
                var tvMazeId = TvHelpers.GetTvMazeId(series.ProviderIds);
                if (tvMazeId == null)
                {
                    // Requires series tv maze id.
                    _logger.LogWarning("[GetImages] tv maze id is required;");
                    return(Enumerable.Empty <RemoteImageInfo>());
                }

                var tvMazeClient = new TvMazeClient(_httpClientFactory.CreateClient(NamedClient.Default));
                var images       = await tvMazeClient.Shows.GetShowImagesAsync(tvMazeId.Value).ConfigureAwait(false);

                if (images == null)
                {
                    _logger.LogDebug("[GetImages] No images found.");
                    return(Enumerable.Empty <RemoteImageInfo>());
                }

                var imageResults = new List <RemoteImageInfo>();
                // Order by type, then by Main=true
                foreach (var image in images.OrderBy(o => o.Type).ThenByDescending(o => o.Main))
                {
                    if (image.Resolutions.Original != null && image.Type.HasValue)
                    {
                        imageResults.Add(new RemoteImageInfo
                        {
                            Url          = image.Resolutions.Original.Url,
                            ProviderName = TvMazePlugin.ProviderName,
                            Language     = "en",
                            Type         = GetImageType(image.Type.Value)
                        });
                    }
                }

                _logger.LogInformation("[GetImages] Images found for {name}: {@images}", item.Name, imageResults);
                return(imageResults);
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "[GetImages]");
                return(Enumerable.Empty <RemoteImageInfo>());
            }
        }
        private async Task <Episode?> GetMetadataInternal(EpisodeInfo info)
        {
            var tvMazeId = TvHelpers.GetTvMazeId(info.SeriesProviderIds);

            if (!tvMazeId.HasValue)
            {
                // Requires a TVMaze id.
                return(null);
            }

            // The search query must provide an episode number.
            if (!info.IndexNumber.HasValue || !info.ParentIndexNumber.HasValue)
            {
                return(null);
            }

            var tvMazeClient  = new TvMazeClient(_httpClientFactory.CreateClient(NamedClient.Default), new RetryRateLimitingStrategy());
            var tvMazeEpisode = await tvMazeClient.Shows.GetEpisodeByNumberAsync(tvMazeId.Value, info.ParentIndexNumber.Value, info.IndexNumber.Value).ConfigureAwait(false);

            if (tvMazeEpisode == null)
            {
                // No episode found.
                return(null);
            }

            var episode = new Episode
            {
                Name              = tvMazeEpisode.Name,
                IndexNumber       = tvMazeEpisode.Number,
                ParentIndexNumber = tvMazeEpisode.Season
            };

            if (DateTime.TryParse(tvMazeEpisode.AirDate, out var airDate))
            {
                episode.PremiereDate = airDate;
            }

            if (tvMazeEpisode.Runtime.HasValue)
            {
                episode.RunTimeTicks = TimeSpan.FromTicks(tvMazeEpisode.Runtime.Value).Ticks;
            }

            episode.Overview = TvHelpers.GetStrippedHtml(tvMazeEpisode.Summary);
            episode.SetProviderId(TvMazePlugin.ProviderId, tvMazeEpisode.Id.ToString(CultureInfo.InvariantCulture));

            return(episode);
        }
Beispiel #8
0
        public async void ThrowExceptionRateLimitingStrategy()
        {
            // arrange
            var strategy     = new ThrowExceptionRateLimitingStrategy();
            var tvMazeClient = new TvMazeClient(new HttpClient(), strategy);
            var beforeCount  = _httpTest.CallLog.Count;

            // act
            Func <Task> action = async() =>
            {
                await tvMazeClient.Shows.GetShowMainInformationAsync(1);
            };

            // assert
            await action.Should().ThrowAsync <UnexpectedResponseStatusException>();

            _httpTest.CallLog.Count.Should().Be(beforeCount + 1);
        }
Beispiel #9
0
        public void GetFullSchedule_MockWebApi_FullSchedule()
        {
            // Arrange
            var json     = File.ReadAllText(Path.Combine(BasePath, DomainObjectFactoryTests.JSON_DATA_PATH, "schedule.json"));
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/schedule/full")
            .Respond("application/json", json);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act
            var schedule = tvMazeClient.GetFullSchedule();

            // Assert
            Assert.IsNotNull(schedule);
            Assert.IsNotEmpty(schedule.Episodes);
            mockHttp.VerifyNoOutstandingExpectation();
        }
Beispiel #10
0
        public void GetFullScheduleAsync_MockWebApiInternalServerError_HttpRequestExtException()
        {
            // Arrange
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/schedule/full")
            .Respond(HttpStatusCode.InternalServerError);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act and Assert
            AsyncTestDelegate act = async() => await tvMazeClient.GetFullScheduleAsync();

            //Assert.That(act, Throws.TypeOf<HttpRequestException>());

            var ex = Assert.ThrowsAsync <HttpRequestExtException>(act);

            Assert.That(ex.StatusCode, Is.EqualTo(HttpStatusCode.InternalServerError));
        }
Beispiel #11
0
        public async void RetryRateLimitingStrategy()
        {
            // arrange
            const int expectedRetries = 5;
            var       strategy        = new RetryRateLimitingStrategy(expectedRetries, TimeSpan.FromMilliseconds(1));
            var       tvMazeClient    = new TvMazeClient(new HttpClient(), strategy);
            var       beforeCount     = _httpTest.CallLog.Count;

            // act
            Func <Task> action = async() =>
            {
                await tvMazeClient.Shows.GetShowMainInformationAsync(1);
            };

            // assert
            await action.Should().ThrowAsync <UnexpectedResponseStatusException>();

            _httpTest.CallLog.Count.Should().Be(beforeCount + expectedRetries + 1);
        }
Beispiel #12
0
        public void GetShowUpdates_MockWebApi_ShowsUpdates()
        {
            // Arrange
            var json     = File.ReadAllText(Path.Combine(BasePath, DomainObjectFactoryTests.JSON_DATA_PATH, "show_updates.json"));
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/updates/shows")
            .Respond("application/json", json);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act
            var showUpdates = tvMazeClient.GetShowUpdates();

            // Assert
            Assert.IsNotNull(showUpdates);
            Assert.IsNotEmpty(showUpdates);
            mockHttp.VerifyNoOutstandingExpectation();
        }
Beispiel #13
0
        public async Task GetAllShowsAsync_MockWebApi_Page0_Shows()
        {
            // Arrange
            var json     = File.ReadAllText(Path.Combine(BasePath, DomainObjectFactoryTests.JSON_DATA_PATH, "cast.json"));
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/shows")
            .Respond("application/json", json);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act
            var shows = await tvMazeClient.GetAllShowsAsync();

            // Assert
            Assert.IsNotNull(shows);
            Assert.IsNotEmpty(shows);
            mockHttp.VerifyNoOutstandingExpectation();
        }
Beispiel #14
0
        private async Task <Season?> GetSeasonInternal(SeasonInfo info)
        {
            var tvMazeId = TvHelpers.GetTvMazeId(info.SeriesProviderIds);

            if (tvMazeId == null)
            {
                // Requires series TVMaze id.
                return(null);
            }

            var tvMazeClient  = new TvMazeClient(_httpClientFactory.CreateClient(NamedClient.Default), new RetryRateLimitingStrategy());
            var tvMazeSeasons = await tvMazeClient.Shows.GetShowSeasonsAsync(tvMazeId.Value).ConfigureAwait(false);

            if (tvMazeSeasons == null)
            {
                return(null);
            }

            foreach (var tvMazeSeason in tvMazeSeasons)
            {
                if (tvMazeSeason.Number == info.IndexNumber)
                {
                    var season = new Season
                    {
                        Name        = tvMazeSeason.Name,
                        IndexNumber = tvMazeSeason.Number
                    };

                    if (DateTime.TryParse(tvMazeSeason.PremiereDate, out var premiereDate))
                    {
                        season.PremiereDate   = premiereDate;
                        season.ProductionYear = premiereDate.Year;
                    }

                    season.SetProviderId(TvMazePlugin.ProviderId, tvMazeSeason.Id.ToString(CultureInfo.InvariantCulture));
                    return(season);
                }
            }

            // Season not found.
            return(null);
        }
Beispiel #15
0
        public void GetGetShow_MockWebApi_ShowId_Show()
        {
            // Arrange
            const int showId   = 1;
            var       json     = File.ReadAllText(Path.Combine(BasePath, DomainObjectFactoryTests.JSON_DATA_PATH, "show.json"));
            var       mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/shows/{showId}")
            .Respond("application/json", json);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act
            var show = tvMazeClient.GetShow(showId);

            // Assert
            Assert.IsNotNull(show);
            Assert.AreEqual(showId, show.Id);
            mockHttp.VerifyNoOutstandingExpectation();
        }
Beispiel #16
0
        public async Task WhenRateLimitReached_ReturnsFailedResult_WithThrottledException()
        {
            const int showId = 1;
            var       apiLimitResponseMessage = new HttpResponseMessage((HttpStatusCode)429);

            var handler = new HttpMessageHandlerStub();

            handler.EndpointResponses.Add($"/shows/{showId}", apiLimitResponseMessage);

            var client = CreateClient(handler);

            _clientFactoryMock.Setup(m => m.CreateClient(It.IsAny <string>()))
            .Returns(client);

            var sut = new TvMazeClient(_clientFactoryMock.Object);

            var result = await sut.GetShowById(showId);

            result.Should().BeFailed().Which.Should().BeOfType <ThrottleException>();
        }
Beispiel #17
0
        public async Task ShowSingleSearchAsync_MockWebApi_SearchQuery_Show()
        {
            // Arrange
            const string query    = "under the dome";
            var          json     = File.ReadAllText(Path.Combine(BasePath, DomainObjectFactoryTests.JSON_DATA_PATH, "show.json"));
            var          mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/singlesearch/shows")
            .Respond("application/json", json);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act
            var show = await tvMazeClient.ShowSingleSearchAsync(query);

            // Assert
            Assert.IsNotNull(show);
            Assert.AreEqual(1, show.Id);
            mockHttp.VerifyNoOutstandingExpectation();
        }
Beispiel #18
0
        public async Task GetCastCreditsAsync_MockWebApi_PersonId_CastCredits()
        {
            // Arrange
            const int personId = 1;
            var       json     = File.ReadAllText(Path.Combine(BasePath, DomainObjectFactoryTests.JSON_DATA_PATH, "person_castcredits.json"));
            var       mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/people/{personId}/castcredits")
            .Respond("application/json", json);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act
            var castCredits = await tvMazeClient.GetCastCreditsAsync(personId);

            // Assert
            Assert.IsNotNull(castCredits);
            Assert.IsNotEmpty(castCredits);
            mockHttp.VerifyNoOutstandingExpectation();
        }
Beispiel #19
0
        public async Task GetScheduleAsync_MockWebApi_DefaultQueryParams_Schedule()
        {
            // Arrange
            var json     = File.ReadAllText(Path.Combine(BasePath, DomainObjectFactoryTests.JSON_DATA_PATH, "schedule.json"));
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/schedule")
            .With(x => string.IsNullOrEmpty(x.RequestUri.Query))
            .Respond("application/json", json);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act
            var schedule = await tvMazeClient.GetScheduleAsync();

            // Assert
            Assert.IsNotNull(schedule);
            Assert.IsNotEmpty(schedule.Episodes);
            mockHttp.VerifyNoOutstandingExpectation();
        }
Beispiel #20
0
        public async Task GetShowCrewAsync_MockWebApi_ShowId_ShowCrew()
        {
            // Arrange
            const int showId   = 1;
            var       json     = File.ReadAllText(Path.Combine(BasePath, DomainObjectFactoryTests.JSON_DATA_PATH, "crew.json"));
            var       mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/shows/{showId}/crew")
            .Respond("application/json", json);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act
            var crew = await tvMazeClient.GetShowCrewAsync(showId);

            // Assert
            Assert.IsNotNull(crew);
            Assert.IsNotEmpty(crew);
            mockHttp.VerifyNoOutstandingExpectation();
        }
Beispiel #21
0
        private async Task <Show?> GetIdentifyShow(ItemLookupInfo lookupInfo, TvMazeClient tvMazeClient)
        {
            var searchResults = (await tvMazeClient.Search.ShowSearchAsync(lookupInfo.Name?.Trim()).ConfigureAwait(false)).ToList();

            if (searchResults.Count == 0)
            {
                // No search results.
                return(null);
            }

            if (lookupInfo.Year.HasValue)
            {
                return(searchResults.OrderBy(
                           s => DateTime.TryParse(s.Show.Premiered, out var premiereDate) ? Math.Abs(premiereDate.Year - lookupInfo.Year.Value) : 1)
                       .ThenByDescending(s => s.Score)
                       .FirstOrDefault()?.Show);
            }

            return(searchResults[0].Show);
        }
Beispiel #22
0
        private async Task <IEnumerable <RemoteImageInfo> > GetSeasonImagesInternal(IHasProviderIds series, int seasonNumber)
        {
            var tvMazeId = TvHelpers.GetTvMazeId(series.ProviderIds);

            if (tvMazeId == null)
            {
                // Requires series TVMaze id.
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var tvMazeClient  = new TvMazeClient(_httpClientFactory.CreateClient(NamedClient.Default), new RetryRateLimitingStrategy());
            var tvMazeSeasons = await tvMazeClient.Shows.GetShowSeasonsAsync(tvMazeId.Value).ConfigureAwait(false);

            if (tvMazeSeasons == null)
            {
                return(Enumerable.Empty <RemoteImageInfo>());
            }

            var imageResults = new List <RemoteImageInfo>();

            foreach (var tvMazeSeason in tvMazeSeasons)
            {
                if (tvMazeSeason.Number == seasonNumber)
                {
                    if (tvMazeSeason.Image?.Original != null)
                    {
                        imageResults.Add(new RemoteImageInfo
                        {
                            Url          = tvMazeSeason.Image.Original,
                            ProviderName = TvMazePlugin.ProviderName,
                            Language     = "en",
                            Type         = ImageType.Primary
                        });
                    }

                    break;
                }
            }

            return(imageResults);
        }
Beispiel #23
0
        public async Task ShowLookupAsync_MockWebApi_ImdbId_Show()
        {
            // Arrange
            const string imdbId   = "tt0944947";
            var          json     = File.ReadAllText(Path.Combine(BasePath, DomainObjectFactoryTests.JSON_DATA_PATH, "show.json"));
            var          mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/lookup/shows")
            .WithQueryString("imdb", imdbId)
            .Respond("application/json", json);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act
            var show = await tvMazeClient.ShowLookupAsync(imdbId, ExternalTvShowProvider.Imdb);

            // Assert
            Assert.IsNotNull(show);
            Assert.AreEqual(1, show.Id);
            mockHttp.VerifyNoOutstandingExpectation();
        }
Beispiel #24
0
        public async Task GetShowEpisodesAsync_MockWebApi_ShowId_AirDate_EpisodeListByAirDate()
        {
            // Arrange
            const int showId   = 1;
            var       json     = File.ReadAllText(Path.Combine(BasePath, DomainObjectFactoryTests.JSON_DATA_PATH, "episodes.json"));
            var       mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/shows/{showId}/episodesbydate")
            .WithQueryString("date", "2013-07-01")
            .Respond("application/json", json);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act
            var episodeList = await tvMazeClient.GetShowEpisodesAsync(showId, new DateTime(2013, 7, 1));

            // Assert
            Assert.IsNotNull(episodeList);
            Assert.IsNotEmpty(episodeList);
            mockHttp.VerifyNoOutstandingExpectation();
        }
Beispiel #25
0
        public async Task GetScheduleAsync_MockWebApi_WithQueryParams_Schedule()
        {
            // Arrange
            var json     = File.ReadAllText(Path.Combine(BasePath, DomainObjectFactoryTests.JSON_DATA_PATH, "schedule.json"));
            var mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/schedule?country=US&date=2014-12-01")
            .WithQueryString("country", "US")
            .WithQueryString("date", "2014-12-01")
            .Respond("application/json", json);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act
            var schedule = await tvMazeClient.GetScheduleAsync("US", new DateTime(2014, 12, 01));

            // Assert
            Assert.IsNotNull(schedule);
            Assert.IsNotEmpty(schedule.Episodes);
            mockHttp.VerifyNoOutstandingExpectation();
        }
Beispiel #26
0
        public void GetShowEpisodeList_MockWebApi_ShowId_With_Specials_EpisodeList()
        {
            // Arrange
            const int showId   = 1;
            var       json     = File.ReadAllText(Path.Combine(BasePath, DomainObjectFactoryTests.JSON_DATA_PATH, "episodes.json"));
            var       mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/shows/{showId}/episodes")
            .WithQueryString("specials", "1")
            .Respond("application/json", json);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act
            var episodeList = tvMazeClient.GetShowEpisodeList(showId);

            // Assert
            Assert.IsNotNull(episodeList);
            Assert.IsNotEmpty(episodeList);
            mockHttp.VerifyNoOutstandingExpectation();
        }
Beispiel #27
0
        public async Task GetGetPersonInfoAsync_MockWebApi_PersonId_WithQueryParam_Person()
        {
            // Arrange
            const int personId = 1;
            var       json     = File.ReadAllText(Path.Combine(BasePath, DomainObjectFactoryTests.JSON_DATA_PATH, "person_embed_castcredits.json"));
            var       mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/people/{personId}")
            .WithQueryString("embed", "castcredits")
            .Respond("application/json", json);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act
            var person = await tvMazeClient.GetPersonInfoAsync(personId, EmbedType.CastCredits);

            // Assert
            Assert.IsNotNull(person);
            Assert.AreEqual(personId, person.Id);
            Assert.IsNotEmpty(person.CastCredits);
            mockHttp.VerifyNoOutstandingExpectation();
        }
Beispiel #28
0
        public async Task GetShowAsync_MockWebApi_ShowId_WithQueryParam_Show()
        {
            // Arrange
            const int showId   = 1;
            var       json     = File.ReadAllText(Path.Combine(BasePath, DomainObjectFactoryTests.JSON_DATA_PATH, "show_embed_cast.json"));
            var       mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/shows/{showId}")
            .WithQueryString("embed", "cast")
            .Respond("application/json", json);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act
            var show = await tvMazeClient.GetShowAsync(showId, EmbedType.Cast);

            // Assert
            Assert.IsNotNull(show);
            Assert.AreEqual(showId, show.Id);
            Assert.IsNotEmpty(show.Casts);
            mockHttp.VerifyNoOutstandingExpectation();
        }
Beispiel #29
0
        /// <inheritdoc />
        public async Task <IEnumerable <RemoteSearchResult> > GetSearchResults(SeriesInfo searchInfo, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogDebug("[GetSearchResults] Starting for {Name}", searchInfo.Name);
                var tvMazeClient      = new TvMazeClient(_httpClientFactory.CreateClient(NamedClient.Default), new RetryRateLimitingStrategy());
                var showSearchResults = (await tvMazeClient.Search.ShowSearchAsync(searchInfo.Name?.Trim()).ConfigureAwait(false)).ToList();
                _logger.LogDebug("[GetSearchResults] Result count for {Name}: {Count}", searchInfo.Name, showSearchResults.Count);
                var searchResults = new List <RemoteSearchResult>();
                foreach (var show in showSearchResults)
                {
                    _logger.LogDebug("[GetSearchResults] Result for {Name}: {@Show}", searchInfo.Name, show);
                    var searchResult = new RemoteSearchResult
                    {
                        Name = show.Show.Name,
                        SearchProviderName = Name,
                        ImageUrl           = show.Show.Image?.Original
                    };

                    if (DateTime.TryParse(show.Show.Premiered, out var premiereDate))
                    {
                        searchResult.PremiereDate   = premiereDate;
                        searchResult.ProductionYear = premiereDate.Year;
                    }

                    SetProviderIds(show.Show, searchResult);
                    searchResults.Add(searchResult);
                }

                _logger.LogDebug("[GetSearchResults] Result for {Name}: {@Series}", searchInfo.Name, searchResults);
                return(searchResults);
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, "[GetSearchResults] Error searching for {Name}", searchInfo.Name);
                return(Enumerable.Empty <RemoteSearchResult>());
            }
        }
Beispiel #30
0
        public async Task PeopleSearchAsync_MockWebApi_SearchQuery_PeopleSearchResults()
        {
            // Arrange
            const string query    = "lauren";
            var          json     = File.ReadAllText(Path.Combine(BasePath, DomainObjectFactoryTests.JSON_DATA_PATH, "search_people.json"));
            var          mockHttp = new MockHttpMessageHandler();

            mockHttp.Expect($"{BASE_API_URL}/search/people")
            .WithQueryString("q", query)
            .Respond("application/json", json);

            var tvMazeClient = new TvMazeClient(BASE_API_URL, mockHttp.ToHttpClient());

            // Act
            var results = await tvMazeClient.PeopleSearchAsync(query);

            // Assert
            Assert.IsNotNull(results);
            Assert.IsNotEmpty(results);
            Assert.IsInstanceOf <Person>(results.ToArray()[0].Element);
            Assert.AreEqual(172658, results.ToArray()[0].Element.Id);
            mockHttp.VerifyNoOutstandingExpectation();
        }