public static void AddTaskIfNotExists(Account acc, BotTask task) { if (!acc.Tasks.Any(x => x.GetType() == task.GetType() && x.ExecuteAt > DateTime.Now)) //there is no such BotTask (that will be executed in more than 10sec), add it { AddTask(acc, task); } }
public void Remove(Type typeTask, Village vill = null, int timeBelow = 0, BotTask thisTask = null) { var removeTasks = _tasks.Where(x => x.GetType() == typeTask); // if vill is specificed, pick task from that vill if (vill != null) { removeTasks = removeTasks.Where(x => x.Vill == vill); } // if thisTask is specificed, dont remove it if (thisTask != null) { removeTasks = removeTasks.Where(x => x != thisTask); } // if timeBelow is specificed, pick task has time excuted in next "timeBelow" mins if (timeBelow > 0) { removeTasks = removeTasks.Where(x => x.ExecuteAt < DateTime.Now.AddMinutes(timeBelow)); } _tasks.RemoveAll(x => removeTasks.Contains(x)); ReOrder(); }
public static void RemoveSameTasks(Account acc, Type type, BotTask thisTask) { acc.Tasks.RemoveAll(x => x.GetType() == type && x != thisTask ); }
private void NoTasks(Account acc) { BotTask task = null; var updateVill = acc.Villages.FirstOrDefault(x => x.Timings.NextVillRefresh < DateTime.Now); if (updateVill != null) { // Update the village task = new UpdateDorf1 { Vill = updateVill }; } else if (acc.Settings.AutoCloseDriver && TimeSpan.FromMinutes(5) < TimeHelper.NextPrioTask(acc, TaskPriority.Medium)) { // Auto close chrome and reopen when there is a high/normal prio BotTask task = new ReopenDriver(); ((ReopenDriver)task).LowestPrio = TaskPriority.Medium; } else if (acc.Settings.AutoRandomTasks) { task = new RandomTask(); } if (task != null) { task.ExecuteAt = DateTime.Now; task.Priority = TaskPriority.Low; TaskExecutor.AddTask(acc, task); } }
/// <summary> /// /// </summary> /// <returns></returns> public BotTask GetNextTask() { BotTask returnValue = null; if (ActiveTemplate != null) { // get if (ActiveTemplate.Tasks.Count > currentTask) { returnValue = ActiveTemplate.Tasks[currentTask]; } // raise or reset if (ActiveTemplate.Tasks.Count > currentTask + 1) { currentTask++; } else { currentTask = 0; } } return(returnValue); }
public static void AddTaskIfNotExists(Account acc, BotTask task) { if (!acc.Tasks.Any(x => x.GetType() == task.GetType())) { AddTask(acc, task); } }
public static void AddTaskIfNotExistInVillage(Account acc, Village vill, BotTask task) { if (!TaskExistsInVillage(acc, vill, task.GetType())) { AddTask(acc, task); } }
BotTask GetSubTask(string url, string postData, string queryName, BotTask currentTask) { var newTask = new BotTask { QueryName = queryName ?? currentTask.QueryName, BotType = currentTask.BotType, UserCompanyID = currentTask.UserCompanyID, EntityID = currentTask.EntityID, SiteID = currentTask.SiteID, SiteName = currentTask.SiteName, MaxItemSizePeerLink = currentTask.MaxItemSizePeerLink, UserCompanyBrandID = currentTask.UserCompanyBrandID, BotBrandID = currentTask.BotBrandID, BotItemID = currentTask.BotItemID, BotProductID = currentTask.BotProductID, BotShopID = currentTask.BotShopID, AddtionalParamters = string.IsNullOrEmpty(postData) ? url : url + PostDataPrefix + postData, ID = currentTask.ID, FriendlyName = currentTask.FriendlyName, IsSnapshotBot = currentTask.IsSnapshotBot, UserCompanyProductID = currentTask.UserCompanyProductID, IsTempSubTask = true, }; return(newTask); }
public static void AddTask(Account acc, BotTask task) { //acc.Tasks.FirstOrDefault(x=>x.GetType == task.GetType) acc.Tasks.Add(task); //Console.WriteLine($"{DateTime.Now.ToString()}] Adding task {task.GetType()} for village {task.vill?.Name}, will get executed in {(task.ExecuteAt - DateTime.Now).TotalSeconds}s"); ReorderTaskList(acc); }
public IBotTask ReloadAnomaly() { var ReloadAnomalyFactory = new BotTask { Component = null, Effects = ReloadAnomalyFunction() }; return(ReloadAnomalyFactory); }
/// <summary> /// Called when there's not enough resources to finish the task. Task will get saved into unfinished task list /// and will be finished later (when we have enough resources). /// </summary> /// <param name="vill">Village</param> /// <param name="task">Unfinished task</param> /// <param name="needed">Resources needed by this task</param> public static void AddUnfinishedTask(Village vill, BotTask task, Resources needed) { vill.UnfinishedTasks.Add(new VillUnfinishedTask { ResNeeded = needed, Task = task }); }
public static void AddTask(Account acc, BotTask task) { if (task.ExecuteAt == null) { task.ExecuteAt = DateTime.Now; } acc.Tasks.Add(task); ReorderTaskList(acc); }
/// <summary> /// Gets name of the task /// </summary> /// <returns>Name of the task</returns> public static string GetName(this BotTask task) { var type = task.GetType().ToString().Split('.'); if (type.Length == 0) { return(null); } return(type[type.Length - 1]); }
/// <summary> /// Returns whether or not a task is allowed to fire. This determination is based off its status and /// whether or not enough time has passed since the last time it was fired. /// </summary> /// <param name="identifier">The name of the task that we want to look up.</param> /// <returns>A boolean denoting whether or not that task is allowed to fire.</returns> public bool Allowed(string identifier) { BotTask task = this.Lookup(identifier); if (task == null) { return(false); } return(task.Status == BotTaskStatus.Active && FloodValid(identifier)); }
/// <summary> /// Invoke all PostTasks that a task might have. /// </summary> /// <param name="task">The task</param> /// <param name="acc">Account</param> private static void PostTask(BotTask task, Account acc) { if (task.PostTaskCheck != null) { foreach (var postTask in task.PostTaskCheck) { postTask.Invoke(acc.Wb.Html, acc); } task.PostTaskCheck.Clear(); } }
public BotTask ToBotTask() { BotTask tsk = new BotTask { ID = _id, SiteName = SiteName, AddtionalParamters = Url, QueryName = QueryName, }; return(tsk); }
public static void AddTaskIfNotExistInVillage(Account acc, Village vill, BotTask task) { var taskExists = acc.Tasks.Any(x => x.GetType() == task.GetType() && x.Vill == vill ); if (!taskExists) { AddTask(acc, task); } }
private async void NewTick() { try { if (acc.Tasks.Count == 0) { return; //No tasks } // Another task is already in progress. wait if (acc.Tasks.Any(x => x.Stage != TaskStage.Start)) { return; } var tasks = acc.Tasks.Where(x => x.ExecuteAt <= DateTime.Now).ToList(); if (tasks.Count == 0) { NoTasks(acc); return; } BotTask firstTask = tasks.FirstOrDefault(x => x.Priority == TaskPriority.High); if (firstTask == null) { firstTask = tasks.FirstOrDefault(x => x.Priority == TaskPriority.Medium); } if (firstTask == null) { firstTask = tasks.FirstOrDefault(); } firstTask.Stage = TaskStage.Executing; //If correct village is selected, otherwise change village if (firstTask.Vill != null) { var active = acc.Villages.FirstOrDefault(x => x.Active); if (active != null && active != firstTask.Vill) { await VillageHelper.SwitchVillage(acc, firstTask.Vill.Id); } } await TaskExecutor.Execute(acc, firstTask); } catch (Exception e) { acc?.Wb?.Log($"Error in TaskTimer! {e.Message}\n{e.StackTrace}"); } }
public void Add(BotTask task, bool IfNotExists = false, Village vill = null) { if (IfNotExists && IsTaskExists(task.GetType(), vill)) { return; } if (task.ExecuteAt == null) { task.ExecuteAt = DateTime.Now; } _tasks.Add(task); ReOrder(); }
public static void AddPersistentTask(BotTask task, string serverName) { string fileName = Path.Combine(AppPath, "serverName.json"); if (!File.Exists(fileName)) { File.Create(fileName); } try { var rawText = File.ReadAllText(fileName); var jsonAsDict = JsonConvert.DeserializeObject <Dictionary <string, object> >(rawText); } catch (Exception ex) { Logger.Error(ex); } }
/// <summary> /// Finds the best delivery task for the specified pod. /// Sets <code>chooseRestLocation</code> to null if none found, otherwise <code>bestDeliveryRequest</code> and <code>bestTimeForDeliveryRequest</code> are initialized. /// </summary> /// <param name="bot">The bot to consider.</param> public Waypoint chooseRestLocation(Bot bot) { BotTask lastTask = GetLastEnqueuedTask(bot); // Find closest free storage location Waypoint closest = null; double closestDistance = double.PositiveInfinity; foreach (var w in Instance.ResourceManager.UnusedRestingLocations) { double distance = bot.GetDistance(w); // If it's closer than the previous closest, then use this new one instead if (distance < closestDistance) { closestDistance = distance; closest = w; } } return(closest); }
public bool FloodValid(string identifier) { if (!Tasks.ContainsKey(identifier)) { return(false); } BotTask task = Tasks[identifier]; long prevTime = task.LastFireTime; long currTime = MiscUtil.GetUnixTime(); bool overTime = (currTime - prevTime >= task.MinTime); if (overTime) { task.LastFireTime = currTime; } return(overTime); }
private void NoTasks(Account acc) { BotTask task = null; if (acc.Settings.AutoCloseDriver && TimeSpan.FromMinutes(5) < TimeHelper.NextPrioTask(acc, TaskPriority.Medium)) { // Auto close chrome and reopen when there is a high/normal prio BotTask task = new ReopenDriver(); ((ReopenDriver)task).LowestPrio = TaskPriority.Medium; } else if (acc.Settings.AutoRandomTasks) { task = new RandomTask(); } if (task != null) { task.ExecuteAt = DateTime.Now; task.Priority = TaskPriority.Low; acc.Tasks.Add(task); } }
public static void AddTask(Account acc, BotTask task) { acc.Tasks.Add(task); ReorderTaskList(acc); }
/// <summary> /// Removes all pending BotTasks of specific type. You can specify only the village where it will /// remove the selected tasks and optionally not remove the 'thisTask' /// </summary> public static void RemoveTaskTypes(Account acc, Type type, Village vill = null, BotTask thisTask = null) { var removeTasks = acc.Tasks.Where(x => x.GetType() == type); if (vill == null) // Only remove tasks for a specific village { removeTasks = removeTasks.Where(x => x.Vill == vill); } if (thisTask == null) // Don't remove this task { removeTasks = removeTasks.Where(x => x != thisTask); } // Remove all 'removeTasks' from the account task list removeTasks.ToList().ForEach(x => acc.Tasks.Remove(x)); }
/// <summary> /// Removes all pending BotTasks of specific type for specific village except for the task calling it /// Called by UpdateDorf1/2 since they are called a lot. /// </summary> /// <param name="acc"></param> /// <param name="vill"></param> /// <param name="type"></param> /// <param name="thisTask"></param> public static void RemoveSameTasksForVillage(Account acc, Village vill, Type type, BotTask thisTask) { acc.Tasks.RemoveAll(x => x.Vill == vill && x.GetType() == type && x != thisTask ); }
/// <summary> /// Removes all pending BotTasks of specific type except for the task calling it /// </summary> /// <param name="acc">Account</param> /// <param name="thisTask">Task not to remove</param> public static void RemoveSameTasks(Account acc, BotTask thisTask) => RemoveSameTasks(acc, thisTask.GetType(), thisTask);
/// <summary> /// Used by BotTasks to insert resources/coordinates into the page. /// </summary> /// <param name="acc">Account</param> /// <param name="resources">Target resources</param> /// <param name="coordinates">Target coordinates</param> /// <returns>Time it will take for transit to complete</returns> public static async Task <TimeSpan> MarketSendResource(Account acc, Resources resources, Village targetVillage, BotTask botTask) => await MarketSendResource(acc, resources.ToArray(), targetVillage, botTask);
/// <summary> /// Called PageLoaded (after navigating to a specific url) or from /// Task timer, if there is no url/bot is already on the url /// </summary> /// <param name="acc">Account</param> /// <param name="task">Task to be executed</param> /// <returns></returns> public static async Task Execute(Account acc, BotTask task) { // Before every execution, wait a random delay if (acc.AccInfo.ServerVersion == Classificator.ServerVersionEnum.T4_5) { await Task.Delay(AccountHelper.Delay()); } if (acc.Wb?.CurrentUrl == null && task.GetType() != typeof(CheckProxy)) { await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/dorf1.php"); } if (task.Vill == null) { task.Vill = acc.Villages.FirstOrDefault(x => x.Active); } try { acc.Wb.Log($"Executing task {task.GetName()}" + (task.Vill == null ? "" : $" in village {task.Vill.Name}")); switch (await task.Execute(acc)) { case TaskRes.Retry: task.RetryCounter++; if (task.NextExecute == null) { task.NextExecute = DateTime.Now.AddMinutes(3); } break; default: task.RetryCounter = 0; if (task.NextTask != null) { task.NextTask.ExecuteAt = DateTime.MinValue.AddHours(5); task.NextTask.Stage = TaskStage.Start; TaskExecutor.AddTask(acc, task.NextTask); task.NextTask = null; } break; } } catch (Exception e) { if (acc.Wb != null) { acc.Wb.Log($"Error executing task {task.GetName()}! Vill {task.Vill?.Name}", e); } task.RetryCounter++; if (task.NextExecute == null) { task.NextExecute = DateTime.Now.AddMinutes(3); } } //We want to re-execute the same task later if (task.NextExecute != null && task.RetryCounter < 3) { task.ExecuteAt = task.NextExecute ?? default; task.NextExecute = null; ReorderTaskList(acc); task.Stage = TaskStage.Start; return; } // Remove the task from the task list acc.Tasks.Remove(task); }
/// <summary> /// Used by BotTasks to insert resources/coordinates into the page. /// </summary> /// <param name="acc">Account</param> /// <param name="resources">Target resources</param> /// <param name="coordinates">Target coordinates</param> /// <returns>Time it will take for transit to complete</returns> public static async Task <TimeSpan> MarketSendResource(Account acc, long[] resources, Village targetVillage, BotTask botTask) { var times = 1; if (acc.AccInfo.GoldClub ?? false) { times = 3; } else if (acc.AccInfo.PlusAccount) { times = 2; } // No resources to send if (resources.Sum() == 0) { return(TimeSpan.Zero); } var sendRes = resources.Select(x => x / times).ToArray(); //round the resources that we want to send, so it looks less like a bot (var merchantsCapacity, var merchantsNum) = MarketHelper.ParseMerchantsInfo(acc.Wb.Html); // We don't have any merchants. if (merchantsNum == 0) { //Parse currently ongoing transits var transits = MarketParser.ParseTransits(acc.Wb.Html); var activeVill = acc.Villages.FirstOrDefault(x => x.Active); // Could also just pass that in params var nextTry = SoonestAvailableMerchants(acc, activeVill, targetVillage, transits); if (nextTry != DateTime.MaxValue) { nextTry = nextTry.AddSeconds(5); } botTask.NextExecute = nextTry; // Just return something, will get overwritten anyways. return(new TimeSpan((int)(nextTry - DateTime.Now).TotalHours + 1, 0, 0)); } var maxRes = merchantsCapacity * times; var allRes = resources.Sum(); if (allRes > maxRes) { // We don't have enough merchants to transit all the resources. Divide all resources by some divider. var resDivider = (float)allRes / maxRes; float[] resFloat = sendRes.Select(x => x / resDivider).ToArray(); sendRes = resFloat.Select(x => (long)Math.Floor(x)).ToArray(); } var wb = acc.Wb.Driver; for (int i = 0; i < 4; i++) { // To avoid exception devide by zero if (50 <= sendRes[i]) { //round the number to about -1%, for rounder numbers var digits = Math.Ceiling(Math.Log10(sendRes[i])); var remainder = sendRes[i] % (long)Math.Pow(10, digits - 2); sendRes[i] -= remainder; await DriverHelper.WriteById(acc, "r" + (i + 1), sendRes[i]); } await Task.Delay(AccountHelper.Delay() / 5); } // Input coordinates await DriverHelper.WriteCoordinates(acc, targetVillage.Coordinates); //Select x2/x3 if (times != 1) { wb.ExecuteScript($"document.getElementById('x2').value='{times}'"); await Task.Delay(AccountHelper.Delay() / 5); } await DriverHelper.ClickById(acc, "enabledButton"); var durNode = acc.Wb.Html.GetElementbyId("target_validate"); if (durNode == null && acc.Wb.Html.GetElementbyId("prepareError") != null) { // Error "Abuse! You have not enough resources." is displayed. } //get duration of transit var dur = durNode.Descendants("td").ToList()[3].InnerText.Replace("\t", "").Replace("\n", ""); // Will NOT trigger a page reload! Thus we should await some time before continuing. await DriverHelper.ClickById(acc, "enabledButton"); targetVillage.Market.LastTransit = DateTime.Now; var duration = TimeParser.ParseDuration(dur); return(TimeSpan.FromTicks(duration.Ticks * (times * 2 - 1))); }