Esempio n. 1
0
        public Automation UpdateAutomation(string id, AutomationViewModel request)
        {
            Guid entityId           = new Guid(id);
            var  existingAutomation = _repo.GetOne(entityId);

            if (existingAutomation == null)
            {
                throw new EntityDoesNotExistException($"Automation with id {id} could not be found");
            }

            existingAutomation.Name             = request.Name;
            existingAutomation.AutomationEngine = GetAutomationEngine(request.AutomationEngine);

            var automationVersion = _automationVersionRepository.Find(null, q => q.AutomationId == existingAutomation.Id).Items?.FirstOrDefault();

            if (!string.IsNullOrEmpty(automationVersion.Status))
            {
                //check if previous value was not published before setting published properties
                automationVersion.Status = request.Status;
                if (automationVersion.Status == "Published")
                {
                    automationVersion.PublishedBy    = _httpContextAccessor.HttpContext.User.Identity.Name;
                    automationVersion.PublishedOnUTC = DateTime.UtcNow;
                }
                _automationVersionRepository.Update(automationVersion);
            }
            return(existingAutomation);
        }
        public async Task <IActionResult> Post([FromBody] CreateJobViewModel request)
        {
            if (request == null)
            {
                ModelState.AddModelError("Save", "No data passed");
                return(BadRequest(ModelState));
            }

            Guid entityId = Guid.NewGuid();

            if (request.Id == null || !request.Id.HasValue || request.Id.Equals(Guid.Empty))
            {
                request.Id = entityId;
            }
            try
            {
                Job        job        = request.Map(request); //assign request to job entity
                Automation automation = automationRepo.GetOne(job.AutomationId ?? Guid.Empty);

                if (automation == null) //no automation was found
                {
                    ModelState.AddModelError("Save", "No automation was found for the specified automation id");
                    return(NotFound(ModelState));
                }
                AutomationVersion automationVersion = automationVersionRepo.Find(null, q => q.AutomationId == automation.Id).Items?.FirstOrDefault();

                job.AutomationVersion   = automationVersion.VersionNumber;
                job.AutomationVersionId = automationVersion.Id;

                foreach (var parameter in request.JobParameters ?? Enumerable.Empty <JobParameter>())
                {
                    parameter.JobId     = entityId;
                    parameter.CreatedBy = applicationUser?.UserName;
                    parameter.CreatedOn = DateTime.UtcNow;
                    parameter.Id        = Guid.NewGuid();
                    jobParameterRepo.Add(parameter);
                }

                //send SignalR notification to all connected clients
                await _hub.Clients.All.SendAsync("botnewjobnotification", request.AgentId.ToString());

                await _hub.Clients.All.SendAsync("sendjobnotification", "New Job added.");

                await _hub.Clients.All.SendAsync("broadcastnewjobs", Tuple.Create(request.Id, request.AgentId, request.AutomationId));

                await webhookPublisher.PublishAsync("Jobs.NewJobCreated", job.Id.ToString()).ConfigureAwait(false);


                return(await base.PostEntity(job));
            }
            catch (Exception ex)
            {
                return(ex.GetActionResult());
            }
        }
