summaryrefslogtreecommitdiff
path: root/Decompiler/Gestor.Application.Servicos/CepService.cs
blob: 0ee1d2cb21bd079d8ea76ec615476abea173c73d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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<EnderecoBase> SearchDirect(string cep)
	{
		return await SearchDirectApiAgger(cep);
	}

	private static async Task<string> 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<EnderecoBase> 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;
		}
	}
}