From 59c62e62e223dcff0ff563c860fb29c3e3de79dc Mon Sep 17 00:00:00 2001 From: Zontreck Date: Sun, 28 Jun 2020 03:27:04 -0700 Subject: [PATCH] Revise the message handler system, and partially the command system --- Assembly/ASMInfo.cs | 4 +- BotSession.cs | 3 +- ChatLogger.cs | 6 +- CommandSystem/BaseCommands.cs | 20 +++ CommandSystem/BaseHooks.cs | 41 +++---- CommandSystem/CommandGroup.cs | 4 +- CommandSystem/CommandHelp.cs | 14 +-- CommandSystem/CommandManager.cs | 43 +++---- CommandSystem/CommandRegistry.cs | 45 +++---- GroupLog.cs | 10 +- IProgram.cs | 2 +- Level System/Auth.cs | 16 +-- MessageHandler.cs | 205 ++++++++++++++++++++++++++----- NonCommands/NotCommand.cs | 2 +- NonCommands/nCMD.cs | 2 +- NonCommands/nRegistry.cs | 2 +- Program.cs | 124 ++++++++----------- WebHookServer/HookCmds.cs | 7 +- WebHookServer/WebHookServer.cs | 9 +- 19 files changed, 350 insertions(+), 209 deletions(-) create mode 100644 CommandSystem/BaseCommands.cs diff --git a/Assembly/ASMInfo.cs b/Assembly/ASMInfo.cs index ab1bb1f..c97f62a 100644 --- a/Assembly/ASMInfo.cs +++ b/Assembly/ASMInfo.cs @@ -6,7 +6,7 @@ using System.Reflection; [assembly: AssemblyCompany("ZNI")] [assembly: AssemblyAlgorithmId(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)] [assembly: AssemblyCopyright("© 2020 Tara Piccari")] -[assembly: AssemblyFileVersion("5.2.112")] +[assembly: AssemblyFileVersion("5.3.091")] [assembly: AssemblyDescription("Second Life Bot - BotCore5")] @@ -15,7 +15,7 @@ namespace Bot.Assemble public class ASMInfo { public static string BotName = "ZBotCore"; - public static string BotVer = "5.2.112"; + public static string BotVer = "5.3.091"; public static string GitPassword { get diff --git a/BotSession.cs b/BotSession.cs index 91f64ac..84333e2 100644 --- a/BotSession.cs +++ b/BotSession.cs @@ -35,8 +35,6 @@ namespace Bot public GridClient grid { get; set; } public Logger Logger { get; set; } - public MessageHandler.MessageHandleEvent MHE; - public MessageHandler MH; public MainConfiguration ConfigurationHandle { get { @@ -47,5 +45,6 @@ namespace Bot public DateTime LaunchTime { get; set; } = DateTime.Now; public bool WaitForFiveMinutes = false; + public MessageService MSGSVC { get; set; } = new MessageService(); } } diff --git a/ChatLogger.cs b/ChatLogger.cs index 5fc77f2..73ad674 100644 --- a/ChatLogger.cs +++ b/ChatLogger.cs @@ -6,7 +6,7 @@ using System.Text; namespace Bot { - public sealed class ChatLogger + public sealed class ChatLogger : BaseCommands { private static readonly object writelock = new object(); private static ChatLogger inst = null; @@ -42,8 +42,8 @@ namespace Bot /// /// /// - [CommandGroup("log_chat", 5, 0, "log_chat - Toggles chat and IM logging", MessageHandler.Destinations.DEST_AGENT | MessageHandler.Destinations.DEST_LOCAL | MessageHandler.Destinations.DEST_CONSOLE_INFO)] - public void toggleChatLog(UUID client, int level, GridClient grid, string[] additionalArgs, MessageHandler.MessageHandleEvent MHE, MessageHandler.Destinations source, CommandRegistry registry, UUID agentKey, string agentName) + [CommandGroup("log_chat", 5, 0, "log_chat - Toggles chat and IM logging", Destinations.DEST_AGENT | Destinations.DEST_LOCAL )] + public void toggleChatLog(UUID client, int level, string[] additionalArgs, Destinations source, UUID agentKey, string agentName) { MHE(source, client, "Toggling"); diff --git a/CommandSystem/BaseCommands.cs b/CommandSystem/BaseCommands.cs new file mode 100644 index 0000000..e88ae2f --- /dev/null +++ b/CommandSystem/BaseCommands.cs @@ -0,0 +1,20 @@ +using OpenMetaverse; +using System; +using System.Collections.Generic; +using System.Text; + +namespace Bot.CommandSystem +{ + public class BaseCommands + { + + public void MHE(Destinations dest, UUID client, string msg) + { + MessageFactory.Post(dest, msg, client); + } + public static void MH(Destinations dest, UUID client, string msg) + { + MessageFactory.Post(dest, msg, client); + } + } +} diff --git a/CommandSystem/BaseHooks.cs b/CommandSystem/BaseHooks.cs index ee5b4d6..54ca143 100644 --- a/CommandSystem/BaseHooks.cs +++ b/CommandSystem/BaseHooks.cs @@ -10,7 +10,7 @@ using System.Text; namespace Bot.CommandSystem { - class BaseHooks + class BaseHooks : BaseCommands { [WebhookAttribs("/help")] @@ -94,28 +94,27 @@ namespace Bot.CommandSystem - [CommandGroup("show_level", 0, 0, "This command shows your current auth level if any.", MessageHandler.Destinations.DEST_AGENT | MessageHandler.Destinations.DEST_LOCAL | MessageHandler.Destinations.DEST_GROUP)] + [CommandGroup("show_level", 0, 0, "This command shows your current auth level if any.", Destinations.DEST_AGENT | Destinations.DEST_LOCAL | Destinations.DEST_GROUP)] public void show_level(UUID client, int level, GridClient grid, string[] additionalArgs, - MessageHandler.MessageHandleEvent MHE, MessageHandler.Destinations source, - CommandRegistry registry, UUID agentKey, string agentName) + Destinations source, + UUID agentKey, string agentName) { MHE(source, client, "Hi secondlife:///app/agent/" + agentKey.ToString() + "/about !! Your authorization level is " + level.ToString()); } - [CommandGroup("show_version", 0, 0, "Outputs the bot version", MessageHandler.Destinations.DEST_AGENT | MessageHandler.Destinations.DEST_LOCAL)] - public void show_version(UUID client, int level, GridClient grid, string[] additionalArgs, - MessageHandler.MessageHandleEvent MHE, MessageHandler.Destinations source, - CommandRegistry registry, UUID agentKey, string agentName) + [CommandGroup("show_version", 0, 0, "Outputs the bot version", Destinations.DEST_AGENT | Destinations.DEST_LOCAL)] + public void show_version(UUID client, int level, string[] additionalArgs, + Destinations source, + UUID agentKey, string agentName) { MHE(source, client, "Version " + ASMInfo.BotVer.ToString()); } - [CommandGroup("show_admins", 4, 0, "Outputs all admin users", MessageHandler.Destinations.DEST_AGENT | MessageHandler.Destinations.DEST_LOCAL)] - public void show_admins(UUID client, int level, GridClient grid, string[] additionalArgs, - MessageHandler.MessageHandleEvent MHE, MessageHandler.Destinations source, - CommandRegistry registry, UUID agentKey, string agentName) + [CommandGroup("show_admins", 4, 0, "Outputs all admin users", Destinations.DEST_AGENT | Destinations.DEST_LOCAL)] + public void show_admins(UUID client, int level, string[] additionalArgs, Destinations source, + UUID agentKey, string agentName) { for (int i = 0; i < MainConfiguration.Instance.BotAdmins.Count; i++) @@ -125,16 +124,16 @@ namespace Bot.CommandSystem } - [CommandGroup("terminate_bot", 5, 0, "", MessageHandler.Destinations.DEST_LOCAL | MessageHandler.Destinations.DEST_AGENT | MessageHandler.Destinations.DEST_CONSOLE_INFO | MessageHandler.Destinations.DEST_DISCORD)] - public void PerformExit(UUID client, int level, GridClient grid, string[] additionalArgs, MessageHandler.MessageHandleEvent MHE, MessageHandler.Destinations source, CommandRegistry registry, UUID agentKey, string agentName) + [CommandGroup("terminate_bot", 5, 0, "", Destinations.DEST_LOCAL | Destinations.DEST_AGENT | Destinations.DEST_DISCORD)] + public void PerformExit(UUID client, int level, string[] additionalArgs, Destinations source, UUID agentKey, string agentName) { MHE(source, client, "Bot exit initiated."); - MHE(MessageHandler.Destinations.DEST_ACTION, UUID.Zero, "{'type':'exit'}"); + BotSession.Instance.LaunchTime = new DateTime(); // zero out date time to force a relog } // !!help - [CommandGroup("!help", 1, 0, "Prints the entire help registry", MessageHandler.Destinations.DEST_AGENT | MessageHandler.Destinations.DEST_LOCAL | MessageHandler.Destinations.DEST_GROUP | MessageHandler.Destinations.DEST_CONSOLE_INFO)] - [CommandGroup("bot.help", 1, 0, "Alias to !help", MessageHandler.Destinations.DEST_AGENT | MessageHandler.Destinations.DEST_LOCAL | MessageHandler.Destinations.DEST_GROUP)] - public void PrintAllHelp(UUID client, int level, GridClient grid, string[] additionalArgs, MessageHandler.MessageHandleEvent MHE, MessageHandler.Destinations source, CommandRegistry registry, UUID agentKey, string agentName) + [CommandGroup("!help", 1, 0, "Prints the entire help registry", Destinations.DEST_AGENT |Destinations.DEST_LOCAL | Destinations.DEST_GROUP)] + [CommandGroup("bot.help", 1, 0, "Alias to !help", Destinations.DEST_AGENT | Destinations.DEST_LOCAL | Destinations.DEST_GROUP)] + public void PrintAllHelp(UUID client, int level, string[] additionalArgs, Destinations source, UUID agentKey, string agentName) { if (MainConfiguration.Instance.UseSSL) MHE(source, client, $"All commands viewable at: https://{MainConfiguration.Instance.WebServerIP}:{MainConfiguration.Instance.WebServerPort}/help"); @@ -142,10 +141,10 @@ namespace Bot.CommandSystem MHE(source, client, $"All commands viewable at: http://{MainConfiguration.Instance.WebServerIP}:{MainConfiguration.Instance.WebServerPort}/help"); } // !help "command" - [CommandGroup("help", 0, 1, "Prints help for one command", MessageHandler.Destinations.DEST_AGENT | MessageHandler.Destinations.DEST_LOCAL | MessageHandler.Destinations.DEST_GROUP | MessageHandler.Destinations.DEST_CONSOLE_INFO)] - public void PrintHelp(UUID client, int level, GridClient grid, string[] additionalArgs, MessageHandler.MessageHandleEvent MHE, MessageHandler.Destinations source, CommandRegistry registry, UUID agentKey, string agentName) + [CommandGroup("help", 0, 1, "Prints help for one command", Destinations.DEST_AGENT | Destinations.DEST_LOCAL | Destinations.DEST_GROUP )] + public void PrintHelp(UUID client, int level, string[] additionalArgs, Destinations source, UUID agentKey, string agentName) { - registry.PrintHelp(source, additionalArgs[0], client); + CommandRegistry.Instance.PrintHelp(source, additionalArgs[0], client); } } } diff --git a/CommandSystem/CommandGroup.cs b/CommandSystem/CommandGroup.cs index f686add..af25656 100644 --- a/CommandSystem/CommandGroup.cs +++ b/CommandSystem/CommandGroup.cs @@ -13,9 +13,9 @@ namespace Bot.CommandSystem public MethodInfo AssignedMethod; public int arguments = 0; public CommandHelp cmdUsage; - public MessageHandler.Destinations CommandSource; + public Destinations CommandSource; - public CommandGroup(string Command, int minLevel, int argCount, string HelpText, MessageHandler.Destinations SourceType) + public CommandGroup(string Command, int minLevel, int argCount, string HelpText, Destinations SourceType) { this.Command = Command; this.minLevel = minLevel; diff --git a/CommandSystem/CommandHelp.cs b/CommandSystem/CommandHelp.cs index d98e595..4ae3169 100644 --- a/CommandSystem/CommandHelp.cs +++ b/CommandSystem/CommandHelp.cs @@ -16,7 +16,7 @@ namespace Bot.CommandSystem public bool hasGroupFlag() { - if ((h.dests_allowed & MessageHandler.Destinations.DEST_GROUP) == MessageHandler.Destinations.DEST_GROUP) return true; + if ((h.dests_allowed & Destinations.DEST_GROUP) == Destinations.DEST_GROUP) return true; else return false; } @@ -28,7 +28,7 @@ namespace Bot.CommandSystem public int args; public string Text; public string sources; - public MessageHandler.Destinations dests_allowed; + public Destinations dests_allowed; } public string GetUsage() { @@ -39,14 +39,14 @@ namespace Bot.CommandSystem { return "Usage: " + h.Text; } - public CommandHelp(string CmdName, int minLevel, int argCount, string HelpText, MessageHandler.Destinations DESTS) + public CommandHelp(string CmdName, int minLevel, int argCount, string HelpText, Destinations DESTS) { h = new Help(); string Applicable = "Command can be used in ["; - if ((DESTS & MessageHandler.Destinations.DEST_LOCAL) == MessageHandler.Destinations.DEST_LOCAL) Applicable += "Local, "; - if ((DESTS & MessageHandler.Destinations.DEST_AGENT) == MessageHandler.Destinations.DEST_AGENT) Applicable += "IM, "; - if ((DESTS & MessageHandler.Destinations.DEST_GROUP) == MessageHandler.Destinations.DEST_GROUP) Applicable += "Group, "; - if ((DESTS & MessageHandler.Destinations.DEST_DISCORD) == MessageHandler.Destinations.DEST_DISCORD) Applicable += "Discord, "; + if ((DESTS & Destinations.DEST_LOCAL) == Destinations.DEST_LOCAL) Applicable += "Local, "; + if ((DESTS & Destinations.DEST_AGENT) == Destinations.DEST_AGENT) Applicable += "IM, "; + if ((DESTS & Destinations.DEST_GROUP) == Destinations.DEST_GROUP) Applicable += "Group, "; + if ((DESTS & Destinations.DEST_DISCORD) == Destinations.DEST_DISCORD) Applicable += "Discord, "; if (Applicable.Substring(Applicable.Length - 1, 1) == " ") Applicable = Applicable.Substring(0, Applicable.Length - 2) + "]"; diff --git a/CommandSystem/CommandManager.cs b/CommandSystem/CommandManager.cs index 666f077..9eeef55 100644 --- a/CommandSystem/CommandManager.cs +++ b/CommandSystem/CommandManager.cs @@ -22,9 +22,9 @@ namespace Bot.CommandSystem public GridClient cl; public Logger Log = BotSession.Instance.Logger; public string newReply; - public unsafe bool RunChatCommand(string cmdData, GridClient client, MessageHandler.MessageHandleEvent MHE, CommandRegistry registry) + public unsafe bool RunChatCommand(string cmdData) { - register = registry; + register = CommandRegistry.Instance; Dictionary BotAdmins = MainConfiguration.Instance.BotAdmins; dynamic parameters = JsonConvert.DeserializeObject(cmdData); string request = parameters.request; @@ -55,46 +55,41 @@ namespace Bot.CommandSystem } - cl = client; + cl = BotSession.Instance.grid; - MessageHandler.Destinations sourceLoc = new MessageHandler.Destinations(); - if (parameters.type == "chat") sourceLoc = MessageHandler.Destinations.DEST_LOCAL; - else if (parameters.type == "group") sourceLoc = MessageHandler.Destinations.DEST_GROUP; - else if (parameters.type == "im") sourceLoc = MessageHandler.Destinations.DEST_AGENT; - else if (parameters.type == "console") - { - userLevel = 5000; - sourceLoc = MessageHandler.Destinations.DEST_CONSOLE_INFO; - } - else sourceLoc = MessageHandler.Destinations.DEST_LOCAL; + Destinations sourceLoc = new Destinations(); + if (parameters.type == "chat") sourceLoc = Destinations.DEST_LOCAL; + else if (parameters.type == "group") sourceLoc = Destinations.DEST_GROUP; + else if (parameters.type == "im") sourceLoc = Destinations.DEST_AGENT; + else sourceLoc = Destinations.DEST_LOCAL; string agentName = parameters.fromName; - if(sourceLoc == MessageHandler.Destinations.DEST_LOCAL) + if(sourceLoc == Destinations.DEST_LOCAL) { GroupLog.Instance.WriteLogEntry(true, false, agentName, agentKey, request); - }else if (sourceLoc == MessageHandler.Destinations.DEST_AGENT) + }else if (sourceLoc == Destinations.DEST_AGENT) { GroupLog.Instance.WriteLogEntry(false, true, agentName, agentKey, request); } - if (sourceLoc == MessageHandler.Destinations.DEST_GROUP) + if (sourceLoc == Destinations.DEST_GROUP) { agentKey = fromID; fromID = sessID; // Initiate group log saver - string GroupName = client.Groups.GroupName2KeyCache[fromID]; + string GroupName = cl.Groups.GroupName2KeyCache[fromID]; GroupLog.Instance.WriteLogEntry(GroupName, "secondlife:///app/agent/" + agentKey.ToString() + "/about (" + agentName + ") : " + request); - if (agentKey == client.Self.AgentID) return false; + if (agentKey == cl.Self.AgentID) return false; } else { agentKey = fromID; - if (agentKey == client.Self.AgentID) return false; + if (agentKey == cl.Self.AgentID) return false; } if (request.Substring(0, 1) != "!") @@ -155,7 +150,7 @@ namespace Bot.CommandSystem try { - register.RunCommand(request, fromID, userLevel, MHE, sourceLoc, agentKey, agentName); + register.RunCommand(request, fromID, userLevel, sourceLoc, agentKey, agentName); } catch (Exception e) { @@ -164,17 +159,17 @@ namespace Bot.CommandSystem int i; int* ptr = &i; IntPtr addr = (IntPtr)ptr; - MHE(MessageHandler.Destinations.DEST_LOCAL, UUID.Zero, "Exception caught: [" + Msg + "]\n \n[STACK] " + e.StackTrace.Replace("ZNI", "")+"\nMemory Position: 0x"+addr.ToString("x")+"\nCommand: "+request+$"\nMisc Details: {fromID}, {userLevel}, {sourceLoc}, {agentKey}, {agentName}"); + MessageFactory.Post(Destinations.DEST_LOCAL, "Exception caught: [" + Msg + "]\n \n[STACK] " + e.StackTrace.Replace("ZNI", "") + "\nMemory Position: 0x" + addr.ToString("x") + "\nCommand: " + request + $"\nMisc Details: {fromID}, {userLevel}, {sourceLoc}, {agentKey}, {agentName}", UUID.Zero); + // do nothing here. } Log.info(log:"Leaving command parser"); return false; } - public CommandManager(Logger _Log, GridClient cl, MessageHandler.MessageHandleEvent MHE) + public CommandManager() { - this.cl = cl; - Log = _Log; + Log = BotSession.Instance.Logger; } } } diff --git a/CommandSystem/CommandRegistry.cs b/CommandSystem/CommandRegistry.cs index ec86a11..da92c83 100644 --- a/CommandSystem/CommandRegistry.cs +++ b/CommandSystem/CommandRegistry.cs @@ -37,7 +37,6 @@ namespace Bot.CommandSystem _instance.client = bs.grid; _instance.config = bs.ConfigurationHandle; _instance.Log = bs.Logger; - _instance.MHEx = bs.MHE; _instance.LocateCommands(); } return _instance; @@ -59,7 +58,6 @@ namespace Bot.CommandSystem public GridClient client; public Logger Log; public IConfig config; - public MessageHandler.MessageHandleEvent MHEx; public void LocateCommands() { try @@ -127,16 +125,17 @@ namespace Bot.CommandSystem } catch (ReflectionTypeLoadException e) { - MHEx(MessageHandler.Destinations.DEST_LOCAL, UUID.Zero, "FAILURE!!!\n \n[Assembly load failure]"); + MessageFactory.Post(Destinations.DEST_LOCAL, "FAILURE!!!\n\n[Assembly load failure]", UUID.Zero); foreach (Exception X in e.LoaderExceptions) { - MHEx(MessageHandler.Destinations.DEST_LOCAL, UUID.Zero, X.Message + "\n \nSTACK: " + X.StackTrace); + MessageFactory.Post(Destinations.DEST_LOCAL, X.Message + "\n \nSTACK: " + X.StackTrace, UUID.Zero); + } } } - public void PrintHelpAll(MessageHandler.Destinations dest, UUID uid) + public void PrintHelpAll(Destinations dest, UUID uid) { for (int i = 0; i < Cmds.Count; i++) @@ -146,7 +145,7 @@ namespace Bot.CommandSystem KeyValuePair kvp = Cmds.ElementAt(i); CommandHelp HE = kvp.Value.cmdUsage; - if (dest == MessageHandler.Destinations.DEST_GROUP) + if (dest == Destinations.DEST_GROUP) { if (!HE.hasGroupFlag()) { @@ -154,13 +153,14 @@ namespace Bot.CommandSystem } else { - MHEx(dest, uid, HE.GetUsage()); + MessageFactory.Post(dest, HE.GetUsage(), uid); + } } else { + MessageFactory.Post(dest, HE.GetUsage(), uid); - MHEx(dest, uid, HE.GetUsage()); } // MHEx(dest, uid, kvp.Value.cmdUsage.GetUsage()); @@ -168,30 +168,31 @@ namespace Bot.CommandSystem } } - public void PrintHelp(MessageHandler.Destinations dest, string cmd, UUID uid) + public void PrintHelp(Destinations dest, string cmd, UUID uid) { try { CommandHelp HE = Cmds[cmd].cmdUsage; - if (dest == MessageHandler.Destinations.DEST_GROUP) + if (dest == Destinations.DEST_GROUP) { if (!HE.hasGroupFlag()) { //return; // DO NOT SCHEDULE THIS HELP INFO FOR GROUP!!! } } - MHEx(dest, uid, Cmds[cmd].cmdUsage.GetUsage()); + MessageFactory.Post(dest, Cmds[cmd].cmdUsage.GetUsage(), uid); + } catch (Exception e) { - MHEx(dest, uid, "Error: Unrecognized command"); + MessageFactory.Post(dest, "Error: Unknown command", uid); + } } - public void RunCommand(string cmdString, UUID user, int level, MessageHandler.MessageHandleEvent MHE, MessageHandler.Destinations source, UUID agentKey, string agentName) + public void RunCommand(string cmdString, UUID user, int level, Destinations source, UUID agentKey, string agentName) { - MHEx = MHE; int pos = 0; string[] cmdStruct = cmdString.Split(' '); int IgnoreCount = 0; @@ -213,11 +214,11 @@ namespace Bot.CommandSystem { // Check that the destination is allowed. // If not then skip this command entirely - MessageHandler.Destinations dests = cgX.CommandSource; + Destinations dests = cgX.CommandSource; bool Allowed = false; - if ((dests & MessageHandler.Destinations.DEST_AGENT) == source) Allowed = true; - if ((dests & MessageHandler.Destinations.DEST_GROUP) == source) Allowed = true; - if ((dests & MessageHandler.Destinations.DEST_LOCAL) == source) Allowed = true; + if ((dests & Destinations.DEST_AGENT) == source) Allowed = true; + if ((dests & Destinations.DEST_GROUP) == source) Allowed = true; + if ((dests & Destinations.DEST_LOCAL) == source) Allowed = true; if (!Allowed) { @@ -235,10 +236,10 @@ namespace Bot.CommandSystem additionalArgs[i - 1] = cmdStruct[pos + i]; } pos++; - //(UUID client, int level, GridClient grid, string[] additionalArgs, - //MessageHandler.MessageHandleEvent MHE, MessageHandler.Destinations source, - //CommandRegistry registry, UUID agentKey, string agentName) - Thread CommandThread = new Thread(() => cgX.AssignedMethod.Invoke(ovj, new object[] { user, level, client, additionalArgs, MHE, source, this, agentKey, agentName })); + //(UUID client, int level, string[] additionalArgs, + //Destinations source, + //UUID agentKey, string agentName) + Thread CommandThread = new Thread(() => cgX.AssignedMethod.Invoke(ovj, new object[] { user, level, additionalArgs, source, agentKey, agentName })); CommandThread.Start(); } } diff --git a/GroupLog.cs b/GroupLog.cs index 1faa002..a5eff56 100644 --- a/GroupLog.cs +++ b/GroupLog.cs @@ -9,7 +9,7 @@ using System.Collections.Specialized; namespace Bot { - public sealed class GroupLog + public sealed class GroupLog : BaseCommands { private static readonly object _lock = new object(); @@ -80,10 +80,10 @@ namespace Bot private static readonly object _fileRead = new object(); [CommandGroupMaster("Logging")] - [CommandGroup("search_log", 5, 2, "search_log [groupName] [search_term] - Searches for the search term in all logs relating to the group name (Use a underscore to show where spaces are!). The search term may also include the pipe (|) delimiter to include more than 1 word.", Bot.MessageHandler.Destinations.DEST_AGENT | Bot.MessageHandler.Destinations.DEST_LOCAL | MessageHandler.Destinations.DEST_GROUP | MessageHandler.Destinations.DEST_DISCORD)] - public void search_log(UUID client, int level, GridClient grid, string[] additionalArgs, - MessageHandler.MessageHandleEvent MHE, MessageHandler.Destinations source, - CommandRegistry registry, UUID agentKey, string agentName) + [CommandGroup("search_log", 5, 2, "search_log [groupName] [search_term] - Searches for the search term in all logs relating to the group name (Use a underscore to show where spaces are!). The search term may also include the pipe (|) delimiter to include more than 1 word.", Destinations.DEST_AGENT | Destinations.DEST_LOCAL | Destinations.DEST_GROUP | Destinations.DEST_DISCORD)] + public void search_log(UUID client, int level, string[] additionalArgs, + Destinations source, + UUID agentKey, string agentName) { string GrpName = additionalArgs[0].Replace('_', ' '); string[] search = additionalArgs[1].Split('|'); diff --git a/IProgram.cs b/IProgram.cs index 537a851..a880a26 100644 --- a/IProgram.cs +++ b/IProgram.cs @@ -9,7 +9,7 @@ namespace Bot { public interface IProgram { - void run(GridClient client, MessageHandler MH, CommandSystem.CommandRegistry registry); // Define the run command since a thread needs a entry point + void run(); // Define the run command since a thread needs a entry point string getTick(); // Run every second to check for queued data. If queue exists, then it will be returned as a JSON string. // getTick can reply with data for the serializer for instance. diff --git a/Level System/Auth.cs b/Level System/Auth.cs index a05abe8..a21dade 100644 --- a/Level System/Auth.cs +++ b/Level System/Auth.cs @@ -13,13 +13,13 @@ using Bot.CommandSystem; namespace Bot { - class Auth + class Auth : BaseCommands { - [CommandGroup("auth_user", 5, 2, "Authorizes a user to have command access. Arguments are user (UUID), and Level (int)", MessageHandler.Destinations.DEST_AGENT | MessageHandler.Destinations.DEST_LOCAL)] - public void set_auth(UUID client, int level, GridClient grid, string[] additionalArgs, - MessageHandler.MessageHandleEvent MHE, MessageHandler.Destinations source, - CommandRegistry registry, UUID agentKey, string agentName) + [CommandGroup("auth_user", 5, 2, "Authorizes a user to have command access. Arguments are user (UUID), and Level (int)", Destinations.DEST_AGENT | Destinations.DEST_LOCAL)] + public void set_auth(UUID client, int level, string[] additionalArgs, + Destinations source, + UUID agentKey, string agentName) { MainConfiguration mem = MainConfiguration.Instance; BotSession.Instance.Logger.info(log:"Existing Admins: " + mem.BotAdmins.Count.ToString()); @@ -36,8 +36,8 @@ namespace Bot if (NewLevel <= 0) { mem.BotAdmins.Remove(user); - MHE(MessageHandler.Destinations.DEST_AGENT, user, "Your access to the main bot has been removed. You will still have access to any command that does not require a access level higher than 0"); - MHE(MessageHandler.Destinations.DEST_LOCAL, UUID.Zero, "Access Removed"); + MHE(Destinations.DEST_AGENT, user, "Your access to the main bot has been removed. You will still have access to any command that does not require a access level higher than 0"); + MHE(Destinations.DEST_LOCAL, UUID.Zero, "Access Removed"); mem.Save(); return; } @@ -53,7 +53,7 @@ namespace Bot mem.BotAdmins.Add(user, NewLevel); else mem.BotAdmins[user] = NewLevel; - MHE(MessageHandler.Destinations.DEST_AGENT, user, "You have been granted authorization level " + NewLevel.ToString()); + MHE(Destinations.DEST_AGENT, user, "You have been granted authorization level " + NewLevel.ToString()); MHE(source, UUID.Zero, "Authorized"); mem.Save(); diff --git a/MessageHandler.cs b/MessageHandler.cs index 5fc8c9c..26eb442 100644 --- a/MessageHandler.cs +++ b/MessageHandler.cs @@ -11,7 +11,178 @@ using System.Threading; namespace Bot { - public class MessageHandler + /// + /// Message stuff! + /// + [Flags] + public enum Destinations + { + DEST_AGENT = 1, + DEST_GROUP = 2, + DEST_LOCAL = 4, + //DEST_CONSOLE_INFO = 8, + //DEST_ACTION = 16, // DEPRECATED + DEST_DISCORD = 32 + }; + /// + /// Message stuffs + /// + public abstract class Message + { + public abstract Destinations GetMessageSource(); + public abstract string GetMessage(); + public abstract UUID GetSender(); + public abstract UUID GetTarget(); + public abstract string GetSenderName(); + public abstract int GetChannel(); + internal abstract void set(Destinations dest, string msg, UUID agentID,string senderName, int channel); + } + /// + /// IM, local, whatever + /// + public class ChatMessage : Message + { + private string Msg; + private Destinations dest; + private UUID sender; + private UUID target; + private string senderName; + private int Chn; + + public override UUID GetTarget() + { + return target; + } + + public override int GetChannel() + { + return Chn; + } + + public override string GetMessage() + { + return Msg; + } + + public override Destinations GetMessageSource() + { + return dest; + } + + public override UUID GetSender() + { + return sender; + } + + public override string GetSenderName() + { + return senderName; + } + + internal override void set(Destinations dest, string msg, UUID agentID,string senderName, int channel) + { + this.dest = dest; + Msg = msg; + sender = agentID; + this.senderName = senderName; + Chn = channel; + } + + public ChatMessage(UUID targetID) + { + target = targetID; + } + } + /// + /// Includes methods specific to the Group + /// + public class GroupMessage : ChatMessage + { + private UUID GroupID; + private string groupName; + public UUID GetGroupID() + { + return GroupID; + } + public string GetGroupName() + { + return groupName; + } + public GroupMessage(UUID ID) : base(ID) + { + GroupID = ID; + } + } + + + public class MessageFactory + { + + public static void Post(Destinations dest, string Msg, UUID destID, int chn = 0) + { + + Message m = null; + + switch (dest) + { + case Destinations.DEST_GROUP: + m = new GroupMessage(destID); + break; + case Destinations.DEST_DISCORD: + m = new ChatMessage(UUID.Zero); + break; + default: + m = new ChatMessage(destID); + break; + } + + m.set(dest, Msg, BotSession.Instance.grid.Self.AgentID, BotSession.Instance.grid.Self.Name, chn); + + MessageService.Dispatch(m); + } + } + + + /// + /// Basic messaging factory + /// + public class MessageService + { + public MessageService() + { + + } + + public static void Dispatch(Message M) + { + MessageEventArgs MEA = new MessageEventArgs(); + MEA.Timestamp = DateTime.Now; + MEA.Msg = M; + + BotSession.Instance.MSGSVC.OnMessageEvent(MEA); + } + + protected virtual void OnMessageEvent(MessageEventArgs e) + { + EventHandler handler = MessageEvent; + if (handler != null) + { + handler(this, e); + } + } + public event EventHandler MessageEvent; + } + + + public class MessageEventArgs : EventArgs + { + public DateTime Timestamp { get; set; } + public Message Msg { get; set; } + } + + + + public class MessageHandler_old // keep the old structure for now { private List MSGQueue = new List(); private List ActionQueue = new List(); @@ -20,17 +191,6 @@ namespace Bot private Logger Log = BotSession.Instance.Logger; - [Flags] - public enum Destinations - { - DEST_AGENT = 1, - DEST_GROUP = 2, - DEST_LOCAL = 4, - DEST_CONSOLE_INFO = 8, - DEST_ACTION = 16, - DEST_DISCORD = 32 - }; - public struct MessageQueuePacket { public Destinations Dest; @@ -50,24 +210,11 @@ namespace Bot public string Action; } - public delegate void MessageHandleEvent(MessageHandler.Destinations DType, UUID AgentOrSession, string MSG, int channel = 0); + public delegate void MessageHandleEvent(Destinations DType, UUID AgentOrSession, string MSG, int channel = 0); public volatile MessageHandleEvent callbacks; public void MessageHandle(Destinations DType, UUID AgentOrSession, string MSG, int channel = 0) { - if (DType == Destinations.DEST_ACTION) - { - if (MSG == "RESET_QUEUE") - { - ClearQueues(); - return; - } - ActionPacket PKT = new ActionPacket(); - PKT.Dest = DType; - PKT.ActionStr = MSG; - ActionQueue.Add(PKT); - return; - } - else if (DType == Destinations.DEST_DISCORD) + if (DType == Destinations.DEST_DISCORD) { DiscordAction DA = new DiscordAction(); DA.Action = MSG; @@ -101,10 +248,6 @@ namespace Bot { client.Self.InstantMessage(pkt.DestID, "[" + MSGQueue.Count.ToString() + "] " + pkt.Msg); } - else if (pkt.Dest == Destinations.DEST_CONSOLE_INFO) - { - Log.info(Restore:true, "[" + MSGQueue.Count.ToString() + "] " + pkt.Msg); - } else if (pkt.Dest == Destinations.DEST_GROUP) { if (client.Self.GroupChatSessions.ContainsKey(pkt.DestID)) diff --git a/NonCommands/NotCommand.cs b/NonCommands/NotCommand.cs index 567ca78..458fe4b 100644 --- a/NonCommands/NotCommand.cs +++ b/NonCommands/NotCommand.cs @@ -10,7 +10,7 @@ namespace Bot.NonCommands /// /// Defaults to all except action /// - public MessageHandler.Destinations SourceType = MessageHandler.Destinations.DEST_AGENT | MessageHandler.Destinations.DEST_CONSOLE_INFO | MessageHandler.Destinations.DEST_DISCORD | MessageHandler.Destinations.DEST_GROUP | MessageHandler.Destinations.DEST_LOCAL; + public Destinations SourceType = Destinations.DEST_AGENT | Destinations.DEST_DISCORD | Destinations.DEST_GROUP | Destinations.DEST_LOCAL; public NotCommand() { // Not Command, this just marks a class diff --git a/NonCommands/nCMD.cs b/NonCommands/nCMD.cs index c2e29b1..6afd3fd 100644 --- a/NonCommands/nCMD.cs +++ b/NonCommands/nCMD.cs @@ -9,6 +9,6 @@ namespace Bot.NonCommands { public interface nCMD { - public void handle(string text, UUID User, string agentName, MessageHandler.Destinations src, UUID originator); + public void handle(string text, UUID User, string agentName, Destinations src, UUID originator); } } diff --git a/NonCommands/nRegistry.cs b/NonCommands/nRegistry.cs index ba95ca4..a891df2 100644 --- a/NonCommands/nRegistry.cs +++ b/NonCommands/nRegistry.cs @@ -10,7 +10,7 @@ namespace Bot.NonCommands { public class nRegistry { - public static void Dispatch(string request, UUID agentKey, string agentName, MessageHandler.Destinations sourceLoc, UUID originator) + public static void Dispatch(string request, UUID agentKey, string agentName, Destinations sourceLoc, UUID originator) { foreach(Assembly a in AppDomain.CurrentDomain.GetAssemblies()) diff --git a/Program.cs b/Program.cs index 18b6983..0d11b5f 100644 --- a/Program.cs +++ b/Program.cs @@ -16,7 +16,7 @@ using System.Reflection; namespace Bot { - public class Program + public class Program : BaseCommands { public static Logger Log; public static string BotVer = ASMInfo.BotVer; @@ -25,7 +25,6 @@ namespace Bot public static SerialManager SM = new SerialManager(); public static GridClient client = new GridClient(); public static bool g_iIsRunning = true; - public static MessageHandler MH; public static CommandRegistry registry; public static List g_ZPrograms = new List(); public static CommandManager CM = null; @@ -33,16 +32,16 @@ namespace Bot static readonly object _CacheLock = new object(); //public static License LicenseKey; // Not to be used yet - public static void msg(MessageHandler.Destinations D, UUID x, string m) + public static void msg(Destinations D, UUID x, string m) { - MH.callbacks(D, x, m); + MessageFactory.Post(D, m, x); } public static void passArguments(string data) { - CM.RunChatCommand(data, client, MH.callbacks, registry); + CM.RunChatCommand(data); } public static unsafe void Main(string[] args) @@ -154,8 +153,9 @@ namespace Bot return; } */ - MH = new MessageHandler(); - MH.callbacks += MH.MessageHandle; + BotSession.Instance.MSGSVC.MessageEvent += MSGSVC_onChat; + BotSession.Instance.MSGSVC.MessageEvent += MSGSVC_onIM; + BotSession.Instance.MSGSVC.MessageEvent += MSGSVC_onGroupMessage; string fna = null; @@ -250,23 +250,22 @@ namespace Bot if (File.Exists("XUP")) { File.Delete("XUP"); - MH.callbacks(MessageHandler.Destinations.DEST_LOCAL, UUID.Zero, "Updated to version " + BotStr + " - "+BotVer.ToString()); + + MessageFactory.Post(Destinations.DEST_LOCAL, $"Updated to version {BotStr} - {BotVer}", UUID.Zero); } // Setup BotSession Singleton! BotSession.Instance.grid = client; BotSession.Instance.Logger = Log; - BotSession.Instance.MHE = MH.callbacks; - BotSession.Instance.MH = MH; Thread prompter = new Thread(() => { BotSession.Instance.Logger.DoPrompt(); }); prompter.Start(); - CM = new CommandManager(BotSession.Instance.Logger, client, MH.callbacks); - + CM = new CommandManager(); + MainConfiguration.Instance.Save(); // Flush the config, to update the file format g_ZPrograms = new List(); @@ -290,7 +289,7 @@ namespace Bot { Console.WriteLine("Plugin [" + prog.ProgramName + "] found (" + fi.FullName + ") loaded and activated"); - prog.run(client, MH, CommandRegistry.Instance); + prog.run(); g_ZPrograms.Add(prog); } } @@ -345,7 +344,8 @@ namespace Bot if (conf.ConfigFor == "Main") { - msg(MessageHandler.Destinations.DEST_LOCAL, UUID.Zero, "Alert: Main.json is not fully initialized. Setting default values"); + MessageFactory.Post(Destinations.DEST_LOCAL, "Alert: Main.json is not fully initialized. Setting default values", UUID.Zero); + conf.ConfigFor = "BOT"; conf.ConfigVersion = 1.0f; // data contains nothing at the moment. @@ -355,12 +355,11 @@ namespace Bot if (conf.ConfigFor == "BOT") { - msg(MessageHandler.Destinations.DEST_LOCAL, UUID.Zero, "Main.json has been created"); - msg(MessageHandler.Destinations.DEST_LOCAL, UUID.Zero, "Continuing with startup"); + MessageFactory.Post(Destinations.DEST_LOCAL, "Main.json has been created", UUID.Zero); } else { - msg(MessageHandler.Destinations.DEST_LOCAL, UUID.Zero, "Main.json does not contain all memory. FAILURE."); + MessageFactory.Post(Destinations.DEST_LOCAL, "Main.json is invalid. Cannot continue", UUID.Zero); g_iIsRunning = false; } } @@ -400,7 +399,7 @@ namespace Bot int i; int* ptr = &i; IntPtr addr = (IntPtr)ptr; - msg(MessageHandler.Destinations.DEST_LOCAL, UUID.Zero, "Generic Exception Caught: " + Msg + " [0x0A, 0x" + addr.ToString("x") + "]\nSTACK: " + STACK); + MessageFactory.Post(Destinations.DEST_LOCAL, "Generic Exception Caught: " + Msg + " [0x0A, 0x" + addr.ToString("x") + "]\nSTACK: " + STACK, UUID.Zero); } } @@ -410,46 +409,7 @@ namespace Bot } - - string jsonReply = MH.CheckActions(); - - - if (jsonReply == "NONE") jsonReply = ""; - - - if (jsonReply == "" || jsonReply == null) - { - //Log.debug("TICK NULL"); - - } - else - { - dynamic jsonObj = JsonConvert.DeserializeObject(jsonReply); - string tp = jsonObj.type; - switch (tp) - { - case "exit": - { - - Log.info(false, "Logging off!"); - g_iIsRunning = false; - break; - } - case "reload_groups": - { - ReloadGroupsCache(); - break; - } - default: - { - - Log.info(true, "Unknown response code"); - break; - } - } - } - - MH.run(client); + //MasterObjectCaches.Save(); if (startupSeq) startupSeq = false; @@ -491,11 +451,37 @@ namespace Bot //System.Console.WriteLine("PAUSING. PRESS ANY KEY TO EXIT"); //System.Console.ReadKey(); } + private static ManualResetEvent GroupJoinWaiter = new ManualResetEvent(false); + private static void MSGSVC_onGroupMessage(object sender, MessageEventArgs e) + { + throw new NotImplementedException(); + } + + private static void MSGSVC_onIM(object sender, MessageEventArgs e) + { + throw new NotImplementedException(); + } + + private static void MSGSVC_onChat(object sender, MessageEventArgs e) + { + switch (e.Msg.GetMessageSource()) + { + case Destinations.DEST_AGENT: + // send as IM + BotSession.Instance.grid.Self.InstantMessage(e.Msg.GetTarget(), e.Msg.GetMessage()); + break; + case Destinations.DEST_LOCAL: + BotSession.Instance.grid.Self.Chat(e.Msg.GetMessage(), e.Msg.GetChannel(), ChatType.Normal); + break; + default: + return; + } + } private static void onJoinGroupChat(object sender, GroupChatJoinedEventArgs e) { if (e.Success) - MH.GroupJoinWaiter.Set(); + GroupJoinWaiter.Set(); } private static AutoResetEvent ReqObjProperties = new AutoResetEvent(false); @@ -574,8 +560,8 @@ namespace Bot private ManualResetEvent profile_get = new ManualResetEvent(false); private Avatar.AvatarProperties Properties_AV; - [CommandGroup("set_profile_text", 75, 1, "set_profile_text [text:Base64] - Sets the profile text", MessageHandler.Destinations.DEST_AGENT | MessageHandler.Destinations.DEST_LOCAL | MessageHandler.Destinations.DEST_CONSOLE_INFO)] - public void setProfileText(UUID client, int level, GridClient grid, string[] additionalArgs, MessageHandler.MessageHandleEvent MHE, MessageHandler.Destinations source, CommandRegistry registry, UUID agentKey, string agentName) + [CommandGroup("set_profile_text", 75, 1, "set_profile_text [text:Base64] - Sets the profile text", Destinations.DEST_AGENT | Destinations.DEST_LOCAL)] + public void setProfileText(UUID client, int level, string[] additionalArgs, Destinations source, UUID agentKey, string agentName) { MHE(source, client, "Setting..."); @@ -707,7 +693,7 @@ namespace Bot else { client.Self.GroupInviteRespond(e.IM.FromAgentID, e.IM.IMSessionID, false); - MH.callbacks(MessageHandler.Destinations.DEST_AGENT, e.IM.FromAgentID, "You lack the proper permissions to perform this action"); + MH(Destinations.DEST_AGENT, e.IM.FromAgentID, "You lack the proper permissions to perform this action"); } } else if (e.IM.Dialog == InstantMessageDialog.FriendshipOffered) @@ -715,11 +701,11 @@ namespace Bot if (Level >= 4) { client.Friends.AcceptFriendship(e.IM.FromAgentID, e.IM.IMSessionID); - MH.callbacks(MessageHandler.Destinations.DEST_AGENT, e.IM.FromAgentID, "Welcome to my friends list!"); + MH(Destinations.DEST_AGENT, e.IM.FromAgentID, "Welcome to my friends list!"); } else { - MH.callbacks(MessageHandler.Destinations.DEST_AGENT, e.IM.FromAgentID, "You lack proper permission"); + MH(Destinations.DEST_AGENT, e.IM.FromAgentID, "You lack proper permission"); } } else if (e.IM.Dialog == InstantMessageDialog.RequestTeleport) @@ -727,12 +713,12 @@ namespace Bot if (Level >= 3) { client.Self.TeleportLureRespond(e.IM.FromAgentID, e.IM.IMSessionID, true); - MH.callbacks(MessageHandler.Destinations.DEST_AGENT, e.IM.FromAgentID, "Teleporting..."); + MH(Destinations.DEST_AGENT, e.IM.FromAgentID, "Teleporting..."); } else { client.Self.TeleportLureRespond(e.IM.FromAgentID, e.IM.IMSessionID, false); - MH.callbacks(MessageHandler.Destinations.DEST_AGENT, e.IM.FromAgentID, "You lack permission"); + MH(Destinations.DEST_AGENT, e.IM.FromAgentID, "You lack permission"); } } else if (e.IM.Dialog == InstantMessageDialog.MessageFromObject) @@ -842,14 +828,12 @@ namespace Bot if(count >= 5) { - MH.callbacks(MessageHandler.Destinations.DEST_LOCAL, UUID.Zero, "Aborting group refresh attempt. Too many errors - Resetting cache and retrying"); + MH(Destinations.DEST_LOCAL, UUID.Zero, "Aborting group refresh attempt. Too many errors - Resetting cache and retrying"); GroupsEvent.Reset(); GroupsCache = new Dictionary(); client.Groups.CurrentGroups -= Groups_CurrentGroups; - Dictionary act = new Dictionary(); - act.Add("type", "reload_groups"); - MH.callbacks(MessageHandler.Destinations.DEST_ACTION, UUID.Zero, JsonConvert.SerializeObject(act)); + ReloadGroupsCache(); return; } diff --git a/WebHookServer/HookCmds.cs b/WebHookServer/HookCmds.cs index 79da196..27be0d9 100644 --- a/WebHookServer/HookCmds.cs +++ b/WebHookServer/HookCmds.cs @@ -8,7 +8,7 @@ using System.Text; namespace Bot.WebHookServer { - class HookCmds + class HookCmds : BaseCommands { public HttpListener listener; @@ -58,12 +58,13 @@ namespace Bot.WebHookServer } - [CommandGroup("webhook_auth", 4, 2, "webhook_auth [github_name] [y/n]", MessageHandler.Destinations.DEST_AGENT | MessageHandler.Destinations.DEST_LOCAL | MessageHandler.Destinations.DEST_GROUP)] - public void WebHookAuthMgr(UUID client, int level, GridClient grid, string[] additionalArgs, MessageHandler.MessageHandleEvent MHE, MessageHandler.Destinations source, CommandRegistry registry, UUID agentKey, string agentName) + [CommandGroup("webhook_auth", 4, 2, "webhook_auth [github_name] [y/n]", Destinations.DEST_AGENT | Destinations.DEST_LOCAL | Destinations.DEST_GROUP)] + public void WebHookAuthMgr(UUID client, int level, string[] additionalArgs, Destinations source, UUID agentKey, string agentName) { MainConfiguration cfg = MainConfiguration.Instance; MHE(source, client, "Checking.."); + if (cfg.Authed(additionalArgs[0])) { diff --git a/WebHookServer/WebHookServer.cs b/WebHookServer/WebHookServer.cs index e008e89..4c79c8d 100644 --- a/WebHookServer/WebHookServer.cs +++ b/WebHookServer/WebHookServer.cs @@ -25,7 +25,6 @@ namespace Bot.WebHookServer class GitServer : IProgram { public HttpListener listener; - public MessageHandler.MessageHandleEvent MHEx; public string ProgramName { get { return "GitServer"; } @@ -33,7 +32,7 @@ namespace Bot.WebHookServer public float ProgramVersion { - get { return 1.6f; } + get { return 1.7f; } } public string getTick() @@ -55,7 +54,7 @@ namespace Bot.WebHookServer public void onIMEvent(object sender, InstantMessageEventArgs e) { } - public void run(GridClient client, MessageHandler MH, CommandRegistry registry) + public void run() { if (listener != null) return;// Already had run triggered try @@ -79,7 +78,6 @@ namespace Bot.WebHookServer listener.Prefixes.Add($"http://*:{MainConfiguration.Instance.WebServerPort}/"); - MHEx = MH.callbacks; listener.Start(); var hc = new HookCmds(); @@ -91,7 +89,8 @@ namespace Bot.WebHookServer }catch(Exception e) { - BotSession.Instance.MHE(MessageHandler.Destinations.DEST_LOCAL, UUID.Zero, "Error: Program could not escalate to Admin Privileges. WebHook engine not running\n\n"+e.Message+"\n"+e.StackTrace); + MessageFactory.Post(Destinations.DEST_LOCAL, "Error: Program could not escalate to Admin Privileges. WebHook engine not running\n\n" + e.Message + "\n" + e.StackTrace, UUID.Zero); + } }