private Dictionary <string, string> ConvertHeaders(HttpResponseHeaders responseHeaders, HttpContent httpContent)
        {
            if ((responseHeaders == null || !responseHeaders.Any()) &&
                (httpContent == null || (httpContent.Headers == null || !httpContent.Headers.Any())))
            {
                return(null);
            }

            var headers = new Dictionary <string, string>();

            if (responseHeaders != null && responseHeaders.Any())
            {
                foreach (var responseHeader in responseHeaders)
                {
                    headers.Add(responseHeader.Key, String.Join(", ", responseHeader.Value.Select(x => x)));
                }
            }

            if (httpContent != null && httpContent.Headers != null && httpContent.Headers.Any())
            {
                foreach (var contentHeader in httpContent.Headers)
                {
                    headers.Add(contentHeader.Key, String.Join(", ", contentHeader.Value.Select(x => x)));
                }
            }

            return(headers);
        }
Example #2
0
        /// <summary>
        ///     Updates the ApiClient's RateLimit
        ///     with the values from the last response from the Api.
        /// </summary>
        /// <param name="headers">The headers from the last request to the endpoint.</param>
        /// <exception cref="T:System.ArgumentNullException">
        ///     Thrown when a null reference is passed to a method that does not accept it as a
        ///     valid argument.
        /// </exception>
        internal virtual void UpdateRateLimit(HttpResponseHeaders headers)
        {
            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }
            string s1 = string.Empty;
            string s2 = string.Empty;

            if (this.ApiClient is IImgurClient && headers.Any <KeyValuePair <string, IEnumerable <string> > >((Func <KeyValuePair <string, IEnumerable <string> >, bool>)(x => x.Key.Equals("X-RateLimit-ClientLimit"))))
            {
                s1 = headers.GetValues("X-RateLimit-ClientLimit").FirstOrDefault <string>();
                s2 = headers.GetValues("X-RateLimit-ClientRemaining").FirstOrDefault <string>();
            }
            if (this.ApiClient is IMashapeClient && headers.Any <KeyValuePair <string, IEnumerable <string> > >((Func <KeyValuePair <string, IEnumerable <string> >, bool>)(x => x.Key.Equals("X-RateLimit-Requests-Limit"))))
            {
                s1 = headers.GetValues("X-RateLimit-Requests-Limit").FirstOrDefault <string>();
                s2 = headers.GetValues("X-RateLimit-Requests-Remaining").FirstOrDefault <string>();
            }
            int result1;

            if (!int.TryParse(s1, out result1))
            {
                result1 = this.ApiClient.RateLimit.ClientLimit;
            }
            int result2;

            if (!int.TryParse(s2, out result2))
            {
                result2 = this.ApiClient.RateLimit.ClientRemaining;
            }
            this.ApiClient.RateLimit.ClientLimit     = result1;
            this.ApiClient.RateLimit.ClientRemaining = result2;
        }
        public void SetProperties(HttpResponseHeaders headers)
        {
            var properties = this.GetType().GetTypeInfo().DeclaredProperties;

            foreach (var prop in properties.Where(prop => headers.Any(h => h.Key == prop.Name)))
            {
                var value = headers.First(h => NetNamingMapper.GetPropertyName(h.Key) == prop.Name).Value;
                if (value == null)
                {
                    continue;
                }

                if (value.Count() == 1)
                {
                    prop.SetValue(this, value.FirstOrDefault());
                }
                else
                {
                    try
                    {
                        prop.SetValue(this, value.FirstOrDefault());
                    }
                    catch (Exception)
                    {
                        // do nothing
                    }
                }
            }
        }
        protected override Browser Assert(Browser browser)
        {
            HttpResponseHeaders headers = browser.Response.Headers;
            var hasHeader = headers.Any(header => header.Key == HeaderKey && HeaderPredicate(header.Value));

            Xunit.Assert.True(hasHeader, userMessage: $"Response does not have correct {HeaderKey} header");
            return(browser);
        }
        /// <summary>
        ///     Updates the ApiClient's RateLimit
        ///     with the values from the last response from the Api.
        /// </summary>
        /// <param name="headers">The response headers from the last request to the endpoint.</param>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="FormatException"></exception>
        /// <exception cref="OverflowException"></exception>
        internal virtual void UpdateRateLimit(HttpResponseHeaders headers)
        {
            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            if (ApiClient is IImgurClient &&
                headers.Any(x => x.Key.Equals("X-RateLimit-ClientLimit")))
            {
                var clientLimit     = headers.GetValues("X-RateLimit-ClientLimit").FirstOrDefault();
                var clientRemaining = headers.GetValues("X-RateLimit-ClientRemaining").FirstOrDefault();
                var userLimit       = headers.GetValues("X-RateLimit-UserLimit").FirstOrDefault();
                var userRemaining   = headers.GetValues("X-RateLimit-UserRemaining").FirstOrDefault();
                var userReset       = headers.GetValues("X-RateLimit-UserReset").FirstOrDefault();

                ApiClient.RateLimit.ClientLimit     = Convert.ToInt32(clientLimit);
                ApiClient.RateLimit.ClientRemaining = Convert.ToInt32(clientRemaining);
                ApiClient.RateLimit.UserLimit       = Convert.ToInt32(userLimit);
                ApiClient.RateLimit.UserRemaining   = Convert.ToInt32(userRemaining);
                ApiClient.RateLimit.UserReset       =
                    new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(Convert.ToInt64(userReset));

                ApiClient.RateLimit.MashapeUploadsLimit     = null;
                ApiClient.RateLimit.MashapeUploadsRemaining = null;
            }

            if (ApiClient is IMashapeClient &&
                headers.Any(x => x.Key.Equals("X-RateLimit-Requests-Limit")))
            {
                var requestsLimit     = headers.GetValues("X-RateLimit-Requests-Limit").FirstOrDefault();
                var requestsRemaining = headers.GetValues("X-RateLimit-Requests-Remaining").FirstOrDefault();
                var uploadsLimit      = headers.GetValues("X-RateLimit-Uploads-Limit").FirstOrDefault();
                var uploadsRemaining  = headers.GetValues("X-RateLimit-Uploads-Remaining").FirstOrDefault();

                ApiClient.RateLimit.ClientLimit             = Convert.ToInt32(requestsLimit);
                ApiClient.RateLimit.ClientRemaining         = Convert.ToInt32(requestsRemaining);
                ApiClient.RateLimit.MashapeUploadsLimit     = Convert.ToInt32(uploadsLimit);
                ApiClient.RateLimit.MashapeUploadsRemaining = Convert.ToInt32(uploadsRemaining);

                ApiClient.RateLimit.UserLimit     = null;
                ApiClient.RateLimit.UserRemaining = null;
                ApiClient.RateLimit.UserReset     = null;
            }
        }
