/// <inheritdoc />
 public IShouldMapTestBuilder ShouldMap(Action<IHttpRequestBuilder> httpRequestBuilder)
 {
     var httpBuilder = new HttpRequestBuilder(this.HttpContext);
     httpRequestBuilder(httpBuilder);
     httpBuilder.ApplyTo(this.HttpContext.Request);
     return this.ShouldMap(this.HttpContext);
 }
        public void Given_a_SocketException_is_thrown_When_requesting_Then_an_HttpSocketConnectionException_is_thrown()
        {
            // setup
            var target = new HttpSocketBuilder()
                         .GivenAnHttpRequest()
                         .GivenASocketExceptionIsThrown()
                         .Build();

            var request = new HttpRequestBuilder()
                          .SetUrl("")
                          .Build();

            TestDelegate method = () => target.Request(request);

            // execution/assertion
            var exception = Assert.Throws(typeof(HttpSocketConnectionException), method);

            Assert.AreEqual("The socket threw a SocketException",
                            exception.Message, "The exception message was not correct");
        }
        public async Task SendRequest_WithCorrelateOptionsNonTransactionIncludeInResponse_ResponseWithoutCorrelationHeaders()
        {
            // Arrange
            var options = new TestApiServerOptions()
                          .ConfigureServices(services => services.AddHttpCorrelation(opt => opt.Transaction.IncludeInResponse = false))
                          .PreConfigure(app => app.UseHttpCorrelation());

            await using (var service = await TestApiServer.StartNewAsync(options, _logger))
            {
                // Act
                var request = HttpRequestBuilder.Get(CorrelationController.GetRoute);
                using (HttpResponseMessage response = await service.SendAsync(request))
                {
                    // Assert
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
                    Assert.Contains(response.Headers, header => header.Key == DefaultOperationId);
                    Assert.DoesNotContain(response.Headers, header => header.Key == DefaultTransactionId);
                }
            }
        }
示例#4
0
        public string GetToken(RarbgSettings settings)
        {
            return(_tokenCache.Get(settings.BaseUrl, () =>
            {
                var requestBuilder = new HttpRequestBuilder(settings.BaseUrl.Trim('/'))
                                     .WithRateLimit(3.0)
                                     .Resource("/pubapi_v2.php?get_token=get_token&app_id=Lidarr")
                                     .Accept(HttpAccept.Json);

                if (settings.CaptchaToken.IsNotNullOrWhiteSpace())
                {
                    requestBuilder.UseSimplifiedUserAgent = true;
                    requestBuilder.SetCookie("cf_clearance", settings.CaptchaToken);
                }

                var response = _httpClient.Get <JObject>(requestBuilder.Build());

                return response.Resource["token"].ToString();
            }, TimeSpan.FromMinutes(14.0)));
        }
示例#5
0
        public IEnumerator Registerv2(RegisterUserRequestv2 registerUserRequest,
                                      ResultCallback <RegisterUserResponse> callback)
        {
            Report.GetFunctionLog(this.GetType().Name);
            Assert.IsNotNull(registerUserRequest, "Register failed. registerUserRequest is null!");

            var request = HttpRequestBuilder.CreatePost(this.baseUrl + "/v4/public/namespaces/{namespace}/users")
                          .WithPathParam("namespace", this.@namespace)
                          .WithContentType(MediaType.ApplicationJson)
                          .WithBody(registerUserRequest.ToUtf8Json())
                          .GetResult();

            IHttpResponse response = null;

            yield return(this.httpWorker.SendRequest(request, rsp => response = rsp));

            var result = response.TryParseJson <RegisterUserResponse>();

            callback.Try(result);
        }
示例#6
0
        public IEnumerator GetPlatformLinks(ResultCallback <PagedPlatformLinks> callback)
        {
            Report.GetFunctionLog(this.GetType().Name);
            var request = HttpRequestBuilder
                          .CreateGet(this.baseUrl + "/v3/public/namespaces/{namespace}/users/{userId}/platforms")
                          .WithPathParam("namespace", this.@namespace)
                          .WithPathParam("userId", this.session.UserId)
                          .WithContentType(MediaType.ApplicationJson)
                          .WithBearerAuth(this.session.AuthorizationToken)
                          .Accepts(MediaType.ApplicationJson)
                          .GetResult();

            IHttpResponse response = null;

            yield return(this.httpWorker.SendRequest(request, rsp => response = rsp));

            var result = response.TryParseJson <PagedPlatformLinks>();

            callback.Try(result);
        }
