using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using RestSharp; using RestSharp.Authenticators; using xCommons.Constants; using xCommons.Extensions; using xExceptions.Constants; using xHttpService.Configurations; using xHttpService.Constants; using xHttpService.Interfaces; using xIdentityModels.Models; using xModels.Base; namespace xHttpService.Providers { public partial class XHttpProvider : XBaseClass, IXHttpProvider { private readonly XHttpServiceConfiguration configuration; public XHttpProvider ( ILoggerFactory loggerFactory, XHttpServiceConfiguration configuration ) : base (loggerFactory) { this.configuration = configuration; } // #region Actions ... /// /// Get an Instance of Http Client /// /// public HttpClient GetHttpClient () { // HttpClient httpClient = null; httpClient = new HttpClient (); // if (configuration.DisableSSLCheck) { // var httpHandler = new HttpClientHandler (); httpHandler.ServerCertificateCustomValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true; // httpClient = new HttpClient (httpHandler); } // // Set Timeout ... httpClient.Timeout = TimeSpan .FromSeconds (configuration.DefaultClientTimeout); // return httpClient; } /// /// Get an Instance of RestClient /// /// /// /// /// public RestClient GetRestClient ( string baseUrl = null, string poweredByValue = null, XTokenResponse tokens = null ) { // var client = new RestClient (baseUrl); // // Add XPowered By to Default Headers ... if (!poweredByValue.IsNullOrEmpty ()) { client.AddDefaultHeader (XAuthorization.XPoweredBy, poweredByValue); } // // Set Authenticator ... if (!tokens.IsNull () && !tokens.AccessToken.IsNullOrEmpty ()) { client.Authenticator = new JwtAuthenticator (tokens.AccessToken); } // // Refresh Token ... if (!tokens.IsNull () && !tokens.RefreshToken.IsNullOrEmpty ()) { client.AddDefaultHeader (XAuthorization.RefreshToken, tokens.RefreshToken); } // // ExpiresAt ... if (!tokens.IsNull () && tokens.ExpiresAt > 0) { client.AddDefaultHeader (XAuthorization.ExpiresAt, tokens.ExpiresAt.AsHttpParamString ()); } // // Set Default Timeout ... client.Timeout = configuration.DefaultClientTimeout; // // SSL Validation Handler ... if (configuration.DisableSSLCheck) { client.RemoteCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true; } // return client; } /// /// Get an Instance of RestRequest /// /// /// /// /// /// public RestRequest GetRestRequet ( string endpoint, IDictionary @params = null, IDictionary headers = null, IDictionary queryStrings = null ) { // var url = endpoint.ToString (); // // Add Route Payloads ... if (!@params.IsNull () && @params.Count > 0) { // var enumerator = @params.GetEnumerator (); while (enumerator.MoveNext ()) { // var item = enumerator.Current; // url = url.Replace (item.Key, item.Value.ToUrlEncoded ()); } } // // Add Query Strings ... if (!queryStrings.IsNull () && queryStrings.Count > 0) { // url = $"{url}?"; var enumerator = queryStrings.GetEnumerator (); while (enumerator.MoveNext ()) { // var item = enumerator.Current; // url += $"{item.Key}={item.Value.ToUrlEncoded ()}&"; } // // remove lates & ... if (url.EndsWith ("&")) { url = url.Substring (0, url.Length - 1); } } // // Create request ... var request = new RestRequest (url, DataFormat.Json); // // Add Headers to request ... if (!headers.IsNull () && headers.Count > 0) { // var enumerator = headers.GetEnumerator (); while (enumerator.MoveNext ()) { // var item = enumerator.Current; request.AddHeader (item.Key, item.Value); } } // return request; } /// /// Handle Call Specific Request and retrieve Response /// /// /// /// /// /// public async Task RunRestRequest ( RestClient client, RestRequest request, XHttpMethod method ) { // var response = await Task.Run (() => { // IRestResponse resp = null; // // Call Endpoint Service using Specified Method ... switch (method) { // // Get ... case XHttpMethod.GET: resp = client.Get (request); break; // // Put ... case XHttpMethod.PUT: resp = client.Put (request); break; // // Post ... case XHttpMethod.POST: resp = client.Post (request); break; // // Delete ... case XHttpMethod.DELETE: resp = client.Delete (request); break; } // if (!resp.IsSuccessful) { // // UnAuthorized ... if (resp.StatusCode == System.Net.HttpStatusCode.Unauthorized) { XException.NotAuthorized.Throw (); } // // NotFound ... if (resp.StatusCode == System.Net.HttpStatusCode.NotFound) { XException.NotFound.Throw (); } // // Timeout ... if (!resp.ErrorMessage.IsNullOrEmpty () && resp.ErrorMessage.Contains ("timed out")) { XException.Timeout.Throw (); } // // ErrorMessage ... if (!resp.ErrorMessage.IsNullOrEmpty ()) { throw new Exception (resp.ErrorMessage); } // // Default Exception ... XException.BadRequest.Throw (); } // var result = resp.Content.FromJSON (); return result; }); // return response; } #endregion } }