Example #6
0
        public void SetProperties(HttpResponseHeaders headers)
        {
            var properties = this.GetType().GetProperties().Where(p => p.GetValue(this) != null);

            foreach (var prop in properties.Where(prop => headers.Any(h => h.Key == prop.Name)))
            {
                prop.SetValue(this, headers.First(h => NetNamingMapper.GetPropertyName(h.Key) == prop.Name));
            }
        }
            private void StoreCookies(Uri uri, HttpResponseHeaders headers)
            {
                if (!_hostToCookie.ContainsKey(uri.Host)) _hostToCookie[uri.Host] = new List<string>();

                if (headers.Any(kvp => kvp.Key == "Set-Cookie"))
                {
                    _hostToCookie[uri.Host] = _hostToCookie[uri.Host]
                        .Concat(headers.GetValues("Set-Cookie").Select(x => x.Substring(0, x.IndexOf(';'))))
                        .Distinct().ToList();
                }
            }
Example #8
0
        /// <summary>
        ///     Updates the ApiClient's RateLimit
        ///     with the values from the last response from the Api.
        /// </summary>
        /// <param name="headers">The headers from the last request to the endpoint.</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown when a null reference is passed to a method that does not accept it as a
        ///     valid argument.
        /// </exception>
        internal virtual void UpdateRateLimit(HttpResponseHeaders headers)
        {
            if (headers == null)
            {
                throw new ArgumentNullException(nameof(headers));
            }

            var clientLimitHeader     = string.Empty;
            var clientRemainingHeader = string.Empty;

            if (ApiClient is IImgurClient &&
                headers.Any(x => x.Key.Equals("X-RateLimit-ClientLimit")))
            {
                clientLimitHeader     = headers.GetValues("X-RateLimit-ClientLimit").FirstOrDefault();
                clientRemainingHeader = headers.GetValues("X-RateLimit-ClientRemaining").FirstOrDefault();
            }

            if (ApiClient is IMashapeClient &&
                headers.Any(x => x.Key.Equals("X-RateLimit-Requests-Limit")))
            {
                clientLimitHeader     = headers.GetValues("X-RateLimit-Requests-Limit").FirstOrDefault();
                clientRemainingHeader = headers.GetValues("X-RateLimit-Requests-Remaining").FirstOrDefault();
            }

            //If the values can't be parsed use the previous value
            if (!int.TryParse(clientLimitHeader, out int clientLimit))
            {
                clientLimit = ApiClient.RateLimit.ClientLimit;
            }

            if (!int.TryParse(clientRemainingHeader, out int clientRemaining))
            {
                clientRemaining = ApiClient.RateLimit.ClientRemaining;
            }

            ApiClient.RateLimit.ClientLimit     = clientLimit;
            ApiClient.RateLimit.ClientRemaining = clientRemaining;
        }
