summaryrefslogtreecommitdiff
path: root/Decompiler/Gestor.Application.Helpers/Connection.cs
blob: 20ca14c95a8a4c62caa10a2ae987447bad704b12 (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Agger.Registro;
using Gestor.Common.Security;
using Gestor.Common.Validation;
using Gestor.Model.API;
using Newtonsoft.Json;

namespace Gestor.Application.Helpers;

public static class Connection
{
	private const bool defaultUsaAzureStorage = false;

	private const string defaultAzureStorage = "ad1";

	public static string Server;

	public static string Catalog;

	public static string User;

	public static string Password;

	public static string Pool;

	public static string Type;

	public static ConnectionAddress ConnectionAddress { get; set; }

	public static string LinkAggilizador { get; set; }

	public static string UrlCentralSegurado { get; set; }

	public static string BasicKey()
	{
		return $"{ApplicationHelper.NumeroSerial}:{Funcoes.GetNetworkTime().ToUniversalTime().Ticks}".Base64Encode();
	}

	public static string Base64Encode(this string plainText)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		return new Token().Encrypt(plainText);
	}

	public static string EncodeBase64(this string plainText)
	{
		try
		{
			return Convert.ToBase64String(Encoding.UTF8.GetBytes(plainText));
		}
		catch
		{
		}
		return string.Empty;
	}

	public static async Task<string> GetPool()
	{
		ConnectionAddress val = await Get<ConnectionAddress>("Server/Pool");
		if (val == null)
		{
			return "";
		}
		Pool = new Token().Decrypt(val.Pool);
		return Pool;
	}

	public static string GetConnection(bool tryconnect = true)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Expected O, but got Unknown
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown
		//IL_03a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_03aa: Unknown result type (might be due to invalid IL or missing references)
		//IL_03b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c0: Unknown result type (might be due to invalid IL or missing references)
		//IL_03cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_03d6: Unknown result type (might be due to invalid IL or missing references)
		//IL_03e1: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ec: Unknown result type (might be due to invalid IL or missing references)
		//IL_03f7: Unknown result type (might be due to invalid IL or missing references)
		//IL_03fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_0405: Unknown result type (might be due to invalid IL or missing references)
		//IL_042d: Expected O, but got Unknown
		try
		{
			Token val = new Token();
			RegistryHelper val2 = new RegistryHelper(ApplicationHelper.Subkey);
			bool flag = false;
			string azureStorage = "ad1";
			if (ApplicationHelper.Conectado)
			{
				List<ConnectionAddress> result = Get<List<ConnectionAddress>>($"Server/{ApplicationHelper.IdFornecedor}").Result;
				for (int i = 0; i < result.Count; i++)
				{
					string text = val.AggerEncrypt(val.Decrypt(result[i].Server));
					string text2 = val.AggerEncrypt(val.Decrypt(result[i].Catalog));
					string text3 = val.AggerEncrypt(val.Decrypt(result[i].User));
					string text4 = val.AggerEncrypt(val.Decrypt(result[i].Password));
					string text5 = val.AggerEncrypt(val.Decrypt(result[i].Pool));
					string text6 = result[i].Type.ToString();
					LinkAggilizador = (string.IsNullOrEmpty(result[i].Aggilizador) ? null : result[i].Aggilizador);
					UrlCentralSegurado = (string.IsNullOrEmpty(result[i].UrlCentralSegurado) ? null : result[0].UrlCentralSegurado);
					flag = result[i].UsaAzureStorage;
					azureStorage = (string.IsNullOrEmpty(result[i].AzureStorage) ? "ad1" : val.Decrypt(result[i].AzureStorage));
					val2.Write<string>($"SERVER{i + 1}", text, true);
					val2.Write<string>($"DB{i + 1}", text2, true);
					val2.Write<string>($"USER{i + 1}", text3, true);
					val2.Write<string>($"PASSWORD{i + 1}", text4, true);
					val2.Write<string>($"POOL{i + 1}", text5, true);
					val2.Write<string>($"TYPE{i + 1}", text6, true);
				}
			}
			string result2 = "";
			for (int j = 0; j < 3 && val2.Read($"SERVER{j + 1}", true) != null; j++)
			{
				if (val2.Read($"TYPE{j + 1}", true) == "4")
				{
					continue;
				}
				Server = val.AggerDecrypt(val2.Read($"SERVER{j + 1}", true));
				Catalog = val.AggerDecrypt(val2.Read($"DB{j + 1}", true));
				User = val.AggerDecrypt(val2.Read($"USER{j + 1}", true));
				Password = val.AggerDecrypt(val2.Read($"PASSWORD{j + 1}", true));
				Pool = val.AggerDecrypt(val2.Read($"POOL{j + 1}", true));
				Type = val2.Read($"TYPE{j + 1}", true);
				if (!flag)
				{
					flag = Task.Run(async () => await SaveInAzureStorage()).Result;
				}
				ConnectionAddress = new ConnectionAddress
				{
					Server = Server,
					Catalog = Catalog,
					User = User,
					Password = Password,
					Pool = Pool,
					Aggilizador = LinkAggilizador,
					UrlCentralSegurado = UrlCentralSegurado,
					UsaAzureStorage = flag,
					AzureStorage = azureStorage,
					Type = int.Parse(ValidationHelper.IsNotNullOrEmpty(Type) ? "0" : Type)
				};
				string connectionString = GetConnectionString();
				if (!tryconnect || TryConnect(connectionString))
				{
					result2 = connectionString;
					break;
				}
			}
			return result2;
		}
		catch (Exception)
		{
			return null;
		}
	}

	public static string GetConnectionString()
	{
		return "Server=" + Server + ";initial catalog=" + Catalog + ";user=" + User + ";password=" + Password + ";";
	}

	internal static bool TryConnect(string connectionString, int retryCount = 1)
	{
		//IL_000c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0012: Expected O, but got Unknown
		List<Exception> list = new List<Exception>();
		for (int i = 0; i < retryCount; i++)
		{
			try
			{
				SqlConnection val = new SqlConnection(connectionString);
				try
				{
					((DbConnection)(object)val).Open();
				}
				finally
				{
					((IDisposable)val)?.Dispose();
				}
				return true;
			}
			catch (Exception item)
			{
				list.Add(item);
			}
		}
		return list.Count == 0;
	}

	public static string GetAdConnection(string serial)
	{
		ApplicationHelper.NumeroSerial = serial;
		if (string.IsNullOrWhiteSpace(Server))
		{
			GetAdConnection(serial);
		}
		return "Server=" + Server + ";initial catalog=" + Catalog + "AD;user=" + User + ";password=" + Password + ";";
	}

	public static async Task<T> Get<T>(string command, bool autorizar = true, bool verificarConexao = false) where T : class
	{
		Uri uri = new Uri(Address.GestorApi(), command);
		HttpClient val = new HttpClient();
		if (autorizar)
		{
			val.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
		}
		ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
		HttpResponseMessage val2;
		try
		{
			val2 = await val.GetAsync(uri).ConfigureAwait(continueOnCapturedContext: false);
		}
		catch (Exception)
		{
			ApplicationHelper.Conectado = false;
			return null;
		}
		if (verificarConexao)
		{
			ApplicationHelper.Conectado = true;
		}
		if (val2.StatusCode == HttpStatusCode.NoContent)
		{
			return null;
		}
		if (val2.StatusCode != HttpStatusCode.OK)
		{
			throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null);
		}
		return JsonConvert.DeserializeObject<T>(val2.Content.ReadAsStringAsync().Result);
	}

	public static async Task<HttpStatusCode> Get(string command, bool autorizar = true)
	{
		Uri uri = new Uri(Address.GestorApi(), command);
		HttpClient val = new HttpClient();
		if (autorizar)
		{
			val.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
		}
		ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
		HttpResponseMessage val2;
		try
		{
			val2 = await val.GetAsync(uri).ConfigureAwait(continueOnCapturedContext: false);
		}
		catch (Exception)
		{
			return HttpStatusCode.InternalServerError;
		}
		return val2.StatusCode;
	}

	public static async Task<T> Post<T>(string command, T keyValues) where T : class
	{
		Uri uri = new Uri(Address.GestorApi(), command);
		StringContent val = new StringContent(JsonConvert.SerializeObject((object)keyValues, (Formatting)1, new JsonSerializerSettings
		{
			ReferenceLoopHandling = (ReferenceLoopHandling)1,
			MissingMemberHandling = (MissingMemberHandling)0
		}), Encoding.UTF8, "application/json");
		HttpClient val2 = new HttpClient();
		val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
		ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
		HttpResponseMessage val3 = await val2.PostAsync(uri, (HttpContent)(object)val);
		if (val3.StatusCode == HttpStatusCode.NoContent)
		{
			return null;
		}
		if (val3.StatusCode != HttpStatusCode.OK)
		{
			throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null);
		}
		return JsonConvert.DeserializeObject<T>(val3.Content.ReadAsStringAsync().Result);
	}

	public static async Task<T> Post<T>(string command, object keyValues) where T : class
	{
		Uri uri = new Uri(Address.GestorApi(), command);
		StringContent val = new StringContent(JsonConvert.SerializeObject(keyValues, (Formatting)1, new JsonSerializerSettings
		{
			ReferenceLoopHandling = (ReferenceLoopHandling)1,
			MissingMemberHandling = (MissingMemberHandling)0
		}), Encoding.UTF8, "application/json");
		HttpClient val2 = new HttpClient();
		val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
		ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
		HttpResponseMessage val3 = await val2.PostAsync(uri, (HttpContent)(object)val);
		if (val3.StatusCode == HttpStatusCode.NoContent)
		{
			return null;
		}
		if (val3.StatusCode != HttpStatusCode.OK)
		{
			throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null);
		}
		return JsonConvert.DeserializeObject<T>(val3.Content.ReadAsStringAsync().Result);
	}

	public static async Task<T> Put<T>(string command, T keyValues) where T : class
	{
		Uri uri = new Uri(Address.GestorApi(), command);
		StringContent val = new StringContent(JsonConvert.SerializeObject((object)keyValues, (Formatting)1, new JsonSerializerSettings
		{
			ReferenceLoopHandling = (ReferenceLoopHandling)1
		}), Encoding.UTF8, "application/json");
		HttpClient val2 = new HttpClient();
		ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
		val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
		HttpResponseMessage obj = await val2.PutAsync(uri, (HttpContent)(object)val);
		if (obj.StatusCode != HttpStatusCode.OK)
		{
			throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null);
		}
		return JsonConvert.DeserializeObject<T>(obj.Content.ReadAsStringAsync().Result);
	}

	public static async Task<T> Put<T>(string command, object keyValues) where T : class
	{
		Uri uri = new Uri(Address.GestorApi(), command);
		StringContent val = new StringContent(JsonConvert.SerializeObject(keyValues, (Formatting)1, new JsonSerializerSettings
		{
			ReferenceLoopHandling = (ReferenceLoopHandling)1
		}), Encoding.UTF8, "application/json");
		HttpClient val2 = new HttpClient();
		ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
		val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
		HttpResponseMessage val3 = await val2.PutAsync(uri, (HttpContent)(object)val);
		if (val3.StatusCode == HttpStatusCode.NoContent)
		{
			return null;
		}
		if (val3.StatusCode != HttpStatusCode.OK)
		{
			throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null);
		}
		return JsonConvert.DeserializeObject<T>(val3.Content.ReadAsStringAsync().Result);
	}

	public static async void PutError<T>(T keyValues) where T : class
	{
		Uri uri = new Uri(Address.GestorApi(), "Error/Objeto");
		StringContent val = new StringContent(JsonConvert.SerializeObject((object)keyValues, (Formatting)1, new JsonSerializerSettings
		{
			ReferenceLoopHandling = (ReferenceLoopHandling)1
		}), Encoding.UTF8, "application/json");
		HttpClient val2 = new HttpClient();
		ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
		val2.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
		if ((await val2.PutAsync(uri, (HttpContent)(object)val)).StatusCode != HttpStatusCode.NoContent)
		{
			throw new Exception("Api connection Error " + Environment.NewLine + " Error", null);
		}
	}

	public static async Task<bool> Delete(string command)
	{
		Uri uri = new Uri(Address.GestorApi(), command);
		HttpClient val = new HttpClient();
		ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
		val.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", BasicKey());
		if ((await val.DeleteAsync(uri)).StatusCode != HttpStatusCode.OK)
		{
			throw new Exception("Api connection Error " + Environment.NewLine + " " + command, null);
		}
		return true;
	}

	internal static async Task<byte[]> DownloadFile(string azureStorage, int ano, Guid id, string extensao, string path = "ad", bool forceDownload = false)
	{
		azureStorage = (string.IsNullOrEmpty(azureStorage) ? "ad1" : azureStorage);
		Uri uri = Address.ApiAD.Append(AdApiV2(azureStorage)).Append(path).Append(ano.ToString())
			.Append(id.ToString())
			.Append(extensao.Replace(".", string.Empty));
		try
		{
			string path2 = $"{Path.GetTempPath()}{id}{extensao}";
			if (!forceDownload && File.Exists(path2))
			{
				return File.ReadAllBytes(path2);
			}
			HttpClient client = new HttpClient();
			try
			{
				ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
				((HttpHeaders)client.DefaultRequestHeaders).Clear();
				((HttpHeaders)client.DefaultRequestHeaders).Add("Authorization", "Token " + BasicKey());
				HttpResponseMessage val = await client.GetAsync(uri);
				if (val.IsSuccessStatusCode && val.StatusCode != HttpStatusCode.NotFound)
				{
					return await val.Content.ReadAsByteArrayAsync();
				}
			}
			finally
			{
				((IDisposable)client)?.Dispose();
			}
		}
		catch
		{
		}
		return null;
	}

	internal static async Task<bool> SaveInAzureStorage()
	{
		string text = $"{Address.GestorApi()}Data";
		try
		{
			HttpClient client = new HttpClient();
			try
			{
				((HttpHeaders)client.DefaultRequestHeaders).Clear();
				((HttpHeaders)client.DefaultRequestHeaders).Add("Authorization", "Token " + BasicKey());
				HttpResponseMessage val = await client.GetAsync(text);
				if (val.IsSuccessStatusCode)
				{
					return await val.Content.ReadAsStringAsync() == "true";
				}
			}
			finally
			{
				((IDisposable)client)?.Dispose();
			}
		}
		catch
		{
		}
		return false;
	}

	internal static async Task<bool> UploadFile(UploadFile upload, string path = "ad")
	{
		Uri uri = Address.ApiAD.Append(AdApiV2(ConnectionAddress.AzureStorage)).Append(path);
		try
		{
			HttpClient client = new HttpClient();
			try
			{
				ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
				((HttpHeaders)client.DefaultRequestHeaders).Clear();
				((HttpHeaders)client.DefaultRequestHeaders).Add("Authorization", "Token " + BasicKey());
				HttpResponseMessage val = await client.PutAsync(uri, (HttpContent)new StringContent(JsonConvert.SerializeObject((object)upload), Encoding.UTF8, "application/json"));
				return val.IsSuccessStatusCode && val.StatusCode != HttpStatusCode.NoContent;
			}
			finally
			{
				((IDisposable)client)?.Dispose();
			}
		}
		catch
		{
		}
		return false;
	}

	internal static async Task<bool> DeleteFile(string azureStorage, int ano, Guid id, string extensao, string path = "ad")
	{
		azureStorage = (string.IsNullOrEmpty(azureStorage) ? "ad1" : azureStorage);
		Uri uri = Address.ApiAD.Append(AdApiV2(azureStorage)).Append(path).Append(ano.ToString())
			.Append(id.ToString())
			.Append(extensao.Replace(".", string.Empty));
		try
		{
			HttpClient client = new HttpClient();
			try
			{
				ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
				((HttpHeaders)client.DefaultRequestHeaders).Clear();
				((HttpHeaders)client.DefaultRequestHeaders).Add("Authorization", "Token " + BasicKey());
				HttpResponseMessage val = await client.DeleteAsync(uri);
				return val.IsSuccessStatusCode && val.StatusCode != HttpStatusCode.NoContent;
			}
			finally
			{
				((IDisposable)client)?.Dispose();
			}
		}
		catch
		{
		}
		return false;
	}

	internal static async Task<double> EspacoUsadoAzureInBytes(string path = "")
	{
		Uri uri = Address.ApiAD.Append(AdApiV2(ConnectionAddress.AzureStorage)).Append("tamanho");
		if (!string.IsNullOrEmpty(path))
		{
			uri.Append(path);
		}
		try
		{
			HttpClient client = new HttpClient();
			try
			{
				ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
				((HttpHeaders)client.DefaultRequestHeaders).Clear();
				((HttpHeaders)client.DefaultRequestHeaders).Add("Authorization", "Token " + BasicKey());
				HttpResponseMessage val = await client.GetAsync(uri);
				if (val.IsSuccessStatusCode && val.StatusCode != HttpStatusCode.NoContent)
				{
					return double.Parse(await val.Content.ReadAsStringAsync());
				}
			}
			finally
			{
				((IDisposable)client)?.Dispose();
			}
		}
		catch
		{
		}
		return 0.0;
	}

	private static string AdApiV2(string storage)
	{
		if (Address.ApiAD.ToString().Contains("/api/v1"))
		{
			return string.Empty;
		}
		return storage;
	}

	internal static Uri Append(this Uri uri, params string[] paths)
	{
		return new Uri(paths.Aggregate(uri.AbsoluteUri, (string current, string path) => current.TrimEnd(new char[1] { '/' }) + "/" + path.TrimStart(new char[1] { '/' })));
	}
}