/// <summary>
        /// Get all Plex servers.
        /// </summary>
        /// <param name="token">Cancellation token instance.</param>
        /// <returns>Found and active servers.</returns>
        public async Task <IEnumerable <Device> > GetAllServers(CancellationToken token)
        {
            string requestUrl = Endpoint.GetDevices.Description();
            var    request    = new HttpRequestMessage(HttpMethod.Get, requestUrl);
            IDictionary <string, string> authHeaders = _basicAuthConstructor.ConstructRequestHeaders(new BasicAuthRequest
            {
                Username = _configuration.PlexAuthenticationRequestUser.Username,
                Password = _configuration.PlexAuthenticationRequestUser.Password
            });
            HttpRequest httpRequest = request
                                      .AddRequestHeaders(_plexBasicHeaders)
                                      .AddRequestHeaders(authHeaders)
                                      .ToHttpRequest();
            HttpResponse <string> response = await _httpService
                                             .RequestAsync <string>(httpRequest, token);

            var xmlStringResponse = await response?
                                    .ResponseMessage?
                                    .Content
                                    .ReadAsStringAsync();
            var castedResponse = xmlStringResponse
                                 .FromXmlString <DevicesMediaContainer>();

            if (castedResponse == null)
            {
                return(new List <Device>());
            }

            IEnumerable <Device> filteredResponse = castedResponse
                                                    .Devices
                                                    .Where(d => d.Connections.Any(c => !c.Uri.Equals(castedResponse.PublicAddress)) && d.Provides.Equals("server"));

            return(filteredResponse);
        }
        public void AddRequestHeaders_WithAlreadyExistingHeader_ShouldUpdateHeaderValue()
        {
            // Setup
            var request  = new HttpRequestMessage();
            var existing = new KeyValuePair <string, string>("test_key", "test_value_updated");
            var expected = new KeyValuePair <string, string>("test_key", "test_value_updated");
            IDictionary <string, string> headersExisting = new Dictionary <string, string>();
            IDictionary <string, string> headers         = new Dictionary <string, string>();

            headersExisting.Add(existing);
            headers.Add(expected);

            // Perform
            request.AddRequestHeaders(headersExisting);
            request.AddRequestHeaders(headers);

            // Assert
            Assert.Equal(expected.Value, request.Headers.First(h => h.Key == expected.Key).Value.First());
        }
        public void AddRequestHeaders_WithInvalidHeaders_ShouldThrowArgumaentNullException()
        {
            // Setup
            var request = new HttpRequestMessage();
            IDictionary <string, string> headers = null;

            // Perform

            // Assert
            Assert.Throws <ArgumentNullException>(() =>
            {
                HttpRequestMessage ammendedRequest = request.AddRequestHeaders(headers);
            });
        }
        public void AddRequestHeaders_WithValidheaders_ShouldAddHeadersToRequest()
        {
            // Setup
            var request  = new HttpRequestMessage();
            var expected = new KeyValuePair <string, string>("test_key", "test_value");
            IDictionary <string, string> headers = new Dictionary <string, string>();

            headers.Add(expected);

            // Perform
            request.AddRequestHeaders(headers);

            // Assert
            Assert.Equal(expected.Value, request.Headers.First(h => h.Key == expected.Key).Value.First());
        }
Beispiel #5
0
        public async Task <HttpResponseMessage> SendAsync(HttpMethod method)
        {
            if (handler == null)
            {
                handler = new HttpClientHandler()
                {
                    AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
                };
            }
            if (client == null)
            {
                client = new HttpClient(handler);
            }
            AddAllCookies(handler);

            await waitForRequestToBeConfigured.Task.WithTimeout(timeoutInMs : 30000);

            httpMethod  = "" + method;
            sentRequest = new HttpRequestMessage(method, uri);
            if (httpContent != null)
            {
                sentRequest.Content = httpContent;
            }
            sentRequest.AddRequestHeaders(requestHeaders);

            if (OnBeforeSend != null)
            {
                await OnBeforeSend(client, sentRequest);
            }
            var result = await client.SendAsync(sentRequest, sendAsyncCompletedAfter, CancellationTokenSource.Token);

            var cookieJar = IoC.inject.Get <cookies.CookieJar>(this, false);

            if (cookieJar != null)
            {
                cookieJar.SetCookies(handler.CookieContainer.GetCookiesForCookieJar(uri).ToArray());
            }

            try {
                var serverUtcDate = result.Headers.Date;
                if (serverUtcDate != null)
                {
                    EventBus.instance.Publish(DateTimeV2.SERVER_UTC_DATE, uri, serverUtcDate.Value.UtcDateTime);
                }
            }
            catch (Exception e) { Log.e(e); }
            return(result);
        }
        /// <summary>
        /// Authenticate a user using username and password.
        /// </summary>
        /// <param name="token">Cancellation token instance.</param>
        /// <returns>Response for authentication whether success or failure.</returns>
        public async Task <UserAuthenticationResponse> AuthenticateAsync(CancellationToken token)
        {
            string requestUrl = Endpoint.SignIn.Description();
            var    request    = new HttpRequestMessage(HttpMethod.Post, requestUrl);
            IDictionary <string, string> authHeaders = _basicAuthConstructor.ConstructRequestHeaders(new BasicAuthRequest
            {
                Username = _configuration.PlexAuthenticationRequestUser.Username,
                Password = _configuration.PlexAuthenticationRequestUser.Password
            });
            HttpRequest httpRequest = request
                                      .AddRequestHeaders(_plexBasicHeaders)
                                      .AddRequestHeaders(authHeaders)
                                      .ToHttpRequest();
            HttpResponse <UserAuthenticationResponse> response = await _httpService
                                                                 .RequestAsync <UserAuthenticationResponse>(httpRequest, token);

            return(response.Response);
        }