Example #9
0
        /// <summary>
        /// Tries the get session token.
        /// </summary>
        /// <param name="headers">The headers from the server response.</param>
        /// <param name="value">The value of the session token.</param>
        /// <returns><see langword="true" /> if a token was found, <see langword="false" /> otherwise.</returns>
        private bool TryGetSessionToken(HttpResponseHeaders headers, out string value)
        {
            value = null;

            if (headers.Any(x => x.Key == "Set-Cookie"))
            {
                var sessionId = headers
                                .First(x => x.Key == "Set-Cookie").Value
                                .ToList()
                                .FirstOrDefault(x => x.Contains("JSESSION"));

                if (sessionId != null)
                {
                    value = sessionId.Split(';')[0];

                    return(true);
                }
            }

            return(false);
        }
        private void Validate()
        {
            if (_headers == null || !_headers.Any(h => h.Key.StartsWith("X-GPGAuth")))
            {
                throw new Exception("No GPGAuth headers set.");
            }

            if (!_headers.TryGetValue("X-GPGAuth-Version", out var version) || version != "1.3.0")
            {
                throw new Exception($"The version of GPGAuth provided by the server ({version}) is not supported.");
            }

            if (_headers.TryGetValue("X-GPGAuth-Error", out _))
            {
                if (_headers.TryGetValue("X-GPGAuth-Debug", out var debug))
                {
                    throw new Exception(debug);
                }

                throw new Exception("There was an error during authentication. Enable debug mode for more information.");
            }

            // Throws an exception if x-gpgauth-progress does not match our client state
            ThrowIfInvalidStage();

            // Verify the correct headers are set in each stage.
            switch (_state)
            {
            case GpgAuthState.Logout:
                ThrowIfHeaderNotEquals("X-GPGAuth-Authenticated", "false");
                break;

            case GpgAuthState.VerifyServer:
                ThrowIfHeaderNotEquals("X-GPGAuth-Authenticated", "false");
                ThrowIfHeaderSet("X-GPGAuth-User-Token");
                ThrowIfHeaderNotSet("X-GPGAuth-Verify-Response");
                ThrowIfHeaderSet("X-GPGAuth-Refer");
                break;

            case GpgAuthState.DecryptToken:     // "Stage 1"
                ThrowIfHeaderNotEquals("X-GPGAuth-Authenticated", "false");
                ThrowIfHeaderSet("X-GPGAuth-User-Token");
                ThrowIfHeaderSet("X-GPGAuth-Verify-Response");
                ThrowIfHeaderSet("X-GPGAuth-Refer");
                break;

            case GpgAuthState.VerifyToken:     // "Stage 2"
                ThrowIfHeaderNotEquals("X-GPGAuth-Authenticated", "false");
                ThrowIfHeaderNotSet("X-GPGAuth-User-Token");
                ThrowIfHeaderSet("X-GPGAuth-Verify-Response");
                ThrowIfHeaderSet("X-GPGAuth-Refer");
                break;

            case GpgAuthState.Complete:
                ThrowIfHeaderNotEquals("X-GPGAuth-Authenticated", "true");
                ThrowIfHeaderSet("X-GPGAuth-User-Token");
                ThrowIfHeaderSet("X-GPGAuth-Verify-Response");
                ThrowIfHeaderNotSet("X-GPGAuth-Refer");
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(_state), _state, null);
            }
        }
 /// <summary>
 /// Returns whether HttpResponseHeaders Contain X-RateLimit-Remaining
 /// </summary>
 /// <param name="responseHeaders"></param>
 /// <returns></returns>
 public static bool DoesContainGitHubRateLimitRemainingHeader(this HttpResponseHeaders responseHeaders) => responseHeaders.Any(x => x.Key is GitHubApiStatusService.RateLimitRemainingHeader);