示例#7
0
        public IEnumerator UnlinkOtherPlatform(PlatformType platformType, ResultCallback callback)
        {
            Report.GetFunctionLog(this.GetType().Name);

            var request = HttpRequestBuilder
                          .CreateDelete(this.baseUrl + "/v3/public/namespaces/{namespace}/users/me/platforms/{platformId}")
                          .WithPathParam("namespace", this.@namespace)
                          .WithPathParam("platformId", platformType.ToString().ToLower())
                          .WithBearerAuth(this.session.AuthorizationToken)
                          .WithContentType(MediaType.TextPlain)
                          .GetResult();

            IHttpResponse response = null;

            yield return(this.httpWorker.SendRequest(request, rsp => response = rsp));

            Result result = response.TryParse();

            callback.Try(result);
        }
示例#8
0
        public IEnumerator UpgradeWithPlayerPortal(string returnUrl, int ttl, ResultCallback <UpgradeUserRequest> callback)
        {
            Report.GetFunctionLog(this.GetType().Name);
            Assert.IsNotNull(returnUrl, "Upgrade failed. return url is null!");

            var request = HttpRequestBuilder
                          .CreatePost(this.apiBaseUrl + "/v1/public/temporarysessions")
                          .WithBearerAuth(this.session.AuthorizationToken)
                          .WithContentType(MediaType.ApplicationJson)
                          .WithBody(string.Format("{{\"return_url\": \"{0}\", \"ttl\": {1}}}", returnUrl, ttl))
                          .GetResult();

            IHttpResponse response = null;

            yield return(this.httpWorker.SendRequest(request, rsp => response = rsp));

            var result = response.TryParseJson <UpgradeUserRequest>();

            callback.Try(result);
        }
        public IEnumerator LoginWithDeviceId(ResultCallback callback)
        {
            Report.GetFunctionLog(this.GetType().Name);
            DeviceProvider deviceProvider = DeviceProvider.GetFromSystemInfo();

            IHttpRequest request = HttpRequestBuilder.CreatePost(this.baseUrl + "/v1/login/platforms/{platformId}")
                                   .WithPathParam("platformId", deviceProvider.DeviceType)
                                   .WithBasicAuth(this.clientId, this.clientSecret)
                                   .WithContentType(MediaType.ApplicationForm)
                                   .Accepts(MediaType.ApplicationJson)
                                   .WithFormParam("device_id", deviceProvider.DeviceId)
                                   .WithFormParam("namespace", this.@namespace)
                                   .GetResult();

            IHttpResponse response = null;

            yield return(this.httpWorker.SendRequest(request, rsp => response = rsp));

            TrySetAccessToken(callback, response);
        }
        public IEnumerator LoginWithAuthorizationCode(string code, ResultCallback callback)
        {
            Report.GetFunctionLog(this.GetType().Name);
            Assert.IsNotNull(code, "Code parameter is null.");

            var request = HttpRequestBuilder.CreatePost(this.baseUrl + "/v1/login/code")
                          .WithBasicAuth(this.clientId, this.clientSecret)
                          .WithContentType(MediaType.ApplicationForm)
                          .Accepts(MediaType.ApplicationJson)
                          .WithFormParam("grant_type", "authorization_code")
                          .WithFormParam("code", code)
                          .WithFormParam("redirect_uri", this.redirecUri)
                          .GetResult();

            IHttpResponse response = null;

            yield return(this.httpWorker.SendRequest(request, rsp => response = rsp));

            TrySetAccessToken(callback, response);
        }
        public async Task <List <UserInfo> > GetFans(string uid, CancellationToken token, int pageIndex = 1,
                                                     int pageSize = 10)
        {
            _logger.LogInformation($"Get Fans: {uid}, {pageIndex}, {pageSize}");
            var request = HttpRequestBuilder
                          .Post(LiveMeUrls.Fans)
                          .WithFormData(new
            {
                access_token = uid,     // strange but that's the way it is.
                page_index   = pageIndex,
                page_size    = pageSize
            });

            var raw = await _client.Fetch(request, token);

            dynamic json  = JsonConvert.DeserializeObject(raw);
            var     users = json.data;

            return(JsonConvert.DeserializeObject <List <UserInfo> >(users.ToString()));
        }
        public IEnumerator GetCurrencyList(string @namespace, string accessToken, ResultCallback <CurrencyList[]> callback)
        {
            Report.GetFunctionLog(this.GetType().Name);
            Assert.IsNotNull(@namespace, "Can't Get Currency List! Namespace parameter is null!");
            Assert.IsNotNull(accessToken, "Can't Get Currency List! accessToken parameter is null!");

            var request = HttpRequestBuilder.CreateGet(this.baseUrl + "/public/namespaces/{namespace}/currencies")
                          .WithPathParam("namespace", @namespace)
                          .WithBearerAuth(accessToken)
                          .Accepts(MediaType.ApplicationJson)
                          .GetResult();

            IHttpResponse response = null;

            yield return(this.httpClient.SendRequest(request, rsp => response = rsp));

            var result = response.TryParseJson <CurrencyList[]>();

            callback.Try(result);
        }
        public async Task AuthorizedRoute_WithSharedAccessKey_ShouldFailWithKeyNotFoundException_WhenNoSecretProviderWasRegistered()
        {
            // Arrange
            string secretValue = $"secret-{Guid.NewGuid()}";
            var    options     = new TestApiServerOptions();

            await using (var server = await TestApiServer.StartNewAsync(options, _logger))
            {
                // Act
                var request = HttpRequestBuilder
                              .Get(SharedAccessKeyAuthenticationController.AuthorizedGetRoute)
                              .WithHeader(HeaderName, secretValue);

                using (HttpResponseMessage response = await server.SendAsync(request))
                {
                    // Assert
                    Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
                }
            }
        }
