summaryrefslogtreecommitdiff
path: root/Decompiler/Gestor.Application.ViewModels.Ferramentas/DownloadViewModel.cs
diff options
context:
space:
mode:
Diffstat (limited to 'Decompiler/Gestor.Application.ViewModels.Ferramentas/DownloadViewModel.cs')
-rw-r--r--Decompiler/Gestor.Application.ViewModels.Ferramentas/DownloadViewModel.cs482
1 files changed, 482 insertions, 0 deletions
diff --git a/Decompiler/Gestor.Application.ViewModels.Ferramentas/DownloadViewModel.cs b/Decompiler/Gestor.Application.ViewModels.Ferramentas/DownloadViewModel.cs
new file mode 100644
index 0000000..1246bfe
--- /dev/null
+++ b/Decompiler/Gestor.Application.ViewModels.Ferramentas/DownloadViewModel.cs
@@ -0,0 +1,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;
+ }
+}