Esempio n. 3
0
        public bool DeleteAutomation(Guid automationId)
        {
            var automation = repo.GetOne(automationId);

            //remove automation version entity associated with automation
            var  automationVersion   = automationVersionRepository.Find(null, q => q.AutomationId == automationId).Items?.FirstOrDefault();
            Guid automationVersionId = (Guid)automationVersion.Id;

            automationVersionRepository.SoftDelete(automationVersionId);

            bool isDeleted = false;

            if (automation != null)
            {
                //remove binary object entity associated with automation
                binaryObjectRepository.SoftDelete(automation.BinaryObjectId);
                repo.SoftDelete(automation.Id.Value);

                isDeleted = true;
            }

            return(isDeleted);
        }
        public Job UpdateJob(string jobId, CreateJobViewModel request, ApplicationUser applicationUser)
        {
            Guid entityId = new Guid(jobId);

            var existingJob = _repo.GetOne(entityId);

            if (existingJob == null)
            {
                throw new EntityDoesNotExistException("Unable to find a job for the specified id");
            }

            Automation automation = _automationRepo.GetOne(existingJob.AutomationId ?? Guid.Empty);

            if (automation == null) //no automation was found
            {
                throw new EntityDoesNotExistException("No automation was found for the specified automation id");
            }

            AutomationVersion automationVersion = _automationVersionRepo.Find(null, q => q.AutomationId == automation.Id).Items?.FirstOrDefault();

            existingJob.AutomationVersion   = automationVersion.VersionNumber;
            existingJob.AutomationVersionId = automationVersion.Id;

            existingJob.AgentId                = request.AgentId;
            existingJob.AgentGroupId           = request.AgentGroupId;
            existingJob.StartTime              = request.StartTime;
            existingJob.EndTime                = request.EndTime;
            existingJob.ExecutionTimeInMinutes = (existingJob.EndTime.Value - existingJob.StartTime).Value.TotalMinutes;
            existingJob.DequeueTime            = request.DequeueTime;
            existingJob.AutomationId           = request.AutomationId;
            existingJob.JobStatus              = request.JobStatus;
            existingJob.Message                = request.Message;
            existingJob.IsSuccessful           = request.IsSuccessful;

            UpdateJobParameters(request.JobParameters, existingJob.Id);

            if (request.EndTime != null)
            {
                UpdateAutomationAverages(existingJob.Id);
            }

            return(existingJob);
        }
Esempio n. 5
0
        public string CreateJob(string scheduleSerializeObject, IEnumerable <ParametersViewModel>?parameters)
        {
            var schedule = JsonSerializer.Deserialize <Schedule>(scheduleSerializeObject);

            if (organizationSettingManager.HasDisallowedExecution())
            {
                return("DisallowedExecution");
            }

            var automationVersion = automationVersionRepository.Find(null, a => a.AutomationId == schedule.AutomationId).Items?.FirstOrDefault();

            //if this is a scheduled job get the schedule parameters
            if (schedule.StartingType.Equals("RunNow") == false)
            {
                List <ParametersViewModel> parametersList = new List <ParametersViewModel>();

                var scheduleParameters = scheduleParameterRepository.Find(null, p => p.ScheduleId == schedule.Id).Items;
                foreach (var scheduleParameter in scheduleParameters)
                {
                    ParametersViewModel parametersViewModel = new ParametersViewModel
                    {
                        Name      = scheduleParameter.Name,
                        DataType  = scheduleParameter.DataType,
                        Value     = scheduleParameter.Value,
                        CreatedBy = scheduleParameter.CreatedBy,
                        CreatedOn = DateTime.UtcNow
                    };
                    parametersList.Add(parametersViewModel);
                }
                parameters = parametersList.AsEnumerable();
            }

            Job job = new Job();

            job.AgentId             = schedule.AgentId == null ? Guid.Empty : schedule.AgentId.Value;
            job.CreatedBy           = schedule.CreatedBy;
            job.CreatedOn           = DateTime.UtcNow;
            job.EnqueueTime         = DateTime.UtcNow;
            job.JobStatus           = JobStatusType.New;
            job.AutomationId        = schedule.AutomationId == null ? Guid.Empty : schedule.AutomationId.Value;
            job.AutomationVersion   = automationVersion != null ? automationVersion.VersionNumber : 0;
            job.AutomationVersionId = automationVersion != null ? automationVersion.Id : Guid.Empty;
            job.Message             = "Job is created through internal system logic.";

            foreach (var parameter in parameters ?? Enumerable.Empty <ParametersViewModel>())
            {
                JobParameter jobParameter = new JobParameter
                {
                    Name      = parameter.Name,
                    DataType  = parameter.DataType,
                    Value     = parameter.Value,
                    JobId     = job.Id ?? Guid.Empty,
                    CreatedBy = schedule.CreatedBy,
                    CreatedOn = DateTime.UtcNow,
                    Id        = Guid.NewGuid()
                };
                jobParameterRepository.Add(jobParameter);
            }

            jobRepository.Add(job);
            _hub.Clients.All.SendAsync("botnewjobnotification", job.AgentId.ToString());
            webhookPublisher.PublishAsync("Jobs.NewJobCreated", job.Id.ToString()).ConfigureAwait(false);

            return("Success");
        }
