Exemplo n.º 1
0
        private string GetQuery(AblyRequest request)
        {
            string query = string.Join("&", request.QueryParameters.Select(x => String.Format("{0}={1}", x.Key, x.Value)));

            if (query.IsNotEmpty())
            {
                return("?" + query);
            }
            return(string.Empty);
        }
Exemplo n.º 2
0
 private void PopulateDefaultHeaders(AblyRequest request, HttpWebRequest webRequest)
 {
     if (request.Method == HttpMethod.Post)
     {
         PopulateWebRequestHeaders(webRequest, GetDefaultPostHeaders(request.Protocol));
     }
     if (request.Method == HttpMethod.Get)
     {
         PopulateWebRequestHeaders(webRequest, GetDefaultHeaders(request.Protocol));
     }
 }
Exemplo n.º 3
0
        AblyResponse IAblyRest.ExecuteRequest(AblyRequest request)
        {
            Logger.Info("Sending {0} request to {1}", request.Method, request.Url);

            if (request.SkipAuthentication == false)
            {
                AddAuthHeader(request);
            }

            _messageHandler.SetRequestBody(request);

            return(ExecuteHttpRequest(request));
        }
Exemplo n.º 4
0
        T IAblyRest.ExecuteRequest <T>(AblyRequest request)
        {
            var response = RestMethods.ExecuteRequest(request);

            Logger.Debug("Response received. Status: " + response.StatusCode);
            Logger.Debug("Content type: " + response.ContentType);
            Logger.Debug("Encoding: " + response.Encoding);
            if (response.Body != null)
            {
                Logger.Debug("Raw response (base64):" + response.Body.ToBase64());
            }

            return(_messageHandler.ParseResponse <T>(request, response));
        }
Exemplo n.º 5
0
        private Uri GetRequestUrl(AblyRequest request)
        {
            string protocol = _isSecure ? "https://" : "http://";

            if (request.Url.StartsWith("http"))
            {
                return(new Uri(request.Url));
            }
            return(new Uri(String.Format("{0}{1}{2}{3}{4}",
                                         protocol,
                                         GetHost(),
                                         _port.HasValue ? ":" + _port.Value : "",
                                         request.Url,
                                         GetQuery(request))));
        }
Exemplo n.º 6
0
        public AblyResponse Execute(AblyRequest request)
        {
            var hosts = Config.FallbackHosts;

            int currentTry = 0;
            var startTime  = Config.Now();

            while (currentTry <= hosts.Length)
            {
                var requestTime = Config.Now();
                if ((requestTime - startTime).TotalSeconds > Config.CommulativeFailedRequestTimeOutInSeconds)
                {
                    Logger.Error("Cumulative retry timeout of {0}s was exceeded", Config.CommulativeFailedRequestTimeOutInSeconds);
                    throw new AblyException(
                              new ErrorInfo(string.Format("Commulative retry timeout of {0}s was exceeded.",
                                                          Config.CommulativeFailedRequestTimeOutInSeconds), 500, null));
                }

                try
                {
                    return(ExecuteInternal(request));
                }
                catch (WebException exception)
                {
                    var errorResponse = exception.Response as HttpWebResponse;

                    if (IsRetryable(exception) && _isDefaultHost)
                    {
                        Logger.Error("Error making a connection to Ably servers. Retrying", exception);
                        _host = hosts[currentTry - 1];
                        currentTry++;
                        continue;
                    }

                    if (errorResponse != null)
                    {
                        throw AblyException.FromResponse(GetAblyResponse(errorResponse));
                    }

                    throw new AblyException(new ErrorInfo("Unexpected error. Check the inner exception for details", 500, null), exception);
                }
            }
            throw new AblyException(new ErrorInfo("Unexpected error while making a request.", 500, null));
        }