示例#14
0
        public void leak_test_over_stream_object()
        {
            var start = Connections();
            var rq    = new HttpRequestBuilder().Get(new Uri("http://localhost:55672/api/vhosts")).BasicAuthentication("guest", "guest").Build();

            for (int i = 0; i < 512; i++)
            {
                var result = _subject.Request(rq);
                using (var stream = result.BodyReader)
                {
                    Assert.That(start, Is.Not.EqualTo(Connections()));
                    Console.WriteLine(stream.ReadStringToLength());
                }
            }
            Thread.Sleep(500);
            var end = Connections();

            Console.WriteLine("Before: " + start + ", after: " + end);
            Assert.That(end, Is.LessThanOrEqualTo(start));
        }
示例#15
0
        public void SendPayload(DiscordPayload payload, DiscordSettings settings)
        {
            try
            {
                var request = new HttpRequestBuilder(settings.WebHookUrl)
                              .Accept(HttpAccept.Json)
                              .Build();

                request.Method = HttpMethod.Post;
                request.Headers.ContentType = "application/json";
                request.SetContent(payload.ToJson());

                _httpClient.Execute(request);
            }
            catch (HttpException ex)
            {
                _logger.Error(ex, "Unable to post payload {0}", payload);
                throw new DiscordException("Unable to post payload", ex);
            }
        }
示例#16
0
        public void should_follow_redirects_to_https()
        {
            if (typeof(TDispatcher) == typeof(ManagedHttpDispatcher) && PlatformInfo.IsMono)
            {
                Assert.Ignore("Will fail on tls1.2 via managed dispatcher, ignore.");
            }

            var request = new HttpRequestBuilder($"http://{_httpBinHost}/redirect-to")
                          .AddQueryParam("url", $"https://sonarr.tv/")
                          .Build();

            request.AllowAutoRedirect = true;

            var response = Subject.Get(request);

            response.StatusCode.Should().Be(HttpStatusCode.OK);
            response.Content.Should().Contain("Sonarr");

            ExceptionVerification.ExpectedErrors(0);
        }