Esempio n. 6
0
        public async Task <IActionResult> Update(string id, [FromForm] AutomationViewModel request)
        {
            Guid entityId           = new Guid(id);
            var  existingAutomation = repository.GetOne(entityId);

            if (existingAutomation == null)
            {
                return(NotFound());
            }

            if (request.File == null)
            {
                ModelState.AddModelError("Save", "No data passed");
                return(BadRequest(ModelState));
            }

            long size = request.File.Length;

            if (size <= 0)
            {
                ModelState.AddModelError("Automation Upload", $"File size of automation {request.File.FileName} cannot be 0");
                return(BadRequest(ModelState));
            }

            string binaryObjectId = existingAutomation.BinaryObjectId.ToString();
            var    binaryObject   = binaryObjectRepo.GetOne(Guid.Parse(binaryObjectId));
            string organizationId = binaryObject.OrganizationId.ToString();

            if (!string.IsNullOrEmpty(organizationId))
            {
                organizationId = manager.GetOrganizationId().ToString();
            }

            try
            {
                BinaryObject newBinaryObject = new BinaryObject();
                if (existingAutomation.BinaryObjectId != Guid.Empty && size > 0)
                {
                    string apiComponent = "AutomationAPI";
                    //update file in OpenBots.Server.Web using relative directory
                    newBinaryObject.Id                  = Guid.NewGuid();
                    newBinaryObject.Name                = request.File.FileName;
                    newBinaryObject.Folder              = apiComponent;
                    newBinaryObject.StoragePath         = Path.Combine("BinaryObjects", organizationId, apiComponent, newBinaryObject.Id.ToString());
                    newBinaryObject.CreatedBy           = applicationUser?.UserName;
                    newBinaryObject.CreatedOn           = DateTime.UtcNow;
                    newBinaryObject.CorrelationEntityId = request.Id;
                    binaryObjectRepo.Add(newBinaryObject);
                    binaryObjectManager.Upload(request.File, organizationId, apiComponent, newBinaryObject.Id.ToString());
                    binaryObjectManager.SaveEntity(request.File, newBinaryObject.StoragePath, newBinaryObject, apiComponent, organizationId);
                    binaryObjectRepo.Update(binaryObject);
                }

                //update automation (create new automation and automation version entities)
                Automation        response          = existingAutomation;
                AutomationVersion automationVersion = automationVersionRepo.Find(null, q => q.AutomationId == response.Id).Items?.FirstOrDefault();
                if (existingAutomation.Name.Trim().ToLower() != request.Name.Trim().ToLower() || automationVersion.Status.Trim().ToLower() != request.Status?.Trim().ToLower())
                {
                    existingAutomation.OriginalPackageName = request.File.FileName;
                    existingAutomation.AutomationEngine    = request.AutomationEngine;
                    automationVersion.Status = request.Status;
                }
                else
                {
                    request.BinaryObjectId = newBinaryObject.Id;
                    response = manager.UpdateAutomation(existingAutomation, request);
                }

                await webhookPublisher.PublishAsync("Files.NewFileCreated", newBinaryObject.Id.ToString(), newBinaryObject.Name).ConfigureAwait(false);

                await webhookPublisher.PublishAsync("Automations.AutomationUpdated", existingAutomation.Id.ToString(), existingAutomation.Name).ConfigureAwait(false);

                return(Ok(response));
            }
            catch (Exception ex)
            {
                return(ex.GetActionResult());
            }
        }
