using System; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Agger.Registro; using Gestor.Application.Helpers; using Gestor.Common.Validation; using Gestor.Model.Domain.Generic; using Gestor.Model.Helper; using Newtonsoft.Json.Linq; namespace Gestor.Application.Servicos; public class CepService { private const string GuidGestor = "bbbf4f03-01fc-4300-b430-33e007753578"; public async Task SearchDirect(string cep) { return await SearchDirectApiAgger(cep); } private static async Task Authorization() { HttpClient client = new HttpClient(); try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; string arg = DateTime.Now.ToString("yyyy-MM-dd"); string content = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}|{1}|{2}", ApplicationHelper.IdFornecedor, "bbbf4f03-01fc-4300-b430-33e007753578", arg))); Uri uri = Address.ApiCep.Append("/auth"); HttpResponseMessage val = await client.PostAsync(uri, (HttpContent)(object)content.ToHttpContent()); return (!val.IsSuccessStatusCode) ? string.Empty : ((object)val.Content.ToJObject()["token"])?.ToString(); } finally { ((IDisposable)client)?.Dispose(); } } public async Task SearchDirectApiAgger(string cep) { _ = 2; try { string cepCleared = ValidationHelper.OnlyNumber(cep); if (ValidationHelper.IsNullOrEmpty(cepCleared)) { return null; } HttpClient httpClient = new HttpClient(); try { ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; string text = await Authorization(); ((HttpHeaders)httpClient.DefaultRequestHeaders).TryAddWithoutValidation("Authorization", "Bearer " + text); Uri uri = Address.ApiCep.Append(cepCleared); string text2 = await (await httpClient.GetAsync(uri)).Content.ReadAsStringAsync(); JObject val = JObject.Parse(text2); if (val == null || text2.Equals("Endereço não encontrado")) { return null; } return new EnderecoBase { Endereco = ((object)val["logradouro"])?.ToString().ToUpper(), Bairro = ((object)val["bairro"])?.ToString().ToUpper(), Cidade = ((object)val["cidade"])?.ToString().ToUpper(), Estado = ((object)val["estado"])?.ToString().ToUpper(), Cep = ((object)val["cep"])?.ToString().ToUpper() }; } finally { ((IDisposable)httpClient)?.Dispose(); } } catch (Exception) { return null; } } }