public async static Task <string> UpdateCredential(string credentialFileName)
        {
            try
            {
                string script = $"/servicesCeltaWare/consolegoogle/ServicesCeltaWare.UtilitariosInfra.ConsoleGoogleApi 5 {credentialFileName} \"destinationName\" \"url\" \"folderId\" ";
                string msg    = await CommandBash.Execute(script);

                if (!msg.ToUpperInvariant().Contains("OK"))
                {
                    return(msg);
                }
                return(msg);
                //string url = "http://192.168.100.115:8080/file/TokenResponse-user.TokenResponse-user";
                //string destino = "/servicesCeltaWare/consolegoogle/credential/Google.Apis.Auth.OAuth2.Responses.TokenResponse-user";
                //Uri siteUri = new Uri(url);
                //WebClient client = new WebClient();
                //await client.DownloadFileTaskAsync(siteUri, destino);
                //return "ok";
            }
            catch (Exception err)
            {
                if (err.InnerException != null)
                {
                    HelperLogs.WriteLog("HelperGoogleDrive UpdateCredential", err.Message + "\n" + err.InnerException.Message);
                    return(err.Message + "\n" + err.InnerException.Message);
                }
                HelperLogs.WriteLog("HelperGoogleDrive UpdateCredential", err.Message + "\n" + err.InnerException.Message);
                return(err.Message);
            }
        }
Exemplo n.º 2
0
        public async Task <string> ExecuteDatabaseSchedule(Model.ModelBackupSchedule _backupSchedule, ModelTaskServiceSettings _setting)
        {
            UtilitariosInfra.UtilTelegram _utilTelegram = new UtilitariosInfra.UtilTelegram(_setting.UidTelegramToken);
            bool isUpdated;

            try
            {
                bool response = false;

                response = await ExecuteBackup(_backupSchedule, _setting);

                if (response)
                {
                    bool res = await ExecuteValidateBackup(_backupSchedule, _setting);

                    if (!res)
                    {
                        response = false;
                    }
                }
                else
                {
                    _utilTelegram.SendMessage($"Falha na execução de backup: {_backupSchedule.Databases.DatabaseName}:{_backupSchedule.DateHourExecution.ToShortTimeString()}\n Tipo: {_backupSchedule.Type}", _setting.UidTelegramDestino);

                    isUpdated = await UpdateStatusDateTimeBackup(_backupSchedule, Model.Enum.BackupStatus.Corrupted, _setting);

                    return("Arquivo corrompido.");
                }

                if (response)
                {
                    if (_setting.IsDebug)
                    {
                        _utilTelegram.SendMessage($"Backup Executado com sucesso: {_backupSchedule.Databases.DatabaseName}:{_backupSchedule.DateHourExecution.ToShortTimeString()}\n Tipo: {_backupSchedule.Type}", _setting.UidTelegramDestino);
                    }
                    return("OK");
                }
                _utilTelegram.SendMessage($"Falha ao validar arquivo backup: {_backupSchedule.Databases.DatabaseName}:{_backupSchedule.DateHourExecution.ToShortTimeString()}\n Tipo: {_backupSchedule.Type}", _setting.UidTelegramDestino);

                isUpdated = await UpdateStatusDateTimeBackup(_backupSchedule, Model.Enum.BackupStatus.Corrupted, _setting);

                return("Arquivo corrompido.");
            }
            catch (Exception err)
            {
                isUpdated = await UpdateStatusDateTimeBackup(_backupSchedule, Model.Enum.BackupStatus.Failed, _setting);

                _utilTelegram.SendMessage($"Falha no sistema de backup: {_backupSchedule.Databases.DatabaseName}:{_backupSchedule.DateHourExecution.ToString()} - { err.Message}", _setting.UidTelegramDestino);

                if (err.InnerException != null)
                {
                    HelperLogs.WriteLog("HelperSqlDatabase", err.Message + "\n" + err.InnerException.Message);
                    return(err.Message + "\n" + err.InnerException.Message);
                }
                HelperLogs.WriteLog("HelperSqlDatabase", err.Message);
                return(err.Message);
            }
        }