Exemplo n.º 7
0
        private AblyResponse ExecuteInternal(AblyRequest request)
        {
            var webRequest = HttpWebRequest.Create(GetRequestUrl(request)) as HttpWebRequest;

            webRequest.Timeout = Config.ConnectTimeout;
            HttpWebResponse response = null;

            webRequest.Headers["X-Ably-Version"] = Config.AblyVersion;
            PopulateDefaultHeaders(request, webRequest);
            PopulateWebRequestHeaders(webRequest, request.Headers);

            webRequest.UserAgent = "Ably.net library";
            webRequest.Method    = request.Method.Method;

            try
            {
                if (webRequest.Method == "POST")
                {
                    var requestBody = request.RequestBody;

                    webRequest
                    .ContentLength = requestBody.Length;
                    if (requestBody.Any())
                    {
                        using (Stream stream = webRequest.GetRequestStream())
                        {
                            stream.Write(requestBody, 0, requestBody.Length);
                        }
                    }
                }

                response = webRequest.GetResponse() as HttpWebResponse;
                return(GetAblyResponse(response));
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
        }
Exemplo n.º 8
0
        /// <summary>
        /// Makes a token request. This will make a token request now, even if the library already
        /// has a valid token. It would typically be used to issue tokens for use by other clients.
        /// </summary>
        /// <param name="requestData">The <see cref="TokenRequest"/> data used for the token</param>
        /// <param name="options">Extra <see cref="AuthOptions"/> used for creating a token </param>
        /// <returns>A valid ably token</returns>
        /// <exception cref="AblyException"></exception>
        public TokenDetails RequestToken(TokenRequest requestData, AuthOptions options)
        {
            var mergedOptions = options != null?options.Merge(_options) : _options;

            string keyId = "", keyValue = "";

            if (!string.IsNullOrEmpty(mergedOptions.Key))
            {
                var key = mergedOptions.ParseKey();
                keyId    = key.KeyName;
                keyValue = key.KeySecret;
            }

            var data = requestData ?? new TokenRequest
            {
                KeyName  = keyId,
                ClientId = _options.ClientId
            };

            if (requestData == null && options == null && _lastTokenRequest != null)
            {
                data = _lastTokenRequest;
            }

            data.KeyName = data.KeyName ?? keyId;

            _lastTokenRequest = data;

            var request = _rest.CreatePostRequest(String.Format("/keys/{0}/requestToken", data.KeyName));

            request.SkipAuthentication = true;
            TokenRequestPostData postData = null;

            if (mergedOptions.AuthCallback != null)
            {
                var token = mergedOptions.AuthCallback(data);
                if (token != null)
                {
                    return(token);
                }
                throw new AblyException("AuthCallback returned an invalid token");
            }

            if (mergedOptions.AuthUrl.IsNotEmpty())
            {
                var url         = mergedOptions.AuthUrl;
                var protocol    = _options.UseBinaryProtocol == false ? Protocol.Json : Protocol.MsgPack;
                var authRequest = new AblyRequest(url, mergedOptions.AuthMethod, protocol);
                if (mergedOptions.AuthMethod == HttpMethod.Get)
                {
                    authRequest.AddQueryParameters(mergedOptions.AuthParams);
                }
                else
                {
                    authRequest.PostParameters = mergedOptions.AuthParams;
                }
                authRequest.Headers.Merge(mergedOptions.AuthHeaders);
                authRequest.SkipAuthentication = true;
                var response = _rest.ExecuteRequest(authRequest);
                if (response.Type != ResponseType.Json)
                {
                    throw new AblyException(
                              new ErrorInfo(
                                  string.Format("Content Type {0} is not supported by this client library",
                                                response.ContentType), 500));
                }

                var signedData = response.TextResponse;
                var jData      = JObject.Parse(signedData);
                if (TokenDetails.IsToken(jData))
                {
                    return(jData.ToObject <TokenDetails>());
                }

                postData = JsonConvert.DeserializeObject <TokenRequestPostData>(signedData);
            }
            else
            {
                postData = data.GetPostData(keyValue);
            }

            if (mergedOptions.QueryTime)
            {
                postData.timestamp = _rest.Time().ToUnixTimeInMilliseconds().ToString();
            }

            request.PostData = postData;

            var result = _rest.ExecuteRequest <TokenDetails>(request);

            if (result == null)
            {
                throw new AblyException(new ErrorInfo("Invalid token response returned", 500));
            }

            return(result);
        }