示例#17
0
        public IEnumerator SendProtectedEvents(List <TelemetryBody> events, string accessToken, ResultCallback callback)
        {
            Assert.IsNotNull(events, nameof(events) + " is null.");

            var request = HttpRequestBuilder
                          .CreatePost(this.baseUrl + "/v1/protected/events")
                          .WithContentType(MediaType.ApplicationJson)
                          .WithBody(events.ToUtf8Json())
                          .WithBearerAuth(accessToken)
                          .Accepts(MediaType.ApplicationJson)
                          .GetResult();

            IHttpResponse response = null;

            yield return(this.httpClient.SendRequest(request, rsp => response = rsp));

            var result = response.TryParse();

            callback.Try(result);
        }
示例#18
0
        private T ProcessRequest <T>(HadoukenSettings settings, string method, params object[] parameters)
        {
            var baseUrl        = HttpRequestBuilder.BuildBaseUrl(settings.UseSsl, settings.Host, settings.Port, "api");
            var requestBuilder = new JsonRpcRequestBuilder(baseUrl, method, parameters);

            requestBuilder.LogResponseContent = true;
            requestBuilder.NetworkCredential  = new NetworkCredential(settings.Username, settings.Password);
            requestBuilder.Headers.Add("Accept-Encoding", "gzip,deflate");

            var httpRequest = requestBuilder.Build();
            var response    = _httpClient.Execute(httpRequest);
            var result      = Json.Deserialize <JsonRpcResponse <T> >(response.Content);

            if (result.Error != null)
            {
                throw new DownloadClientException("Error response received from Hadouken: {0}", result.Error.ToString());
            }

            return(result.Result);
        }
        public IEnumerator Logout(ResultCallback callback)
        {
            Report.GetFunctionLog(this.GetType().Name);
            var request = HttpRequestBuilder.CreatePost(this.baseUrl + "/oauth/revoke/token")
                          .WithBearerAuth(this.AuthorizationToken)
                          .WithContentType(MediaType.ApplicationForm)
                          .Accepts(MediaType.ApplicationJson)
                          .WithFormParam("token", this.AuthorizationToken)
                          .GetResult();

            IHttpResponse response = null;

            yield return(this.httpWorker.SendRequest(request, rsp => response = rsp));

            this.tokenData = null;
            var result = response.TryParse();

            this.coroutineRunner.Stop(this.maintainAccessTokenCoroutine);
            callback.Try(result);
        }
示例#20
0
        public void read_from_iana()
        {
            var rq = new HttpRequestBuilder().Get(new Uri("http://www.iana.org/domains/reserved")).Build();

            using (var result = _subject.Request(rq))
            {
                var body = result.BodyReader.ReadStringToLength();

                Console.WriteLine(Write(result.Headers));

                Console.WriteLine("Expected " + result.BodyReader.ExpectedLength + ", got " + body.Length);
                Console.WriteLine(body);
                Assert.That(body, Contains.Substring("<html"));
                Assert.That(body, Contains.Substring("</html>"), "didn't read to end");
                Assert.That(result.BodyReader.Complete, Is.True, "reader did not complete");

                // this server returns an invalid length!
                Assert.That(result.BodyReader.ExpectedLength, Is.GreaterThanOrEqualTo(body.Length), "length was not correct");
            }
        }
