using Agger.Registro; using Gestor.Common.Helpers; using Gestor.Common.Validation; using Gestor.Model.API; using Gestor.Model.Domain.Generic; using Gestor.Model.Domain.Seguros; using Gestor.Model.License; using Microsoft.Win32; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace Gestor.Application.Helpers { public class LicenseHelper { private string _guid { get; set; } public static DateTime DataAtual { get; private set; } public static int? DiasRestantes { get; set; } public static Gestor.Model.License.Instalacao Instalacao { get; set; } public static List Produtos { get; set; } public static StatusLicenca Status { get; set; } static LicenseHelper() { LicenseHelper.Status = 1; } public LicenseHelper() { } public async Task FindKey() { string str; string str1 = EncryptionHelper.Decrypt((new RegistryHelper(ApplicationHelper.Subkey)).ForceRead("MACHINEID", false)); str = (string.IsNullOrEmpty(str1) ? string.Concat(this.GetMacAddress(), this.GetMachineSerial()) : str1); string str2 = str; string str3 = await Gestor.Application.Helpers.Connection.Get(string.Concat("Installation/Serial/", str2), false, false); return str3; } public NetworkInterface FindMacAddress(string macToSearch) { string[] strArrays = macToSearch.Split(new char[] { '|' }); return NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault((NetworkInterface ni) => strArrays.Contains(ni.GetPhysicalAddress().ToString())); } private string GetFrameworkVersion() { try { using (RegistryKey registryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey("SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v4\\Full\\")) { if (registryKey != null && registryKey.GetValue("Version") != null) { return registryKey.GetValue("Version").ToString(); } } } catch { } return "<4.5"; } public async Task> GetInstalacoes() { List instalacaos = await Gestor.Application.Helpers.Connection.Get>(string.Format("Installation/Machine/{0}", ApplicationHelper.IdFornecedor), true, false); return instalacaos; } public string GetMacAddress() { IEnumerable strs = ((IEnumerable)NetworkInterface.GetAllNetworkInterfaces()).Where((NetworkInterface ni) => { if (ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { return true; } return ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211; }).OrderByDescending((NetworkInterface ni) => ni.Id).Select((NetworkInterface x) => x.GetPhysicalAddress().ToString()); return string.Join("", strs); } private string GetMachineSerial() { if (string.IsNullOrEmpty(this._guid)) { this._guid = Guid.NewGuid().ToString(); } return this._guid; } public async Task Registrar(string chave) { string str3 = await Task.Run(() => { IEnumerable strs; if (string.IsNullOrEmpty(chave)) { return "false"; } RegistryHelper registryHelper = new RegistryHelper(""); string[] strArrays = EncryptionHelper.Decrypt(chave).Split(new char[] { ' ' }); if ((int)strArrays.Length < 2) { return "false"; } string str = registryHelper.Verificar(strArrays[0], EncryptionHelper.Encrypt(strArrays[0])); if (str != "false") { if (str == "root") { return "root"; } ApplicationHelper.NumeroSerial = strArrays[0]; ApplicationHelper.IdFornecedor = long.Parse(Gestor.Application.Helpers.Connection.Get("Maintenance/Customer", true, false).Result); Instancia.Conexao = null; ApplicationHelper.Subkey = strArrays[0]; return "true"; } DateTime networkTime = Funcoes.GetNetworkTime(); string result = Gestor.Application.Helpers.Connection.Get("Installation/Time", false, true).Result ?? networkTime.ToString("d"); if (!ApplicationHelper.Conectado) { return "false"; } LicenseHelper.DataAtual = DateTime.Parse(string.Format("{0} {1}:{2}:{3}", new object[] { result, networkTime.Hour, networkTime.Minute, networkTime.Second })); DateTime dateTime = DateTime.Parse(strArrays[1]); if (Math.Abs((LicenseHelper.DataAtual - dateTime).TotalDays) > 1) { return "false"; } string str1 = EncryptionHelper.Decrypt(registryHelper.Read("NS", true)); string str2 = registryHelper.Read("SERIALS", false); if (string.IsNullOrWhiteSpace(str2) && !string.IsNullOrWhiteSpace(str1)) { registryHelper.Write("SERIALS", EncryptionHelper.Encrypt(str1), false); str2 = registryHelper.Read("SERIALS", false); } strs = (str2 != null ? EncryptionHelper.Decrypt(str2).Split(new char[] { ':' }).ToList() : new List()); List strs1 = new List(); strs.Distinct().ToList().ForEach((string x) => { if (registryHelper.Verificar(x, EncryptionHelper.Encrypt(x)) == "false") { return; } strs1.Add(x); }); strs1.Add(strArrays[0]); registryHelper.Write("SERIALS", EncryptionHelper.Encrypt(string.Join(":", strs1.Distinct())), false); registryHelper.set_Serial((strs1.Count > 1 ? string.Concat("\\", strArrays[0]) : "")); ApplicationHelper.Subkey = (strs1.Count > 1 ? strArrays[0] : ""); ApplicationHelper.NumeroSerial = strArrays[0]; registryHelper.Write("PERFIL", Gestor.Application.Helpers.Connection.Get(string.Concat("Customer/Name/", strArrays[0]), true, false).Result, true); registryHelper.Write("CURRENTDATE", EncryptionHelper.Encrypt(result), true); registryHelper.Write("DATE", result, true); registryHelper.Write("NS", EncryptionHelper.Encrypt(strArrays[0]), true); registryHelper.Write("INSTALL", EncryptionHelper.Encrypt(strArrays[0]), true); ApplicationHelper.IdFornecedor = long.Parse(Gestor.Application.Helpers.Connection.Get("Maintenance/Customer", true, false).Result); registryHelper.Write("CUSTOMER", EncryptionHelper.Encrypt(ApplicationHelper.IdFornecedor.ToString()), true); Instancia.Conexao = null; return "true"; }); return str3; } public async Task RegistrarMaquina() { bool flag = await Task.Run(() => { int quantidade; string str; if (!ApplicationHelper.Conectado) { return false; } List result = this.GetInstalacoes().Result; Licenca licenca = LicenseHelper.Produtos.FirstOrDefault((Licenca x) => x.get_Produto() == 1); quantidade = (licenca != null ? licenca.get_Quantidade() : 0); if (quantidade <= result.Count((Gestor.Model.License.Instalacao x) => x.get_Gerenciador() != null)) { return false; } string str1 = ""; RegistryHelper registryHelper = new RegistryHelper(""); if (LicenseHelper.Instalacao == null) { string machineSerial = this.GetMachineSerial(); str1 = EncryptionHelper.Encrypt(string.Concat(this.GetMacAddress(), " ", machineSerial)); Gestor.Model.License.Instalacao instalacao = new Gestor.Model.License.Instalacao(); instalacao.set_IdFornecedor(ApplicationHelper.IdFornecedor); instalacao.set_Data(LicenseHelper.DataAtual); instalacao.set_Gerenciador(machineSerial); instalacao.set_NomeMaquina(Environment.MachineName); instalacao.set_UsuarioMaquina(Environment.UserName); instalacao.set_UsuarioId(Recursos.Usuario.get_Id()); instalacao.set_UsuarioSistema(Recursos.Usuario.get_Nome()); instalacao.set_UltimoAcesso(DateTime.Now); Gestor.Model.License.Instalacao instalacao1 = instalacao; IPAddress pAddress = ((IEnumerable)Recursos.Host.AddressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); if (pAddress != null) { str = pAddress.ToString(); } else { str = null; } instalacao1.set_Ip(str); instalacao.set_OSInfo(string.Format("P={0};V={1};x64={2};N={3}", new object[] { (Environment.OSVersion.Platform == PlatformID.Win32NT ? "W" : "O"), Environment.OSVersion.Version, (Environment.Is64BitOperatingSystem ? "1" : "0"), this.GetFrameworkVersion() })); LicenseHelper.Instalacao = instalacao; } registryHelper.Write("MACHINEID", str1, false); LicenseHelper.Instalacao = Gestor.Application.Helpers.Connection.Put("Installation/Machine", LicenseHelper.Instalacao).Result; return true; }); return flag; } public async Task> VerificarAcesso() { Tuple tuple = await Task.Run>(() => { DateTime dateTime; TimeSpan timeSpan; DateTime liberacao; RegistryHelper registryHelper = new RegistryHelper(ApplicationHelper.Subkey); DateTime networkTime = Funcoes.GetNetworkTime(); DateTime date = networkTime.Date; if (!ApplicationHelper.Conectado) { if ((date - LicenseHelper.DataAtual).TotalDays > 2) { return new Tuple(true, "DATA INVÁLIDA"); } dateTime = DateTime.Parse(EncryptionHelper.Decrypt(registryHelper.Read("EXPIRATION", true))); timeSpan = dateTime.AddDays(5) - LicenseHelper.DataAtual; LicenseHelper.DiasRestantes = new int?((int)timeSpan.TotalDays); int? diasRestantes = LicenseHelper.DiasRestantes; if (diasRestantes.GetValueOrDefault() < 1 & diasRestantes.HasValue) { return new Tuple(true, "SISTEMA BLOQUEADO"); } if (EncryptionHelper.Decrypt(registryHelper.Read("BLOCK", true)) == "TRUE") { return new Tuple(true, "SISTEMA BLOQUEADO"); } if (EncryptionHelper.Decrypt(registryHelper.Read("CONSULTA", true)) == "TRUE") { LicenseHelper.Status = 2; } string str = EncryptionHelper.Decrypt(registryHelper.Read("PRODUTOS", true)); if (string.IsNullOrEmpty(str)) { LicenseHelper.Status = 3; return new Tuple(false, "SISTEMA CANCELADO"); } LicenseHelper.Produtos = JsonConvert.DeserializeObject>(str); LicenseHelper.Status = (LicenseHelper.Status != 2 ? 0 : LicenseHelper.Status); return new Tuple(true, EnumHelper.GetDescription(LicenseHelper.Status)); } List result = Gestor.Application.Helpers.Connection.Get>(string.Format("Access/Customer/{0}", ApplicationHelper.IdFornecedor), true, false).Result; List nums = new List() { (long)2, (long)3, (long)4, (long)5, (long)24, (long)10024 }; LicenseHelper.Produtos = ( from x in result group x by new { ProductId = x.get_ProductId(), Status = x.get_Status() }).Select((x) => { DateTime expiration; Licenca licenca = new Licenca(); licenca.set_Produto((int)x.Key.ProductId.GetValueOrDefault()); var collection1 = x; Func> u003cu003e9_2110 = LicenseHelper.u003cu003ec.u003cu003e9__21_10; if (u003cu003e9_2110 == null) { u003cu003e9_2110 = (Access c) => c.get_Control(); LicenseHelper.u003cu003ec.u003cu003e9__21_10 = u003cu003e9_2110; } IEnumerable accessControls1 = collection1.SelectMany(u003cu003e9_2110); Func u003cu003e9_2111 = LicenseHelper.u003cu003ec.u003cu003e9__21_11; if (u003cu003e9_2111 == null) { u003cu003e9_2111 = (AccessControl l) => l.get_Expiration(); LicenseHelper.u003cu003ec.u003cu003e9__21_11 = u003cu003e9_2111; } AccessControl accessControl1 = accessControls1.OrderByDescending(u003cu003e9_2111).FirstOrDefault(); expiration = (accessControl1 != null ? accessControl1.get_Expiration() : networkTime.AddDays(-1)); licenca.set_Liberacao(expiration); licenca.set_AcessoLiberado(x.All((Access l) => { if (l.get_AgreementId().HasValue && nums.Contains(l.get_AgreementId().Value)) { return true; } var collection = x; Func> u003cu003e9_2114 = LicenseHelper.u003cu003ec.u003cu003e9__21_14; if (u003cu003e9_2114 == null) { u003cu003e9_2114 = (Access c) => c.get_Control(); LicenseHelper.u003cu003ec.u003cu003e9__21_14 = u003cu003e9_2114; } IEnumerable accessControls = collection.SelectMany(u003cu003e9_2114); Func u003cu003e9_2115 = LicenseHelper.u003cu003ec.u003cu003e9__21_15; if (u003cu003e9_2115 == null) { u003cu003e9_2115 = (AccessControl d) => d.get_Expiration(); LicenseHelper.u003cu003ec.u003cu003e9__21_15 = u003cu003e9_2115; } AccessControl accessControl = accessControls.OrderByDescending(u003cu003e9_2115).FirstOrDefault(); if (accessControl == null) { return false; } return accessControl.get_Expiration() >= date; })); var collection2 = x; Func u003cu003e9_2113 = LicenseHelper.u003cu003ec.u003cu003e9__21_13; if (u003cu003e9_2113 == null) { u003cu003e9_2113 = (Access l) => l.get_Ammount().GetValueOrDefault(); LicenseHelper.u003cu003ec.u003cu003e9__21_13 = u003cu003e9_2113; } licenca.set_Quantidade((int)collection2.Sum(u003cu003e9_2113)); licenca.set_Status(int.Parse(x.Key.Status ?? "1")); return licenca; }).ToList(); if (LicenseHelper.Produtos != null && LicenseHelper.Produtos.Count != 0) { if (!LicenseHelper.Produtos.All((Licenca x) => x.get_Status() == 3)) { Licenca licenca1 = ( from x in LicenseHelper.Produtos orderby x.get_Liberacao() select x).FirstOrDefault((Licenca x) => { if (x.get_AcessoLiberado()) { return false; } return x.get_Status() == 1; }); liberacao = (licenca1 != null ? licenca1.get_Liberacao() : networkTime); DateTime dateTime1 = liberacao; timeSpan = dateTime1 - date; LicenseHelper.DiasRestantes = new int?((int)timeSpan.TotalDays); registryHelper.Write("EXPIRATION", EncryptionHelper.Encrypt(dateTime1.ToString("d")), true); registryHelper.Write("BLOCK", (dateTime1 >= date ? EncryptionHelper.Encrypt("FALSE") : EncryptionHelper.Encrypt("TRUE")), true); bool flag = LicenseHelper.Produtos.Any((Licenca x) => { if (x.get_Produto() != 1) { return false; } return x.get_Status() == 4; }); registryHelper.Write("CONSULTA", EncryptionHelper.Encrypt(flag.ToString().ToUpper()), true); if (flag) { LicenseHelper.Status = 2; } LicenseHelper.Status = (dateTime1 < date ? 1 : 0); if (LicenseHelper.Produtos.Any((Licenca x) => x.get_Produto() == 1) && LicenseHelper.Status == null) { registryHelper.Write("P1", EncryptionHelper.Encrypt(string.Concat("1$P1#", ApplicationHelper.NumeroSerial)), true); registryHelper.Write("P5", EncryptionHelper.Encrypt(string.Concat("1$P1#", ApplicationHelper.NumeroSerial)), true); registryHelper.Write("M1", EncryptionHelper.Encrypt("TRUE"), true); } IEnumerable produtos = from x in LicenseHelper.Produtos where x.get_Status() == 1 select x; JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); jsonSerializerSetting.set_ReferenceLoopHandling(1); registryHelper.Write("PRODUTOS", EncryptionHelper.Encrypt(JsonConvert.SerializeObject(produtos, 1, jsonSerializerSetting)), true); if (LicenseHelper.Produtos.Find((Licenca p) => p.get_Produto() == 86) != null) { return new Tuple(true, EnumHelper.GetDescription(LicenseHelper.Status)); } if (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(AssinadorHelper.Key().Result)) { List licencas = LicenseHelper.Produtos; Licenca licenca2 = new Licenca(); licenca2.set_AcessoLiberado(true); licenca2.set_Liberacao(date); licenca2.set_Produto(86); licenca2.set_Quantidade(0); licenca2.set_Status(1); licencas.Add(licenca2); } return new Tuple(true, EnumHelper.GetDescription(LicenseHelper.Status)); } } dateTime = networkTime.AddDays(-1); registryHelper.Write("EXPIRATION", EncryptionHelper.Encrypt(dateTime.ToString("d")), true); registryHelper.Write("BLOCK", EncryptionHelper.Encrypt("TRUE"), true); LicenseHelper.Status = 3; return new Tuple(false, ""); }); return tuple; } public async Task VerificarMaquina() { bool flag = await Task.Run(() => { Guid guid; string str; Gestor.Model.License.Instalacao instalacao; string str1; RegistryHelper registryHelper = new RegistryHelper(ApplicationHelper.Subkey); string macAddress = this.GetMacAddress(); if (string.IsNullOrEmpty(registryHelper.Read("MACHINEID", false))) { registryHelper.Write("MACHINEID", EncryptionHelper.Encrypt(string.Concat(macAddress, " ", this.GetMachineSerial())), false); } string[] strArrays = EncryptionHelper.Decrypt(registryHelper.Read("MACHINEID", false)).Split(new char[] { ' ' }); string machineSerial = ((int)strArrays.Length > 1 ? strArrays[1] : strArrays[0]); if (ApplicationHelper.Conectado) { List result = Gestor.Application.Helpers.Connection.Get>(string.Concat("Installation/Machine/", machineSerial, "/GerenciadorList"), true, false).Result; if (!Guid.TryParse(machineSerial, out guid)) { machineSerial = this.GetMachineSerial(); } this._guid = machineSerial; if (result != null) { instalacao = result.FirstOrDefault((Gestor.Model.License.Instalacao x) => x.get_IdFornecedor() == ApplicationHelper.IdFornecedor); } else { instalacao = null; } LicenseHelper.Instalacao = instalacao; if (LicenseHelper.Instalacao != null && LicenseHelper.Instalacao.get_IdFornecedor() != ApplicationHelper.IdFornecedor) { LicenseHelper.Instalacao = null; } if (LicenseHelper.Instalacao != null) { LicenseHelper.Instalacao.set_Gerenciador(machineSerial); LicenseHelper.Instalacao.set_UsuarioId(Recursos.Usuario.get_Id()); LicenseHelper.Instalacao.set_UsuarioSistema(Recursos.Usuario.get_Nome()); Gestor.Model.License.Instalacao instalacao1 = LicenseHelper.Instalacao; IPAddress pAddress = ((IEnumerable)Recursos.Host.AddressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); if (pAddress != null) { str1 = pAddress.ToString(); } else { str1 = null; } instalacao1.set_Ip(str1); LicenseHelper.Instalacao.set_UltimoAcesso(DateTime.Now); LicenseHelper.Instalacao.set_OSInfo(string.Format("P={0};V={1};x64={2};N={3}", new object[] { (Environment.OSVersion.Platform == PlatformID.Win32NT ? "W" : "O"), Environment.OSVersion.Version, (Environment.Is64BitOperatingSystem ? "1" : "0"), this.GetFrameworkVersion() })); LicenseHelper.Instalacao = Gestor.Application.Helpers.Connection.Put("Installation/Machine", LicenseHelper.Instalacao).Result; registryHelper.Write("MACHINEID", EncryptionHelper.Encrypt(string.Concat(macAddress, " ", LicenseHelper.Instalacao.get_Gerenciador())), false); } registryHelper.Write("ACCESS", (LicenseHelper.Instalacao != null || this.RegistrarMaquina().Result ? EncryptionHelper.Encrypt("TRUE") : EncryptionHelper.Encrypt("FALSE")), false); } else if (EncryptionHelper.Decrypt(registryHelper.Read("ACCESS", false)) == "TRUE") { Gestor.Model.License.Instalacao instalacao2 = new Gestor.Model.License.Instalacao(); instalacao2.set_IdFornecedor(ApplicationHelper.IdFornecedor); instalacao2.set_Data(LicenseHelper.DataAtual); instalacao2.set_Gerenciador(machineSerial); instalacao2.set_NomeMaquina(Environment.MachineName); instalacao2.set_UsuarioMaquina(Environment.UserName); instalacao2.set_UsuarioId(Recursos.Usuario.get_Id()); instalacao2.set_UsuarioSistema(Recursos.Usuario.get_Nome()); instalacao2.set_UltimoAcesso(DateTime.Now); IPAddress pAddress1 = ((IEnumerable)Recursos.Host.AddressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); if (pAddress1 != null) { str = pAddress1.ToString(); } else { str = null; } instalacao2.set_Ip(str); LicenseHelper.Instalacao = instalacao2; } if (!LicenseHelper.Produtos.Any((Licenca x) => x.get_Produto() == 1)) { return false; } if (LicenseHelper.Instalacao != null) { return true; } return this.RegistrarMaquina().Result; }); return flag; } public async Task VerificarRegistro() { bool flag = await Task.Run(() => { long idFornecedor; RegistryHelper registryHelper = new RegistryHelper(ApplicationHelper.Subkey); if (string.IsNullOrEmpty(registryHelper.Read("NS", true))) { return false; } string str = EncryptionHelper.Decrypt(registryHelper.Read("CUSTOMER", true)); if (long.TryParse(str, out idFornecedor)) { ApplicationHelper.IdFornecedor = long.Parse(str); } else { ApplicationHelper.IdFornecedor = long.Parse(Gestor.Application.Helpers.Connection.Get("Configuration/Customer", true, false).Result); idFornecedor = ApplicationHelper.IdFornecedor; registryHelper.Write("CUSTOMER", EncryptionHelper.Encrypt(idFornecedor.ToString()), true); } string result = Gestor.Application.Helpers.Connection.Get("Installation/Time", false, false).Result ?? Funcoes.GetNetworkTime().ToString("d"); LicenseHelper.DataAtual = DateTime.Parse(result); registryHelper.Write("CURRENTDATE", EncryptionHelper.Encrypt(result), true); registryHelper.Write("DATE", result, true); List objs = Gestor.Application.Helpers.Connection.Get>(string.Format("Configuration/Customer/{0}", ApplicationHelper.IdFornecedor), true, false).Result; ApplicationHelper.Beta = (objs == null ? false : objs.Any((object x) => x.ToString().Contains("\"Tipo\": 45"))); Address.set_Beta(ApplicationHelper.Beta); return true; }); return flag; } public async Task> VerificarVersao() { Tuple tuple = new Tuple(bool.Parse(await Gestor.Application.Helpers.Connection.Get(string.Format("Installation/Version/{0}", ApplicationHelper.IdFornecedor), true, false)), "VERSÃO INDISPONÍVEL"); return tuple; } } }