Esempio n. 7
0
        public string CreateJob(string scheduleSerializeObject, IEnumerable<ParametersViewModel>? parameters)
        {
            var schedule = JsonSerializer.Deserialize<Schedule>(scheduleSerializeObject);
            //if schedule has expired
            if (DateTime.UtcNow > schedule.ExpiryDate)
            {
                _recurringJobManager.RemoveIfExists(schedule.Id.Value.ToString());//removes an existing recurring job
                return "ScheduleExpired";
            }

            if (_organizationSettingManager.HasDisallowedExecution())
            {
                return "DisallowedExecution";
            }

            //if this is not a "RunNow" job, then use the schedule parameters
            if (schedule.StartingType.Equals("RunNow") == false)
            {
                if (schedule.MaxRunningJobs != null)
                {
                    if (ActiveJobLimitReached(schedule.Id, schedule.MaxRunningJobs))
                    {
                        return "ActiveJobLimitReached";
                    }
                }

                List<ParametersViewModel> parametersList = new List<ParametersViewModel>();

                var scheduleParameters = _scheduleParameterRepository.Find(null, p => p.ScheduleId == schedule.Id).Items;
                foreach (var scheduleParameter in scheduleParameters)
                {
                    ParametersViewModel parametersViewModel = new ParametersViewModel
                    {
                        Name = scheduleParameter.Name,
                        DataType = scheduleParameter.DataType,
                        Value = scheduleParameter.Value,
                        CreatedBy = scheduleParameter.CreatedBy,
                        CreatedOn = DateTime.UtcNow
                    };
                    parametersList.Add(parametersViewModel);
                }
                parameters = parametersList.AsEnumerable();
            }

            var automationVersion = _automationVersionRepository.Find(null, a => a.AutomationId == schedule.AutomationId).Items?.FirstOrDefault();

            Job job = new Job();
            job.AgentId = schedule.AgentId == null ? Guid.Empty : schedule.AgentId.Value;
            job.AgentGroupId = schedule.AgentGroupId == null ? Guid.Empty : schedule.AgentGroupId.Value;
            job.CreatedBy = schedule.CreatedBy;
            job.CreatedOn = DateTime.UtcNow;
            job.EnqueueTime = DateTime.UtcNow;
            job.JobStatus = JobStatusType.New;
            job.AutomationId = schedule.AutomationId == null ? Guid.Empty : schedule.AutomationId.Value;
            job.AutomationVersion = automationVersion != null ? automationVersion.VersionNumber : 0;
            job.AutomationVersionId = automationVersion != null ? automationVersion.Id : Guid.Empty;
            job.Message = "Job is created through internal system logic.";
            job.ScheduleId = schedule.Id;

            foreach (var parameter in parameters ?? Enumerable.Empty<ParametersViewModel>())
            {
                JobParameter jobParameter = new JobParameter
                {
                    Name = parameter.Name,
                    DataType = parameter.DataType,
                    Value = parameter.Value,
                    JobId = job.Id ?? Guid.Empty,
                    CreatedBy = schedule.CreatedBy,
                    CreatedOn = DateTime.UtcNow,
                    Id = Guid.NewGuid()
                };
                _jobParameterRepository.Add(jobParameter);
            }
            _jobRepository.Add(job);

            if (job.AgentGroupId == null || job.AgentGroupId == Guid.Empty)
            {
                _hub.Clients.All.SendAsync("botnewjobnotification", job.AgentId.ToString());
            }
            else //notify all group members
            {
                var agentsInGroup = _agentGroupManager.GetAllMembersInGroup(job.AgentGroupId.ToString());
                foreach (var groupMember in agentsInGroup ?? Enumerable.Empty<AgentGroupMember>())
                {
                    _hub.Clients.All.SendAsync("botnewjobnotification", groupMember.AgentId.ToString());
                }
            }

            _webhookPublisher.PublishAsync("Jobs.NewJobCreated", job.Id.ToString()).ConfigureAwait(false);

            return "Success";
        }