示例#21
0
        public override async Task <byte[]> Download(Uri link)
        {
            if (Settings.Freeleech)
            {
                _logger.Debug($"Attempting to use freeleech token for {link.AbsoluteUri}");

                var idMatch = TorrentIdRegex.Match(link.AbsoluteUri);
                if (idMatch.Success)
                {
                    var id           = int.Parse(idMatch.Groups["id"].Value);
                    var timestamp    = DateTimeOffset.Now.ToUnixTimeSeconds();
                    var freeleechUrl = Settings.BaseUrl + $"json/bonusBuy.php/{timestamp}";

                    var freeleechRequest = new HttpRequestBuilder(freeleechUrl)
                                           .AddQueryParam("spendtype", "personalFL")
                                           .AddQueryParam("torrentid", id)
                                           .AddQueryParam("timestamp", timestamp.ToString())
                                           .Build();

                    var indexerReq = new IndexerRequest(freeleechRequest);
                    var response   = await FetchIndexerResponse(indexerReq).ConfigureAwait(false);

                    var resource = Json.Deserialize <MyAnonamouseFreeleechResponse>(response.Content);

                    if (resource.Success)
                    {
                        _logger.Debug($"Successfully to used freeleech token for torrentid ${id}");
                    }
                    else
                    {
                        _logger.Debug($"Failed to use freeleech token: ${resource.Error}");
                    }
                }
                else
                {
                    _logger.Debug($"Could not get torrent id from link ${link.AbsoluteUri}, skipping freeleech");
                }
            }

            return(await base.Download(link).ConfigureAwait(false));
        }
示例#22
0
        public IEnumerator CreateSlot(string @namespace, string userId, string accessToken, byte[] data,
                                      string filename, ResultCallback <Slot> callback)
        {
            Report.GetFunctionLog(this.GetType().Name);
            Assert.IsNotNull(@namespace, "Can't create a slot! namespace parameter is null!");
            Assert.IsNotNull(userId, "Can't create a slot! userId parameter is null!");
            Assert.IsNotNull(accessToken, "Can't create a slot! accessToken parameter is null!");
            Assert.IsNotNull(data, "Can't create a slot! data parameter is null!");
            Assert.IsNotNull(filename, "Can't create a slot! filename parameter is null!");

            string checkSum;

            using (MD5 md5 = MD5.Create())
            {
                byte[] computeHash = md5.ComputeHash(data);
                checkSum = BitConverter.ToString(computeHash).Replace("-", "");
            }

            FormDataContent formDataContent = new FormDataContent();

            formDataContent.Add(filename, data);

            var request = HttpRequestBuilder
                          .CreatePost(this.baseUrl + "/public/namespaces/{namespace}/users/{userId}/slots")
                          .WithPathParam("namespace", @namespace)
                          .WithPathParam("userId", userId)
                          .WithQueryParam("checksum", checkSum)
                          .Accepts(MediaType.ApplicationJson)
                          .WithBearerAuth(accessToken)
                          .WithContentType(formDataContent.GetMediaType())
                          .WithBody(formDataContent)
                          .GetResult();

            IHttpResponse response = null;

            yield return(this.httpWorker.SendRequest(request, rsp => response = rsp));

            var result = response.TryParseJson <Slot>();

            callback.Try(result);
        }
示例#23
0
        public async Task TestFunctionShouldReturnErrorMessageIfExceptionIsThrown1Async()
        {
            //Given
            var alarmService    = new Mock <IAlarmService>();
            var watchService    = new Mock <IWatchService>();
            var machineService  = new Mock <IMachineService>();
            var alarmLogService = new Mock <IAlarmLogService>();
            var notificationConnectionSetting = new Mock <INotificationHubConnectionSettings>();
            var notificationHub = new Mock <INotificationHubClient>();

            var body    = new { MachineId = "test-id-1", AlarmCode = 42 };
            var machine = new AlarmSystem.Core.Entity.DB.Machine
            {
                MachineId = "machine-id-test",
                Type      = "machine-type-test",
                Name      = "machine-name-test"
            };
            var alarm = new AlarmSystem.Core.Entity.DB.Alarm
            {
                AlarmId     = 1,
                Code        = 1,
                Description = "alarm-description-test"
            };

            var req = new HttpRequestBuilder().Body(body).Build();

            var alarmSubs = new List <AlarmWatch>();

            //When
            alarmService.Setup(als => als.GetAlarmByCode(It.IsAny <int>())).Returns(alarm);
            machineService.Setup(ms => ms.GetMachineById(It.IsAny <string>())).Returns(machine);
            watchService.Setup(ws => ws.GetAlarmSubscriptionsByAlarmCode(It.IsAny <int>())).Returns(alarmSubs);
            watchService.Setup(ws => ws.GetMachineSubscriptionsByMachine(It.IsAny <string>())).Throws <InvalidDataException>();
            notificationHub.Setup(nh => nh.SendDirectNotificationAsync(It.IsAny <Notification>(), It.IsAny <string>()));
            notificationConnectionSetting.Setup(ncs => ncs.Hub).Returns(notificationHub.Object);

            var res = (BadRequestObjectResult)await new SendAlert(watchService.Object, alarmService.Object, machineService.Object, alarmLogService.Object, notificationConnectionSetting.Object).Run(req, logger);

            //Then
            Assert.False(String.IsNullOrEmpty((string)res.Value));
        }
