private void Initialize() { if (initialized) { return; } initialized = true; timer.Elapsed += (sender, args) => CheckForUpdate(); UpdateRoutine = DownloadMode switch { DownloadMode.Dynamic => new DynamicUpdateRoutine(appConfiguration), DownloadMode.Compressed => new CompressedUpdateRoutine(), //DownloadMode.Custom => null, _ => throw new ArgumentOutOfRangeException() }; UpdateRoutine.Started += NotifyStartEvent; UpdateRoutine.Finished += NotifyFinishEvent; UpdateRoutine.ProgressChanged += NotifyProgressChanged; }
public async static Task RunRoutine <T>(this T device, BaseRoutine <T> routine) where T : IDevice { await routine.Run(device); }
private void ProcessMsgAsInput(EvtUserMessageArgs e) { //Ignore commands as inputs if (e.UsrMessage.Message.StartsWith(DataConstants.COMMAND_IDENTIFIER) == true) { return; } GameConsole usedConsole = null; int lastConsoleID = 1; using (BotDBContext context = DatabaseManager.OpenContext()) { lastConsoleID = (int)DataHelper.GetSettingIntNoOpen(SettingsConstants.LAST_CONSOLE, context, 1L); GameConsole lastConsole = context.Consoles.FirstOrDefault(c => c.ID == lastConsoleID); if (lastConsole != null) { //Create a new console using data from the database usedConsole = new GameConsole(lastConsole.Name, lastConsole.InputList, lastConsole.InvalidCombos); } } //If there are no valid inputs, don't attempt to parse if (usedConsole == null) { MsgHandler.QueueMessage($"The current console does not point to valid data. Please set a different console to use, or if none are available, add one."); return; } if (usedConsole.ConsoleInputs.Count == 0) { MsgHandler.QueueMessage($"The current console, \"{usedConsole.Name}\", does not have any available inputs."); } ParsedInputSequence inputSequence = default; string userName = e.UsrMessage.Username; int defaultDur = 200; int defaultPort = 0; try { int maxDur = 60000; string regexStr = usedConsole.InputRegex; string readyMessage = string.Empty; //Get default and max input durations //Use user overrides if they exist, otherwise use the global values User user = DataHelper.GetUser(userName); //Get default controller port defaultPort = (int)user.ControllerPort; defaultDur = (int)DataHelper.GetUserOrGlobalDefaultInputDur(userName); maxDur = (int)DataHelper.GetUserOrGlobalMaxInputDur(userName); //TRBotLogger.Logger.Information($"Default dur: {defaultDur} | Max dur: {maxDur}"); using (BotDBContext context = DatabaseManager.OpenContext()) { //Get input synonyms for this console IQueryable <InputSynonym> synonyms = context.InputSynonyms.Where(syn => syn.ConsoleID == lastConsoleID); //Prepare the message for parsing readyMessage = InputParser.PrepParse(e.UsrMessage.Message, context.Macros, synonyms); } //Parse inputs to get our parsed input sequence inputSequence = InputParser.ParseInputs(readyMessage, regexStr, new ParserOptions(defaultPort, defaultDur, true, maxDur)); TRBotLogger.Logger.Debug(inputSequence.ToString()); TRBotLogger.Logger.Debug("Reverse Parsed (on parse): " + ReverseParser.ReverseParse(inputSequence, usedConsole, new ReverseParser.ReverseParserOptions(ReverseParser.ShowPortTypes.ShowNonDefaultPorts, defaultPort, ReverseParser.ShowDurationTypes.ShowNonDefaultDurations, defaultDur))); } catch (Exception exception) { string excMsg = exception.Message; //Handle parsing exceptions MsgHandler.QueueMessage($"ERROR PARSING: {excMsg} | {exception.StackTrace}", Serilog.Events.LogEventLevel.Warning); inputSequence.ParsedInputResult = ParsedInputResults.Invalid; } //Check for non-valid messages if (inputSequence.ParsedInputResult != ParsedInputResults.Valid) { //Display error message for invalid inputs if (inputSequence.ParsedInputResult == ParsedInputResults.Invalid) { MsgHandler.QueueMessage(inputSequence.Error); } return; } #region Parser Post-Process Validation /* All this validation may be able to be performed faster. * Find a way to speed it up. */ long globalInputPermLevel = DataHelper.GetSettingInt(SettingsConstants.GLOBAL_INPUT_LEVEL, 0L); int userControllerPort = 0; long userLevel = 0; using (BotDBContext context = DatabaseManager.OpenContext()) { User user = DataHelper.GetUserNoOpen(e.UsrMessage.Username, context); //Check if the user is silenced and ignore the message if so if (user.HasEnabledAbility(PermissionConstants.SILENCED_ABILITY) == true) { return; } //Ignore based on user level and permissions if (user.Level < globalInputPermLevel) { MsgHandler.QueueMessage($"Inputs are restricted to levels {(PermissionLevels)globalInputPermLevel} and above."); return; } userControllerPort = (int)user.ControllerPort; userLevel = user.Level; } //First, add delays between inputs if we should //We do this first so we can validate the inserted inputs later //The blank inputs can have a different permission level if (DataHelper.GetUserOrGlobalMidInputDelay(e.UsrMessage.Username, out long midInputDelay) == true) { MidInputDelayData midInputDelayData = ParserPostProcess.InsertMidInputDelays(inputSequence, userControllerPort, (int)midInputDelay, usedConsole); //If it's successful, replace the input list and duration if (midInputDelayData.Success == true) { int oldDur = inputSequence.TotalDuration; inputSequence.Inputs = midInputDelayData.NewInputs; inputSequence.TotalDuration = midInputDelayData.NewTotalDuration; //TRBotLogger.Logger.Debug($"Mid input delay success. Message: {midInputDelayData.Message} | OldDur: {oldDur} | NewDur: {inputSequence.TotalDuration}\n{ReverseParser.ReverseParse(inputSequence, usedConsole, new ReverseParser.ReverseParserOptions(ReverseParser.ShowPortTypes.ShowAllPorts, 0))}"); } } InputValidation validation = default; using (BotDBContext context = DatabaseManager.OpenContext()) { User user = DataHelper.GetUserNoOpen(userName, context); //Check for restricted inputs on this user validation = ParserPostProcess.InputSequenceContainsRestrictedInputs(inputSequence, user.GetRestrictedInputs()); if (validation.InputValidationType != InputValidationTypes.Valid) { if (string.IsNullOrEmpty(validation.Message) == false) { MsgHandler.QueueMessage(validation.Message); } return; } //Check for invalid input combinations validation = ParserPostProcess.ValidateInputCombos(inputSequence, usedConsole.InvalidCombos, DataContainer.ControllerMngr, usedConsole); if (validation.InputValidationType != InputValidationTypes.Valid) { if (string.IsNullOrEmpty(validation.Message) == false) { MsgHandler.QueueMessage(validation.Message); } return; } } //Check for level permissions and ports validation = ParserPostProcess.ValidateInputLvlPermsAndPorts(userLevel, inputSequence, DataContainer.ControllerMngr, usedConsole.ConsoleInputs); if (validation.InputValidationType != InputValidationTypes.Valid) { if (string.IsNullOrEmpty(validation.Message) == false) { MsgHandler.QueueMessage(validation.Message, Serilog.Events.LogEventLevel.Warning); } return; } #endregion //Make sure inputs aren't stopped if (InputHandler.InputsHalted == true) { //We can't process inputs because they're currently stopped MsgHandler.QueueMessage("New inputs cannot be processed until all other inputs have stopped.", Serilog.Events.LogEventLevel.Warning); return; } //Fetch these values ahead of time to avoid passing the database context through so many methods long autoPromoteEnabled = DataHelper.GetSettingInt(SettingsConstants.AUTO_PROMOTE_ENABLED, 0L); long autoPromoteInputReq = DataHelper.GetSettingInt(SettingsConstants.AUTO_PROMOTE_INPUT_REQ, long.MaxValue); long autoPromoteLevel = DataHelper.GetSettingInt(SettingsConstants.AUTO_PROMOTE_LEVEL, -1L); string autoPromoteMsg = DataHelper.GetSettingString(SettingsConstants.AUTOPROMOTE_MESSAGE, string.Empty); bool addedInputCount = false; TRBotLogger.Logger.Debug($"Reverse Parsed (post-process): " + ReverseParser.ReverseParse(inputSequence, usedConsole, new ReverseParser.ReverseParserOptions(ReverseParser.ShowPortTypes.ShowNonDefaultPorts, defaultPort, ReverseParser.ShowDurationTypes.ShowNonDefaultDurations, defaultDur))); //Get the max recorded inputs per-user long maxUserRecInps = DataHelper.GetSettingInt(SettingsConstants.MAX_USER_RECENT_INPUTS, 0L); //It's a valid input - save it in the user's stats //Also record the input if we should using (BotDBContext context = DatabaseManager.OpenContext()) { User user = DataHelper.GetUserNoOpen(e.UsrMessage.Username, context); //Ignore if the user is opted out if (user.IsOptedOut == false) { user.Stats.ValidInputCount++; addedInputCount = true; context.SaveChanges(); //If we should store recent user inputs, do so if (maxUserRecInps > 0) { //Get the input sequence - we may have added mid input delays between //As a result, we'll need to reverse parse it string message = ReverseParser.ReverseParse(inputSequence, usedConsole, new ReverseParser.ReverseParserOptions(ReverseParser.ShowPortTypes.ShowNonDefaultPorts, (int)user.ControllerPort, ReverseParser.ShowDurationTypes.ShowNonDefaultDurations, defaultDur)); //Add the recorded input user.RecentInputs.Add(new RecentInput(message)); context.SaveChanges(); int diff = user.RecentInputs.Count - (int)maxUserRecInps; //If we're over the max after adding, remove if (diff > 0) { //Order by ascending ID and take the difference //Lower IDs = older entries IEnumerable <RecentInput> shouldRemove = user.RecentInputs.OrderBy(r => r.UserID).Take(diff); foreach (RecentInput rec in shouldRemove) { user.RecentInputs.Remove(rec); context.SaveChanges(); } } } } } bool autoPromoted = false; //Check if auto promote is enabled and auto promote the user if applicable if (addedInputCount == true) { using (BotDBContext context = DatabaseManager.OpenContext()) { User user = DataHelper.GetUserNoOpen(e.UsrMessage.Username, context); //Check if the user was already autopromoted, autopromote is enabled, //and if the user reached the autopromote input count requirement if (user.Stats.AutoPromoted == 0 && autoPromoteEnabled > 0 && user.Stats.ValidInputCount >= autoPromoteInputReq) { //Only autopromote if this is a valid permission level //We may not want to log or send a message for this, as it has potential to be very spammy, //and it's not something the users can control if (PermissionHelpers.IsValidPermissionValue(autoPromoteLevel) == true) { //Mark the user as autopromoted and save user.Stats.AutoPromoted = 1; autoPromoted = true; context.SaveChanges(); } } } } if (autoPromoted == true) { //If the user is already at or above this level, don't set them to it //Only set if the user is below if (userLevel < autoPromoteLevel) { //Adjust abilities and promote to the new level DataHelper.AdjustUserLvlAndAbilitiesOnLevel(userName, autoPromoteLevel); if (string.IsNullOrEmpty(autoPromoteMsg) == false) { PermissionLevels permLvl = (PermissionLevels)autoPromoteLevel; string finalMsg = autoPromoteMsg.Replace("{0}", userName).Replace("{1}", permLvl.ToString()); MsgHandler.QueueMessage(finalMsg); } } } InputModes inputMode = (InputModes)DataHelper.GetSettingInt(SettingsConstants.INPUT_MODE, 0L); //If the mode is Democracy, add it as a vote for this input if (inputMode == InputModes.Democracy) { //Set up the routine if it doesn't exist BaseRoutine foundRoutine = RoutineHandler.FindRoutine(RoutineConstants.DEMOCRACY_ROUTINE_ID, out int indexFound); DemocracyRoutine democracyRoutine = null; if (foundRoutine == null) { long voteTime = DataHelper.GetSettingInt(SettingsConstants.DEMOCRACY_VOTE_TIME, 10000L); democracyRoutine = new DemocracyRoutine(voteTime); RoutineHandler.AddRoutine(democracyRoutine); } else { democracyRoutine = (DemocracyRoutine)foundRoutine; } democracyRoutine.AddInputSequence(userName, inputSequence.Inputs); } //If it's Anarchy, carry out the input else { /************************************ * Finally carry out the inputs now! * ************************************/ InputHandler.CarryOutInput(inputSequence.Inputs, usedConsole, DataContainer.ControllerMngr); } }
public override void ExecuteCommand(EvtChatCommandArgs args) { List <string> arguments = args.Command.ArgumentsAsList; long curInputMode = DataHelper.GetSettingInt(SettingsConstants.INPUT_MODE, 0L); InputModes inpMode = (InputModes)curInputMode; //See the input mode if (arguments.Count == 0) { QueueMessage($"The current input mode is {inpMode}. To set the input mode, add one as an argument: {CachedInputModesStr}"); return; } //Invalid number of arguments if (arguments.Count > 1) { QueueMessage(UsageMessage); return; } using (BotDBContext context = DatabaseManager.OpenContext()) { //Check if the user has the ability to set the mode User user = DataHelper.GetUserNoOpen(args.Command.ChatMessage.Username, context); if (user != null && user.HasEnabledAbility(PermissionConstants.SET_INPUT_MODE_ABILITY) == false) { QueueMessage("You don't have the ability to set the input mode!"); return; } } string inputModeStr = arguments[0]; //Parse if (EnumUtility.TryParseEnumValue(inputModeStr, out InputModes parsedInputMode) == false) { QueueMessage($"Please enter a valid input mode: {CachedInputModesStr}"); return; } //Same mode if (parsedInputMode == inpMode) { QueueMessage($"The current input mode is already {inpMode}!"); return; } using (BotDBContext context = DatabaseManager.OpenContext()) { //Set the value and save Settings inputModeSetting = DataHelper.GetSettingNoOpen(SettingsConstants.INPUT_MODE, context); inputModeSetting.ValueInt = (long)parsedInputMode; context.SaveChanges(); } QueueMessage($"Changed the input mode from {inpMode} to {parsedInputMode}!"); //If we set it to Anarchy, check if the Democracy routine is active and remove it if so if (parsedInputMode == InputModes.Anarchy) { BaseRoutine democracyRoutine = RoutineHandler.FindRoutine(RoutineConstants.DEMOCRACY_ROUTINE_ID, out int indexFound); if (democracyRoutine != null) { RoutineHandler.RemoveRoutine(indexFound); } } //If we set it to Democracy, add the routine if it's not already active else if (parsedInputMode == InputModes.Democracy) { DemocracyRoutine democracyRoutine = RoutineHandler.FindRoutine <DemocracyRoutine>(); if (democracyRoutine == null) { long votingTime = DataHelper.GetSettingInt(SettingsConstants.DEMOCRACY_VOTE_TIME, 10000L); democracyRoutine = new DemocracyRoutine(votingTime); RoutineHandler.AddRoutine(democracyRoutine); } } }
public override void ExecuteCommand(EvtChatCommandArgs args) { List <string> arguments = args.Command.ArgumentsAsList; //Ignore with too few arguments if (arguments.Count > 1) { QueueMessage(UsageMessage); return; } if (arguments.Count == 0) { long periodicInputVal = DataHelper.GetSettingInt(SettingsConstants.PERIODIC_INPUT_ENABLED, 0L); string enabledStr = (periodicInputVal <= 0) ? "disabled" : "enabled"; QueueMessage($"The periodic input is currently {enabledStr}. To change the periodic input enabled state, pass either \"true\" or \"false\" as an argument."); return; } //Check for sufficient permissions using (BotDBContext context = DatabaseManager.OpenContext()) { User user = DataHelper.GetUserNoOpen(args.Command.ChatMessage.Username, context); if (user == null || user.HasEnabledAbility(PermissionConstants.SET_PERIODIC_INPUT_ABILITY) == false) { QueueMessage("You do not have the ability to change the periodic input state!"); return; } } string newStateStr = arguments[0].ToLowerInvariant(); if (bool.TryParse(newStateStr, out bool newState) == false) { QueueMessage("Invalid argument. To enable or disable the periodic input, pass either \"true\" or \"false\" as an argument."); return; } long newVal = (newState == true) ? 1L : 0L; bool oldState = false; using (BotDBContext context = DatabaseManager.OpenContext()) { Settings periodicInput = DataHelper.GetSettingNoOpen(SettingsConstants.PERIODIC_INPUT_ENABLED, context); if (periodicInput == null) { periodicInput = new Settings(SettingsConstants.PERIODIC_INPUT_ENABLED, string.Empty, 0L); context.SettingCollection.Add(periodicInput); context.SaveChanges(); } //Same value - don't make changes if ((periodicInput.ValueInt > 0 && newVal > 0) || (periodicInput.ValueInt <= 0 && newVal <= 0)) { QueueMessage("The periodic input state is already this value!"); return; } oldState = (periodicInput.ValueInt > 0) ? true : false; periodicInput.ValueInt = newVal; context.SaveChanges(); } //Now add or remove the routine if we should if (oldState == true && newState == false) { RoutineHandler.RemoveRoutine(RoutineConstants.PERIODIC_INPUT_ROUTINE_ID); } //Add the routine else if (oldState == false && newState == true) { BaseRoutine routine = RoutineHandler.FindRoutine(RoutineConstants.PERIODIC_INPUT_ROUTINE_ID, out int indexFound); if (routine == null) { RoutineHandler.AddRoutine(new PeriodicInputRoutine()); } else { QueueMessage("Huh? The periodic input routine is somehow already running even though it was just enabled."); } } if (newState == true) { QueueMessage("Enabled periodic inputs. Every now and then, an input sequence will be automatically performed."); } else { QueueMessage("Disabled periodic inputs."); } }