Exemplo n.º 3
0
        public async Task <string> BackupRun(Model.ModelBackupSchedule _backupSchedule, ModelTaskServiceSettings _setting)
        {
            UtilitariosInfra.UtilTelegram _utilTelegram = new UtilitariosInfra.UtilTelegram(_setting.UidTelegramToken);

            try
            {
                var isExecuted = await ExecuteDatabaseSchedule(_backupSchedule, _setting);

                if (isExecuted.ToUpperInvariant().Contains("OK"))
                {
                    var resp = await UpdateStatusDateTimeBackup(_backupSchedule, Model.Enum.BackupStatus.Success, _setting);

                    return(isExecuted);

                    #region lixeira
                    ////backup garantido.. então inicie o upload
                    //var googleDriveFileId = await _helperGoogleDrive.UploadBackup(_backupSchedule, _setting);
                    //if (googleDriveFileId.Contains("ERRO"))
                    //{
                    //    resp = await UpdateStatusBackup(_backupSchedule, Model.Enum.BackupStatus.OutOfDate, true, _setting);
                    //    _utilTelegram.SendMessage($"Falha no Upload do Backup {_backupSchedule.Databases.DatabaseName}, tipo {_backupSchedule.Type}: {googleDriveFileId}", _configuration.GetSection("Services").GetSection("UidTelegramDestino").Value);
                    //    new Exception(googleDriveFileId);
                    //}
                    //else
                    //{
                    //    _backupSchedule.GoogleDriveFileId = googleDriveFileId;
                    //    resp = await UpdateStatusBackup(_backupSchedule, Model.Enum.BackupStatus.Success, true, _setting);
                    //    if (!resp.Equals("sucess"))
                    //    {
                    //        _utilTelegram.SendMessage($"Falha no serviço TaskManager: Erro ao atualizar status do backup, GoogleFileId e Status. " + resp, _configuration.GetSection("Services").GetSection("UidTelegramDestino").Value);
                    //    }
                    //}
                    #endregion
                }

                return(isExecuted);
            }
            catch (Exception err)
            {
                var isUpdated = await UpdateStatusDateTimeBackup(_backupSchedule, Model.Enum.BackupStatus.Failed, _setting);

                _utilTelegram.SendMessage($"Falha no serviço TaskManager: " + err.Message + "\n" + err.StackTrace, _configuration.GetSection("Services").GetSection("UidTelegramDestino").Value);
                if (err.InnerException != null)
                {
                    HelperLogs.WriteLog("HelperSqlDatabase", err.Message + "\n" + err.InnerException.Message);
                    return(err.Message + "\n" + err.InnerException.Message);
                }
                return(err.Message);
            }
        }
Exemplo n.º 4
0
        public async Task <string> ExecuteUpload(Model.ModelBackupSchedule _backupSchedule, ModelTaskServiceSettings _setting)
        {
            UtilitariosInfra.UtilTelegram _utilTelegram = new UtilitariosInfra.UtilTelegram(_setting.UidTelegramToken);
            bool isUpdated;

            try
            {
                string resp = null;
                isUpdated = await UpdateStatusDateTimeUpload(_backupSchedule, Model.Enum.BackupStatus.Uploading, _setting);

                var googleDriveFileId = await _helperGoogleDrive.UploadBackup(_backupSchedule, _setting);

                if (googleDriveFileId.ToUpperInvariant().Contains("ERRO"))
                {
                    isUpdated = await UpdateStatusDateTimeUpload(_backupSchedule, Model.Enum.BackupStatus.OutOfDate, _setting);

                    _utilTelegram.SendMessage($"Falha no Upload do Backup {_backupSchedule.Databases.DatabaseName}, tipo {_backupSchedule.Type}: {googleDriveFileId}", _configuration.GetSection("Services").GetSection("UidTelegramDestino").Value);
                    new Exception(googleDriveFileId);
                }
                else
                {
                    _backupSchedule.GoogleDriveFileId = googleDriveFileId;
                    isUpdated = await UpdateStatusDateTimeUpload(_backupSchedule, Model.Enum.BackupStatus.Success, _setting);

                    if (!isUpdated)
                    {
                        _utilTelegram.SendMessage($"Falha ao atualizar status do backup, TaskService ExecUpload. \n" + resp, _configuration.GetSection("Services").GetSection("UidTelegramDestino").Value);
                    }
                }

                return(resp);
            }
            catch (Exception err)
            {
                isUpdated = await UpdateStatusDateTimeUpload(_backupSchedule, Model.Enum.BackupStatus.OutOfDate, _setting);

                if (!isUpdated)
                {
                    _utilTelegram.SendMessage($"Falha ao atualizar status do backup, TaskService ExecUpload. \n", _configuration.GetSection("Services").GetSection("UidTelegramDestino").Value);
                }
                if (err.InnerException != null)
                {
                    HelperLogs.WriteLog("HelperSqlDatabase", err.Message + "\n" + err.InnerException.Message);
                    return(err.Message + "\n" + err.InnerException.Message);
                }
                HelperLogs.WriteLog("HelperSqlDatabase", err.Message);
                return(err.Message);
            }
        }