示例#24
0
        public UTorrentResponse ProcessRequest(HttpRequestBuilder requestBuilder, UTorrentSettings settings)
        {
            AuthenticateClient(requestBuilder, settings);

            var request = requestBuilder.Build();

            HttpResponse response;

            try
            {
                response = _httpClient.Execute(request);
            }
            catch (HttpException ex)
            {
                if (ex.Response.StatusCode == HttpStatusCode.BadRequest || ex.Response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    _logger.Debug("Authentication required, logging in.");

                    AuthenticateClient(requestBuilder, settings, true);

                    request = requestBuilder.Build();

                    response = _httpClient.Execute(request);
                }
                else
                {
                    throw new DownloadClientException("Unable to connect to uTorrent, please check your settings", ex);
                }
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.TrustFailure)
                {
                    throw new DownloadClientUnavailableException("Unable to connect to uTorrent, certificate validation failed.", ex);
                }

                throw new DownloadClientException("Unable to connect to uTorrent, please check your settings", ex);
            }

            return(Json.Deserialize <UTorrentResponse>(response.Content));
        }
示例#25
0
        protected override async Task DoLogin()
        {
            var requestBuilder = new HttpRequestBuilder(LoginUrl)
            {
                LogResponseContent = true,
                AllowAutoRedirect  = true,
                Method             = HttpMethod.Post,
            };

            var request = requestBuilder.Build();

            var data = new SpeedAppAuthenticationRequest
            {
                Email    = Settings.Email,
                Password = Settings.Password
            };

            request.SetContent(JsonConvert.SerializeObject(data));

            request.Headers.ContentType = MediaTypeNames.Application.Json;

            var response = await ExecuteAuth(request);

            var statusCode = (int)response.StatusCode;

            if (statusCode is < 200 or > 299)
            {
                throw new HttpException(response);
            }

            var parsedResponse = JsonConvert.DeserializeObject <SpeedAppAuthenticationResponse>(response.Content);

            Settings.ApiKey = parsedResponse.Token;

            if (Definition.Id > 0)
            {
                _indexerRepository.UpdateSettings((IndexerDefinition)Definition);
            }

            _logger.Debug("SpeedApp authentication succeeded.");
        }
示例#26
0
        public async Task SharedAccessKeyAuthorizedRoute_EmitsSecurityEventsWhenRequested_RunsAuthentication(bool emitsSecurityEvents)
        {
            // Arrange
            const string issuerKey = "issuer";
            var          spySink   = new InMemorySink();
            var          options   = new TestApiServerOptions()
                                     .ConfigureServices(services =>
            {
                var certificateValidator =
                    new CertificateAuthenticationValidator(
                        new CertificateAuthenticationConfigBuilder()
                        .WithIssuer(X509ValidationLocation.SecretProvider, issuerKey)
                        .Build());

                services.AddSecretStore(stores => stores.AddInMemory(issuerKey, "CN=issuer"))
                .AddSingleton(certificateValidator)
                .AddMvc(opt => opt.Filters.AddCertificateAuthentication(authOptions =>
                {
                    authOptions.EmitSecurityEvents = emitsSecurityEvents;
                }));
            })
                                     .ConfigureHost(host => host.UseSerilog((context, config) => config.WriteTo.Sink(spySink)));

            await using (var server = await TestApiServer.StartNewAsync(options, _logger))
            {
                var request = HttpRequestBuilder.Get(NoneAuthenticationController.GetRoute);

                // Act
                using (HttpResponseMessage response = await server.SendAsync(request))
                {
                    // Assert
                    Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
                    IEnumerable <LogEvent> logEvents = spySink.DequeueLogEvents();
                    Assert.True(emitsSecurityEvents == logEvents.Any(logEvent =>
                    {
                        string message = logEvent.RenderMessage();
                        return(message.Contains("EventType") && message.Contains("Security"));
                    }));
                }
            }
        }
