summaryrefslogtreecommitdiff
path: root/Decompiler/Gestor.Application.ViewModels.Ferramentas/DownloadViewModel.cs
blob: 1246bfe66398ccf0f701c735386df8a8d64b257d (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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using Gestor.Application.Helpers;
using Gestor.Application.ViewModels.Generic;
using Gestor.Application.Views.Ferramentas;
using Gestor.Common.Validation;
using Gestor.Model.API;
using Gestor.Model.Domain.Generic;
using IWshRuntimeLibrary;

namespace Gestor.Application.ViewModels.Ferramentas;

public class DownloadViewModel : BaseSegurosViewModel
{
	private const string _path = "c:\\AggerSeguros\\";

	private string _head;

	private string _total;

	private string _progresso;

	private decimal _porcentagem;

	private bool _processando = true;

	private Geometry _maximizeRestore = Geometry.Parse((string)Application.Current.Resources[(object)"Maximize"]);

	private Parameters Parameters { get; set; }

	private string CurrentVersion { get; set; }

	public string Head
	{
		get
		{
			return _head;
		}
		set
		{
			_head = value;
			OnPropertyChanged("Head");
		}
	}

	public string Total
	{
		get
		{
			return _total;
		}
		set
		{
			_total = value;
			OnPropertyChanged("Total");
		}
	}

	public string Progresso
	{
		get
		{
			return _progresso;
		}
		set
		{
			_progresso = value;
			OnPropertyChanged("Progresso");
		}
	}

	public decimal Porcentagem
	{
		get
		{
			return _porcentagem;
		}
		set
		{
			_porcentagem = value;
			Progresso = $"{value}% de {Total} MB";
			OnPropertyChanged("Porcentagem");
		}
	}

	public bool Processando
	{
		get
		{
			return _processando;
		}
		set
		{
			_processando = value;
			OnPropertyChanged("Processando");
		}
	}

	public Geometry MaximizeRestore
	{
		get
		{
			return _maximizeRestore;
		}
		set
		{
			_maximizeRestore = value;
			OnPropertyChanged("MaximizeRestore");
		}
	}

	public DownloadViewModel(Parameters parameters)
	{
		Parameters = parameters;
		base.IsEnabled = false;
		Head = "ATUALIZAÇÃO " + Parameters.Directory.ToUpper();
	}

	public async Task Atualizar()
	{
		string rota = (Parameters.Beta ? "Beta" : "Released");
		switch (Parameters.Type)
		{
		default:
		{
			CurrentVersion = await GetCurrentVersion(Parameters.Directory);
			Version val2 = await Connection.Get<Version>($"Update/{rota}/{Parameters.Type}");
			if (VerificarVersao(val2))
			{
				Open();
			}
			else
			{
				await Atualizar(val2);
			}
			break;
		}
		case 88:
			if (!File.Exists("c:\\AggerSeguros\\Aggilizador.Application.exe"))
			{
				Parameters.Arguments = "";
				await AtualizarAggilizador();
			}
			else
			{
				Parameters.Application = "Aggilizador.Application.exe";
				Open();
			}
			break;
		case 7:
			try
			{
				Version val = await Connection.Get<Version>($"Update/{rota}/{Parameters.Type}");
				FileVersionInfo fileVersionInfo = (File.Exists("c:\\AggerSeguros\\Agger.Gestor.exe") ? FileVersionInfo.GetVersionInfo("c:\\AggerSeguros\\Agger.Gestor.exe") : null);
				if (fileVersionInfo == null || !Version.TryParse(fileVersionInfo.FileVersion, out Version result) || !(result >= Version.Parse(val.VersaoAplicacao)))
				{
					await AtualizarGestor(val, criarAtalho: true);
				}
				else
				{
					Funcoes.Destroy<DownloadWindow>();
				}
				break;
			}
			catch (Exception)
			{
				Funcoes.Destroy<DownloadWindow>();
				break;
			}
		case 99:
			await Atualizar(await Connection.Get<Version>($"Update/Released/{Parameters.Type}"));
			break;
		}
	}

	public void Open()
	{
		if (!Parameters.Run)
		{
			Funcoes.Destroy<DownloadWindow>();
			return;
		}
		string fileName = Path.Combine((Parameters.Type == 99 || Parameters.Type == 88) ? "c:\\AggerSeguros\\" : ("c:\\AggerSeguros\\" + CurrentVersion), Parameters.Application);
		try
		{
			Process.Start(fileName, Parameters.Arguments);
		}
		catch
		{
		}
		Funcoes.Destroy<DownloadWindow>();
	}

	private bool CheckFreeSpace()
	{
		DriveInfo driveInfo = new DriveInfo("C");
		if (driveInfo.IsReady)
		{
			return driveInfo.AvailableFreeSpace > 314572800;
		}
		return false;
	}

	public async Task Atualizar(Version version)
	{
		if (!CheckFreeSpace())
		{
			Erro.RegistrarErro(new LogError
			{
				IdFornecedor = ApplicationHelper.IdFornecedor,
				Fornecedor = Recursos.Empresa.Nome,
				UsuarioLogado = Recursos.Usuario.Nome,
				IdUsuarioLogado = ((DomainBase)Recursos.Usuario).Id,
				Versao = ApplicationHelper.Versao.ToString(),
				Data = Funcoes.GetNetworkTime(),
				IdErro = 1001,
				Erro = ValidationHelper.GetDescription((Enum)(object)(TipoErro)1001) + " - " + version.Name,
				HResult = 0,
				HelpLink = "",
				Message = "",
				Source = "",
				StackTrace = "",
				Maquina = Environment.MachineName,
				UsuarioMaquina = Environment.UserName
			});
			return;
		}
		string text = "c:\\AggerSeguros\\" + version.Name;
		if (Directory.Exists(text))
		{
			Directory.Delete(text, recursive: true);
		}
		while (Directory.Exists(text))
		{
			Thread.Sleep(500);
		}
		Directory.CreateDirectory(text);
		using WebClient webClient = new WebClient();
		webClient.DownloadFileCompleted += DownloadFileComplete;
		webClient.DownloadProgressChanged += DownloadProgressCallback;
		CurrentVersion = version.Name;
		string address = ((Parameters.Type == 99) ? (version.Uri + "/" + version.Name + ".exe") : (version.Uri + "/" + version.Name + ".zip"));
		string fileName = ((Parameters.Type == 99) ? (text + ".exe") : (text + "//" + version.Name + ".zip"));
		Stream stream = webClient.OpenRead(address);
		Total = Math.Round((float)long.Parse(webClient.ResponseHeaders["Content-Length"]) / 1024f / 1024f, 2).ToString(CultureInfo.InvariantCulture);
		stream?.Dispose();
		await webClient.DownloadFileTaskAsync(address, fileName);
		webClient.Dispose();
	}

	public async Task AtualizarGestor(Version version, bool criarAtalho = false)
	{
		string text = "c:\\AggerSeguros\\";
		using (WebClient webClient = new WebClient())
		{
			webClient.DownloadFileCompleted += DownloadFileCompleteGestor;
			webClient.DownloadProgressChanged += DownloadProgressCallback;
			CurrentVersion = version.Name;
			string address = version.Uri + "/" + version.Name + ".zip";
			string fileName = text + version.Name + ".zip";
			Stream stream = webClient.OpenRead(address);
			Total = Math.Round((float)long.Parse(webClient.ResponseHeaders["Content-Length"]) / 1024f / 1024f, 2).ToString(CultureInfo.InvariantCulture);
			stream?.Dispose();
			await webClient.DownloadFileTaskAsync(address, fileName);
			webClient.Dispose();
		}
		if (criarAtalho)
		{
			CriarAtalho();
		}
	}

	private void CriarAtalho()
	{
		WshShell wshShell = (WshShell)Activator.CreateInstance(Marshal.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")));
		string text = "c:\\AggerSeguros\\";
		string text2 = "Agger.Gestor.exe";
		string description = "Agger Gestor";
		try
		{
			if (wshShell.CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Agger Gestor.lnk") is IWshShortcut wshShortcut)
			{
				wshShortcut.TargetPath = text + text2;
				wshShortcut.WindowStyle = 1;
				wshShortcut.Description = description;
				wshShortcut.WorkingDirectory = text;
				wshShortcut.IconLocation = text + text2 + ",0";
				wshShortcut.Save();
			}
		}
		catch (Exception)
		{
		}
		try
		{
			if (wshShell.CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.Programs) + "\\Agger Gestor.lnk") is IWshShortcut wshShortcut2)
			{
				wshShortcut2.TargetPath = text + text2;
				wshShortcut2.WindowStyle = 1;
				wshShortcut2.Description = description;
				wshShortcut2.WorkingDirectory = text;
				wshShortcut2.IconLocation = text + text2 + ",0";
				wshShortcut2.Save();
			}
		}
		catch (Exception)
		{
		}
		try
		{
			if (wshShell.CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Agger Gestor.lnk") is IWshShortcut wshShortcut3)
			{
				wshShortcut3.TargetPath = text + text2;
				wshShortcut3.WindowStyle = 1;
				wshShortcut3.Description = description;
				wshShortcut3.WorkingDirectory = text;
				wshShortcut3.IconLocation = text + text2 + ",0";
				wshShortcut3.Save();
			}
		}
		catch (Exception)
		{
		}
		try
		{
			if (wshShell.CreateShortcut(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu) + "\\Agger Gestor.lnk") is IWshShortcut wshShortcut4)
			{
				wshShortcut4.TargetPath = text + text2;
				wshShortcut4.WindowStyle = 1;
				wshShortcut4.Description = description;
				wshShortcut4.WorkingDirectory = text;
				wshShortcut4.IconLocation = text + text2 + ",0";
				wshShortcut4.Save();
			}
		}
		catch (Exception)
		{
		}
	}

	public async Task AtualizarAggilizador()
	{
		if (!CheckFreeSpace())
		{
			Erro.RegistrarErro(new LogError
			{
				IdFornecedor = ApplicationHelper.IdFornecedor,
				Fornecedor = Recursos.Empresa.Nome,
				UsuarioLogado = Recursos.Usuario.Nome,
				IdUsuarioLogado = ((DomainBase)Recursos.Usuario).Id,
				Versao = ApplicationHelper.Versao.ToString(),
				Data = Funcoes.GetNetworkTime(),
				IdErro = 1001,
				Erro = ValidationHelper.GetDescription((Enum)(object)(TipoErro)1001) + " - AGGILIZADOR",
				HResult = 0,
				HelpLink = "",
				Message = "",
				Source = "",
				StackTrace = "",
				Maquina = Environment.MachineName,
				UsuarioMaquina = Environment.UserName
			});
		}
		else
		{
			using WebClient webClient = new WebClient();
			webClient.DownloadFileCompleted += DownloadFileComplete;
			webClient.DownloadProgressChanged += DownloadProgressCallback;
			string address = "https://update.aggilizador.com.br/stable/Instalador.exe";
			string fileName = "c:\\AggerSeguros\\" + Parameters.Application;
			Stream stream = webClient.OpenRead(address);
			Total = Math.Round((float)long.Parse(webClient.ResponseHeaders["Content-Length"]) / 1024f / 1024f, 2).ToString(CultureInfo.InvariantCulture);
			stream?.Dispose();
			await webClient.DownloadFileTaskAsync(address, fileName);
			webClient.Dispose();
		}
	}

	private bool VerificarVersao(Version versao)
	{
		bool flag = File.Exists("c:\\AggerSeguros\\\\" + CurrentVersion + "\\" + Parameters.Application);
		return versao.Name == CurrentVersion && flag;
	}

	private async Task<string> GetCurrentVersion(string name)
	{
		return await Task.Run(delegate
		{
			string[] directories = Directory.GetDirectories("c:\\AggerSeguros\\");
			List<long> list = new List<long>();
			string[] array = directories;
			foreach (string text in array)
			{
				if (text.IndexOf(name, StringComparison.Ordinal) > -1)
				{
					Match match = new Regex("(^[A-Za-z]+)(.)([A-Za-z]+)(\\d+)", RegexOptions.IgnoreCase).Match(text.Replace("c:\\AggerSeguros\\", ""));
					if (match.Success)
					{
						long item = long.Parse(match.Groups[4].Value);
						list.Add(item);
					}
				}
			}
			list.Reverse();
			return (list.Count != 0) ? $"{name}{list.First()}" : "";
		});
	}

	private void DownloadFileComplete(object sender, AsyncCompletedEventArgs e)
	{
		Processando = true;
		Porcentagem = 0m;
		Extract();
		Open();
	}

	private void DownloadFileCompleteGestor(object sender, AsyncCompletedEventArgs e)
	{
		Processando = true;
		Porcentagem = 0m;
		ExtractGestor();
		Funcoes.Destroy<DownloadWindow>();
	}

	public void Extract()
	{
		if (Parameters.Type != 99 && Parameters.Type != 88)
		{
			string text = "c:\\AggerSeguros\\" + CurrentVersion;
			string text2 = text + "\\" + CurrentVersion + ".zip";
			_ = text + "\\" + Parameters.Application;
			ZipFile.ExtractToDirectory(text2, text);
			File.Delete(text2);
		}
	}

	public void ExtractGestor()
	{
		string text = "c:\\AggerSeguros\\" + CurrentVersion + ".zip";
		ZipArchive zipArchive = ZipFile.OpenRead(text);
		try
		{
			foreach (ZipArchiveEntry entry in zipArchive.Entries)
			{
				string fullPath = Path.GetFullPath(Path.Combine("c:\\AggerSeguros\\", entry.FullName));
				fullPath.StartsWith("c:\\AggerSeguros\\", StringComparison.OrdinalIgnoreCase);
				if (entry.Name == "")
				{
					Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
				}
				else
				{
					entry.ExtractToFile(fullPath, overwrite: true);
				}
			}
			zipArchive.Dispose();
			File.Delete(text);
		}
		catch (Exception)
		{
		}
	}

	private void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
	{
		Processando = false;
		Porcentagem = e.ProgressPercentage;
	}
}