Exemplo n.º 5
0
        public async Task <string> UploadBackup(Model.ModelBackupSchedule _backupSchedule, ModelTaskServiceSettings _setting)
        {
            UtilitariosInfra.UtilTelegram _utilTelegram = new UtilitariosInfra.UtilTelegram(_setting.UidTelegramToken);

            try
            {
                string url           = "http://" + _backupSchedule.CustomerProduct.Server.IpAddress + ":" + _backupSchedule.CustomerProduct.Server.Port;
                var    json          = JsonConvert.SerializeObject(_backupSchedule);
                var    stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");

                var streamResult = await client.PostAsync(url + "/api/GoogleDriveService/Upload", stringContent);

                if (!streamResult.IsSuccessStatusCode)
                {
                    _utilTelegram.SendMessage($"Falha no Upload {_backupSchedule.Databases.DatabaseName}, tipo {_backupSchedule.Type}: \n Retorno Status Code Http: {streamResult.StatusCode} \n Chamada api: /api/GoogleDriveService/Upload.", _setting.UidTelegramDestino);
                    return("ERRO: " + await streamResult.Content.ReadAsStringAsync());
                }

                if (streamResult.IsSuccessStatusCode)
                {
                    if (_setting.IsDebug)
                    {
                        _utilTelegram.SendMessage($"Backup armazenado no GDrive com sucesso: {_backupSchedule.Databases.DatabaseName}:{_backupSchedule.DateHourExecution.ToShortTimeString()}\rTipo: {_backupSchedule.Type}", _setting.UidTelegramDestino);
                    }
                }

                return(await streamResult.Content.ReadAsStringAsync());
            }
            catch (Exception err)
            {
                if (err.InnerException != null)
                {
                    HelperLogs.WriteLog("HelperSqlDatabase", err.Message + "\n" + err.InnerException.Message);
                    _utilTelegram.SendMessage($"Falha durante armazenamento no GDrive: {_backupSchedule.Databases.DatabaseName}:{_backupSchedule.DateHourExecution.ToString()} \n Mensagem: { err.Message} \n {err.InnerException.Message}", _setting.UidTelegramDestino);
                    return(err.Message + "\n" + err.InnerException.Message);
                }
                HelperLogs.WriteLog("HelperSqlDatabase", err.Message);
                _utilTelegram.SendMessage($"Falha durante armazenamento no GDrive: {_backupSchedule.Databases.DatabaseName}:{_backupSchedule.DateHourExecution.ToString()} \n Mensagem: { err.Message}", _setting.UidTelegramDestino);
                return(err.Message);
            }
        }
        public async Task <IActionResult> Upload(ModelBackupSchedule _databaseSchedule)
        {
            try
            {
                ModelGoogleDrive googleDrive = new ModelGoogleDrive();
                googleDrive = Helpers.HelperGoogleDrive.LoadSetting(_configuration);
                string path           = _databaseSchedule.Databases.Directory + "/" + _databaseSchedule.Directory + "/";
                string backupFileName = null;
                if (_databaseSchedule.Type == ServicesCeltaWare.Model.Enum.BackuypType.MysqlFull)
                {
                    backupFileName = $"{_databaseSchedule.Databases.ConteinerName}Backup.sql";
                }
                else
                {
                    backupFileName = Helpers.DatabaseServiceHelper.ReturnBackupName(_databaseSchedule);
                }

                if (_databaseSchedule.GoogleDriveFolderId == null)
                {
                    return(BadRequest($"{_databaseSchedule.Databases.DatabaseName} GoogleDriveFolderId nulo!"));
                }

                var resp = await Helpers.HelperGoogleDrive.UploadFromLinux(googleDrive.CredentialFileName, backupFileName, path, _databaseSchedule.GoogleDriveFolderId);

                if (resp.Contains("The access token has expired and could not be refreshed"))
                {
                    HelperLogs.WriteLog("GoogleDriveServiceController. ", resp);
                    var respUpdate = await Helpers.HelperGoogleDrive.UpdateCredential(googleDrive.CredentialFileName);

                    if (respUpdate.ToUpperInvariant().Contains("OK"))
                    {
                        var resp2 = await Helpers.HelperGoogleDrive.UploadFromLinux(googleDrive.CredentialFileName, backupFileName, path, _databaseSchedule.GoogleDriveFolderId);
                    }
                    else
                    {
                        return(BadRequest("Não foi possível atualizar arquivo de credencial. \n" + respUpdate));
                    }
                }

                if (resp.Contains("Failed"))
                {
                    HelperLogs.WriteLog("GoogleDriveServiceController", resp);
                    await Task.Delay(2000);

                    var resp2 = await Helpers.HelperGoogleDrive.UploadFromLinux(googleDrive.CredentialFileName, backupFileName, path, _databaseSchedule.GoogleDriveFolderId);

                    if (resp2.Contains("ok"))
                    {
                        resp = resp2;
                    }
                    else
                    {
                        HelperLogs.WriteLog("GoogleDriveServiceController", resp2);
                        return(BadRequest("Não foi possível atualizar o backup pela segunda vez!. \n" + resp2));
                    }
                }

                if (resp.Contains("ERRO: Arquivo não existe") || resp.Contains("Error:\"invalid_grant\"") ||
                    resp.Contains("The operation was canceled"))
                {
                    HelperLogs.WriteLog("GoogleDriveServiceController", resp);
                    return(Forbid());
                }

                return(Ok(resp));
            }
            catch (Exception err)
            {
                if (err.InnerException != null)
                {
                    HelperLogs.WriteLog("GoogleDriveServiceController", err.Message + "\n" + err.InnerException.Message);
                    return(BadRequest(err.Message + "\n" + err.InnerException.Message));
                }
                HelperLogs.WriteLog("GoogleDriveServiceController", err.Message);
                return(BadRequest(err.Message));
            }
        }