示例#27
0
        private void AuthenticateClient(HttpRequestBuilder requestBuilder, TransmissionSettings settings, bool reauthenticate = false)
        {
            var authKey = string.Format("{0}:{1}", requestBuilder.BaseUrl, settings.Password);

            var sessionId = _authSessionIDCache.Find(authKey);

            if (sessionId == null || reauthenticate)
            {
                _authSessionIDCache.Remove(authKey);

                var authLoginRequest = BuildRequest(settings).Build();
                authLoginRequest.SuppressHttpError = true;

                var response = _httpClient.Execute(authLoginRequest);
                if (response.StatusCode == HttpStatusCode.MovedPermanently)
                {
                    var url = response.Headers.GetSingleValue("Location");

                    throw new DownloadClientException("Remote site redirected to " + url);
                }
                else if (response.StatusCode == HttpStatusCode.Conflict)
                {
                    sessionId = response.Headers.GetSingleValue("X-Transmission-Session-Id");

                    if (sessionId == null)
                    {
                        throw new DownloadClientException("Remote host did not return a Session Id.");
                    }
                }
                else
                {
                    throw new DownloadClientAuthenticationException("Failed to authenticate with Transmission.");
                }

                _logger.Debug("Transmission authentication succeeded.");

                _authSessionIDCache.Set(authKey, sessionId);
            }

            requestBuilder.SetHeader("X-Transmission-Session-Id", sessionId);
        }
示例#28
0
        private T ProcessRequest <T>(HadoukenSettings settings, string method, params object[] parameters)
        {
            var baseUrl = HttpRequestBuilder.BuildBaseUrl(settings.UseSsl, settings.Host, settings.Port, settings.UrlBase);

            baseUrl = HttpUri.CombinePath(baseUrl, "api");
            var requestBuilder = new JsonRpcRequestBuilder(baseUrl, method, parameters);

            requestBuilder.LogResponseContent = true;
            requestBuilder.NetworkCredential  = new BasicNetworkCredential(settings.Username, settings.Password);
            requestBuilder.Headers.Add("Accept-Encoding", "gzip,deflate");

            var          httpRequest = requestBuilder.Build();
            HttpResponse response;

            try
            {
                response = _httpClient.Execute(httpRequest);
            }
            catch (HttpException ex)
            {
                throw new DownloadClientException("Unable to connect to Hadouken, please check your settings", ex);
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.TrustFailure)
                {
                    throw new DownloadClientUnavailableException("Unable to connect to Hadouken, certificate validation failed.", ex);
                }

                throw new DownloadClientUnavailableException("Unable to connect to Hadouken, please check your settings", ex);
            }

            var result = Json.Deserialize <JsonRpcResponse <T> >(response.Content);

            if (result.Error != null)
            {
                throw new DownloadClientException("Error response received from Hadouken: {0}", result.Error.ToString());
            }

            return(result.Result);
        }
示例#29
0
        public ListResource GetListInfo(int foreignListId, int page, bool useCache = true)
        {
            _logger.Debug("Getting List with GoodreadsId of {0}", foreignListId);

            var httpRequest = new HttpRequestBuilder("https://www.goodreads.com/book/list/listopia.xml")
                              .AddQueryParam("key", new string("whFzJP3Ud0gZsAdyXxSr7T".Reverse().ToArray()))
                              .AddQueryParam("_nc", "1")
                              .AddQueryParam("format", "xml")
                              .AddQueryParam("id", foreignListId)
                              .AddQueryParam("items_per_page", 30)
                              .AddQueryParam("page", page)
                              .SetHeader("User-Agent", "Goodreads/3.33.1 (iPhone; iOS 14.3; Scale/3.00)")
                              .SetHeader("X_APPLE_DEVICE_MODEL", "iPhone")
                              .SetHeader("x-gr-os-version", "iOS 14.3")
                              .SetHeader("Accept-Language", "en-GB;q=1")
                              .SetHeader("X_APPLE_APP_VERSION", "761")
                              .SetHeader("x-gr-app-version", "761")
                              .SetHeader("x-gr-hw-model", "iPhone11,6")
                              .SetHeader("X_APPLE_SYSTEM_VERSION", "14.3")
                              .KeepAlive()
                              .Build();

            httpRequest.AllowAutoRedirect = true;
            httpRequest.SuppressHttpError = true;

            var httpResponse = _cachedHttpClient.Get(httpRequest, useCache, TimeSpan.FromDays(7));

            if (httpResponse.HasHttpError)
            {
                if (httpResponse.StatusCode == HttpStatusCode.BadRequest)
                {
                    throw new BadRequestException(foreignListId.ToString());
                }
                else
                {
                    throw new HttpException(httpRequest, httpResponse);
                }
            }

            return(httpResponse.Deserialize <ListResource>());
        }
示例#30
0
        private IEnumerable <IndexerRequest> GetMovieRequest(MovieSearchCriteria searchCriteria)
        {
            var requestBuilder = new HttpRequestBuilder(Settings.BaseUrl)
                                 .Resource("/pubapi_v2.php")
                                 .Accept(HttpAccept.Json);

            if (Settings.CaptchaToken.IsNotNullOrWhiteSpace())
            {
                requestBuilder.UseSimplifiedUserAgent = true;
                requestBuilder.SetCookie("cf_clearance", Settings.CaptchaToken);
            }

            requestBuilder.AddQueryParam("mode", "search");

            if (searchCriteria.Movie.ImdbId.IsNotNullOrWhiteSpace())
            {
                requestBuilder.AddQueryParam("search_imdb", searchCriteria.Movie.ImdbId);
            }
            else if (searchCriteria.Movie.TmdbId > 0)
            {
                requestBuilder.AddQueryParam("search_themoviedb", searchCriteria.Movie.TmdbId);
            }
            else
            {
                requestBuilder.AddQueryParam("search_string", $"{searchCriteria.Movie.Title} {searchCriteria.Movie.Year}");
            }


            if (!Settings.RankedOnly)
            {
                requestBuilder.AddQueryParam("ranked", "0");
            }

            requestBuilder.AddQueryParam("category", string.Join(";", Settings.Categories.Distinct()));
            requestBuilder.AddQueryParam("limit", "100");
            requestBuilder.AddQueryParam("token", _tokenProvider.GetToken(Settings));
            requestBuilder.AddQueryParam("format", "json_extended");
            requestBuilder.AddQueryParam("app_id", "Radarr");

            yield return(new IndexerRequest(requestBuilder.Build()));
        }
示例#31
0
        private DiskStationResponse <T> ProcessRequest <T>(HttpRequestBuilder requestBuilder,
                                                           string operation,
                                                           DiskStationApi api,
                                                           DownloadStationSettings settings) where T : new()
        {
            var request  = requestBuilder.Build();
            var response = _httpClient.Execute(request);

            _logger.Debug("Trying to {0}", operation);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var responseContent = Json.Deserialize <DiskStationResponse <T> >(response.Content);

                if (responseContent.Success)
                {
                    return(responseContent);
                }
                else
                {
                    var msg = $"Failed to {operation}. Reason: {responseContent.Error.GetMessage(api)}";
                    _logger.Error(msg);

                    if (responseContent.Error.SessionError)
                    {
                        _sessionCache.Remove(GenerateSessionCacheKey(settings));

                        if (responseContent.Error.Code == 105)
                        {
                            throw new DownloadClientAuthenticationException(msg);
                        }
                    }

                    throw new DownloadClientException(msg);
                }
            }
            else
            {
                throw new HttpException(request, response);
            }
        }
 public void Setup()
 {
     _request = new HttpRequestMessage();
     _builder = new HttpRequestBuilder(_request);
 }