public virtual object Execute(ExecutionInformation info, IReadOnlyList <ICommand> arguments, IReadOnlyList <Type> returnTypes)
        {
            // Make arguments lazy, we only want to execute them once
            arguments = arguments.Select(c => new LazyCommand(c)).ToArray();

            CommandException contextException = null;

            foreach (var f in Functions)
            {
                // Try to call each overload
                try
                {
                    return(f.Execute(info, arguments, returnTypes));
                }
                catch (CommandException cmdEx)
                    when(cmdEx.Reason == CommandExceptionReason.MissingParameter ||
                         cmdEx.Reason == CommandExceptionReason.MissingContext ||
                         cmdEx.Reason == CommandExceptionReason.NoReturnMatch)
                    {
                        // When we encounter a missing module problem we store it for later, as it is more helpful
                        // im most cases to know that some commands *could* have matched if the module were there.
                        if (cmdEx.Reason == CommandExceptionReason.MissingContext)
                        {
                            contextException = cmdEx;
                        }
                    }
            }
            if (contextException != null)
            {
                System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(contextException).Throw();
            }
            throw new CommandException(strings.error_cmd_no_matching_overload, CommandExceptionReason.MissingParameter);
        }
Example #2
0
        public bool HasAllRights(ExecutionInformation info, params string[] requestedRights)
        {
            var ctx = GetRightsContext(info);
            var normalizedRequest = ExpandRights(requestedRights, registeredRights);

            return(ctx.DeclAdd.IsSupersetOf(normalizedRequest));
        }
Example #3
0
 public virtual ICommandResult Execute(ExecutionInformation info, IReadOnlyList <ICommand> arguments, IReadOnlyList <CommandResultType> returnTypes)
 {
     // Make arguments lazy, we only want to execute them once
     arguments = arguments.Select(c => new LazyCommand(c)).ToArray();
     foreach (var f in Functions)
     {
         bool fits = false;
         try
         {
             // Find out if this overload works
             f.FitArguments(info, arguments, returnTypes, out var _);
             fits = true;
         }
         catch (CommandException)
         {
             // Do nothing, just move on to the next function
         }
         if (fits)
         {
             // Call this overload
             return(f.Execute(info, arguments, returnTypes));
         }
     }
     throw new CommandException("No matching function overload could be found", CommandExceptionReason.FunctionNotFound);
 }
Example #4
0
        public string[] GetRightsSubset(ExecutionInformation info, params string[] requestedRights)
        {
            var ctx = GetRightsContext(info);
            var normalizedRequest = ExpandRights(requestedRights, registeredRights);

            return(ctx.DeclAdd.Intersect(normalizedRequest).ToArray());
        }
Example #5
0
        private void Execute(MetadataBuilder builder, DbConnection connection, string method, IParam[] parameters,
                             Func <ExecutionInformation, string> beforeQuery = null,
                             Func <ExecutionInformation, AdditionalInformation> beforeEnd = null)
        {
            _Logger?.LogInformation("Executing {method}", method);

            LoadObjectParametersMetadata(builder, parameters);

            var info    = new ExecutionInformation();
            var declare = ProcessDeclaration(parameters);
            var body    = ProcessBody(parameters, info);

            var query = new StringBuilder(beforeQuery?.Invoke(info));

            query.AppendLine(ProcessQuery(method, parameters, info));

            var outparameters = ProcessOutputParameters(parameters, info);

            var additionalInfo = beforeEnd?.Invoke(info);

            if (additionalInfo != null)
            {
                declare.AppendLine(additionalInfo.Declare);
                outparameters.AppendLine(additionalInfo.Output);
            }

            var execute = PrepareStatement(declare.ToString(), body, query.ToString(), outparameters.ToString());

            ExecuteNonQuery(connection, info.OracleParameterList, execute);

            ProcessOutParameters(info.Outputs);
        }
Example #6
0
        private OracleParameter FunctionReturnOracleParameter <T>(ExecutionInformation info, MetadataBase metadata)
        {
            OracleParameter retOra;
            var             type = typeof(T);

            if (type.IsBoolean())
            {
                retOra = new OracleParameter
                {
                    ParameterName = $":{info.ParameterCounter}",
                    OracleDbType  = OracleDbType.Byte,
                    Direction     = ParameterDirection.Output
                };
            }
            else if (type.IsClrType())
            {
                retOra = _Common.GetOracleParameter(
                    type: type, direction: ParameterDirection.Output, name: $":{info.ParameterCounter++}", value: DBNull.Value);
            }
            else
            {
                retOra = new OracleParameter($":{info.ParameterCounter}", DBNull.Value)
                {
                    OracleDbType = OracleDbType.RefCursor
                };
            }

            info.OracleParameterList.Add(retOra);
            return(retOra);
        }
Example #7
0
        private static bool ResponseYoutube(ExecutionInformation info)
        {
            string[] command = info.TextMessage.Message.SplitNoEmpty(' ');
            if (command[0] != "!f")
            {
                return(false);
            }
            if (command.Length != 2)
            {
                return(true);
            }
            int entry;

            if (int.TryParse(command[1], out entry))
            {
                PlayData data = info.Session.UserResource;
                if (data == null || data.Resource as YoutubeResource == null)
                {
                    info.Session.Write("An unexpected error with the ytresource occured: null.");
                    return(true);
                }
                YoutubeResource ytResource = (YoutubeResource)data.Resource;
                if (entry < 0 || entry >= ytResource.AvailableTypes.Count)
                {
                    return(true);
                }
                ytResource.Selected = entry;
                if (ValidateMedia(info.Session, ytResource))
                {
                    info.Session.Bot.FactoryManager.Play(data);
                }
            }
            return(true);
        }
Example #8
0
        private ExecutionInformation CreateExecInfo(InvokerData invoker = null, UserSession session = null)
        {
            var info = new ExecutionInformation(Injector.CloneRealm <DependencyRealm>());

            info.AddDynamicObject(invoker ?? InvokerData.Anonymous);
            info.AddDynamicObject(session ?? new AnonymousSession());
            return(info);
        }
        public virtual ICommandResult Execute(ExecutionInformation info, IReadOnlyList <ICommand> arguments, IReadOnlyList <CommandResultType> returnTypes)
        {
            var merged = new ICommand[internArguments.Count + arguments.Count];

            internArguments.CopyTo(0, merged, 0);
            arguments.CopyTo(0, merged, internArguments.Count);
            return(internCommand.Execute(info, merged, returnTypes));
        }
Example #10
0
 public void CommandSilentCmd(ExecutionInformation info, string cmd, params string[] cmdpara)
 {
     try {
         var result = lib.Send <TS3Client.Messages.ResponseDictionary>(cmd,
                                                                       cmdpara.Select(x => x.Split(new[] { '=' }, 2)).Select(x => new CommandParameter(x[0], x[1])).Cast <ICommandPart>().ToList());
         PluginLog(Log.Level.Info, string.Join("\n", result.Select(x => string.Join(", ", x.Select(kvp => kvp.Key + "=" + kvp.Value)))));
     } catch (TS3Client.Ts3CommandException ex) { throw new CommandException(ex.Message, CommandExceptionReason.CommandError); }
 }
Example #11
0
        public virtual async ValueTask <object?> Execute(ExecutionInformation info, IReadOnlyList <ICommand> arguments)
        {
            var merged = new ICommand[internArguments.Count + arguments.Count];

            internArguments.CopyTo(0, merged, 0);
            arguments.CopyTo(0, merged, internArguments.Count);
            return(await internCommand.Execute(info, merged));
        }
Example #12
0
 public virtual ICommandResult Execute(ExecutionInformation info, IReadOnlyList <ICommand> arguments, IReadOnlyList <CommandResultType> returnTypes)
 {
     if (tailContent != null)
     {
         return(new TailStringCommandResult(content, tailContent));
     }
     return(new StringCommandResult(content));
 }
Example #13
0
        private void CallScript(ExecutionInformation info, string command, bool answer, bool skipRights)
        {
            Log.Debug("Calling script (skipRights:{0}, answer:{1}): {2}", skipRights, answer, command);

            info.AddDynamicObject(new CallerInfo(command, false)
            {
                SkipRightsChecks = skipRights
            });

            try
            {
                // parse (and execute) the command
                var res = CommandManager.CommandSystem.Execute(info, command);

                if (!answer)
                {
                    return;
                }

                // Write result to user
                switch (res.ResultType)
                {
                case CommandResultType.String:
                    var sRes = (StringCommandResult)res;
                    if (!string.IsNullOrEmpty(sRes.Content))
                    {
                        info.Write(sRes.Content).UnwrapToLog(Log);
                    }
                    break;

                case CommandResultType.Empty:
                    break;

                default:
                    Log.Warn("Got result which is not a string/empty. Result: {0}", res.ToString());
                    break;
                }
            }
            catch (CommandException ex)
            {
                Log.Debug(ex, "Command Error ({0})", ex.Message);
                if (answer)
                {
                    info.Write(TextMod.Format(config.Commands.Color, strings.error_call_error.Mod().Color(Color.Red).Bold(), ex.Message))
                    .UnwrapToLog(Log);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Unexpected command error: {0}", ex.UnrollException());
                if (answer)
                {
                    info.Write(TextMod.Format(config.Commands.Color, strings.error_call_unexpected_error.Mod().Color(Color.Red).Bold(), ex.Message))
                    .UnwrapToLog(Log);
                }
            }
        }
Example #14
0
        string CallCommand(string command)
        {
            var info = new ExecutionInformation(null, new InvokerData("InvokerUid"), null)
            {
                SkipRightsChecks = true
            };

            return(bot.CommandManager.CommandSystem.ExecuteCommand(info, command));
        }
Example #15
0
 public virtual object Execute(ExecutionInformation info, IReadOnlyList <ICommand> arguments, IReadOnlyList <Type> returnTypes)
 {
     if (!ResultHelper.IsValidResult(Content, returnTypes))
     {
         Log.Debug("Failed to return {0} ({1})", Content.GetType(), Content);
         throw new CommandException(strings.error_cmd_no_matching_overload, CommandExceptionReason.NoReturnMatch);
     }
     return(Content);
 }
Example #16
0
        private void ProcessApiV1Call(Uri uri, HttpListenerResponse response, InvokerData invoker)
        {
            string apirequest = uri.OriginalString.Substring(uri.GetLeftPart(UriPartial.Authority).Length + "/api".Length);
            var    ast        = CommandParser.ParseCommandRequest(apirequest, '/', '/');

            UnescapeAstTree(ast);
            Log.Trace(ast.ToString);

            var command = CommandManager.CommandSystem.AstToCommandResult(ast);

            var execInfo = new ExecutionInformation(CoreInjector.CloneRealm <CoreInjector>());

            execInfo.AddDynamicObject(new CallerInfo(apirequest, true));
            execInfo.AddDynamicObject(invoker);
            // todo creating token usersessions is now possible

            try
            {
                var res = command.Execute(execInfo, Array.Empty <ICommand>(), XCommandSystem.ReturnJsonOrNothing);

                if (res.ResultType == CommandResultType.Empty)
                {
                    response.StatusCode = (int)HttpStatusCode.NoContent;
                }
                else if (res.ResultType == CommandResultType.Json)
                {
                    response.StatusCode = (int)HttpStatusCode.OK;
                    var returnJson   = (JsonCommandResult)res;
                    var returnString = returnJson.JsonObject.Serialize();
                    using (var responseStream = new StreamWriter(response.OutputStream))
                        responseStream.Write(returnString);
                }
            }
            catch (CommandException ex)
            {
                try { ReturnError(ex, response); }
                catch (Exception htex) { Log.Error(htex, "Failed to respond to HTTP request."); }
            }
            catch (Exception ex)
            {
                if (ex is NotImplementedException)
                {
                    response.StatusCode = (int)HttpStatusCode.NotImplemented;
                }
                else
                {
                    response.StatusCode = (int)HttpStatusCode.InternalServerError;
                }
                Log.Error(ex, "Unexpected command error");
                try
                {
                    using (var responseStream = new StreamWriter(response.OutputStream))
                        responseStream.Write(new JsonError(ex.Message, CommandExceptionReason.Unknown).Serialize());
                }
                catch (Exception htex) { Log.Error(htex, "Failed to respond to HTTP request."); }
            }
        }
Example #17
0
 static Utils()
 {
     ExecInfo = new ExecutionInformation();
     ExecInfo.AddDynamicObject(new CallerInfo(null, false)
     {
         SkipRightsChecks = true
     });
     ExecInfo.AddDynamicObject(new InvokerData("InvokerUid"));
 }
Example #18
0
 public override (Func <string> action, bool removeOnResourceEnd) Create(
     ExecutionInformation info, string command, string args)
 {
     if (!string.IsNullOrWhiteSpace(args) && !int.TryParse(args, out _))
     {
         throw new CommandException("Skip expects no parameters or a number.",
                                    CommandExceptionReason.CommandError);
     }
     return(() => ExecuteCommandWithArgs(info, command, args), true);
 }
Example #19
0
        public virtual async ValueTask <object?> Execute(ExecutionInformation info, IReadOnlyList <ICommand> arguments)
        {
            if (!executed)
            {
                result = await innerCommand.Execute(info, arguments);

                executed = true;
                return(result);
            }
            return(result);
        }
Example #20
0
 private void CallScript(string script, InvokerData invoker)
 {
     try
     {
         var info = new ExecutionInformation(parent, invoker, null)
         {
             SkipRightsChecks = true
         };
         CommandManager.CommandSystem.Execute(info, script);
     }
     catch (CommandException) { }
 }
Example #21
0
        public virtual object Execute(ExecutionInformation info, IReadOnlyList <ICommand> arguments, IReadOnlyList <Type> returnTypes)
        {
            var merged = new ICommand[internArguments.Count + arguments.Count];

            internArguments.CopyTo(0, merged, 0);
            arguments.CopyTo(0, merged, internArguments.Count);
            if (!info.TryGet <CommandManager>(out var cmdSys))
            {
                throw new CommandException("Could not find local commandsystem tree", CommandExceptionReason.MissingContext);
            }
            return(cmdSys.RootGroup.Execute(info, merged, returnTypes));
        }
Example #22
0
        private AdditionalInformation ReturnValueAdditionalInformationBoolean <T>(ExecutionInformation info,
                                                                                  MetadataOracleBoolean metadata, out OracleParameter parameter)
        {
            parameter = FunctionReturnOracleParameter <T>(info, metadata);
            var name = "ret";

            return(new AdditionalInformation
            {
                Declare = metadata.GetDeclareLine(name),
                Output = metadata.OutputString(info.ParameterCounter, name)
            });
        }
Example #23
0
        private void ProcessApiV1Call(UriExt uri, HttpListenerResponse response, UserSession session)
        {
            string apirequest = uri.AbsolutePath.Substring("/api".Length);
            var    ast        = CommandParser.ParseCommandRequest(apirequest, '/', '/');

            UnescapeAstTree(ast);

            var command = MainBot.CommandManager.CommandSystem.AstToCommandResult(ast);

            var execInfo = new ExecutionInformation(session, null)
            {
                ApiCall = true
            };

            using (var token = execInfo.Session.GetLock())
            {
                try
                {
                    var res = command.Execute(execInfo, Enumerable.Empty <ICommand>(),
                                              new[] { CommandResultType.Json, CommandResultType.Empty });

                    if (res.ResultType == CommandResultType.Empty)
                    {
                        response.StatusCode = (int)HttpStatusCode.NoContent;
                    }
                    else if (res.ResultType == CommandResultType.Json)
                    {
                        response.StatusCode = (int)HttpStatusCode.OK;
                        var sRes = (JsonCommandResult)res;
                        using (var responseStream = new StreamWriter(response.OutputStream))
                            responseStream.Write(sRes.JsonObject.Serialize());
                    }
                }
                catch (CommandException ex)
                {
                    ReturnError(ex, response);
                }
                catch (Exception ex)
                {
                    if (ex is NotImplementedException)
                    {
                        response.StatusCode = (int)HttpStatusCode.NotImplemented;
                    }
                    else
                    {
                        response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    }
                    Log.Write(Log.Level.Error, "WA Unexpected command error: {0}", ex);
                    using (var responseStream = new StreamWriter(response.OutputStream))
                        responseStream.Write(new JsonError(ex.Message, CommandExceptionReason.Unknown).Serialize());
                }
            }
        }
Example #24
0
        private void CallScript(ExecutionInformation info, string command, bool answer, bool skipRights)
        {
            Log.Debug("Calling script (skipRights:{0}, answer:{1}): {2}", skipRights, answer, command);

            info.AddDynamicObject(new CallerInfo(command, false)
            {
                SkipRightsChecks = skipRights
            });

            try
            {
                // parse (and execute) the command
                var res = CommandManager.CommandSystem.Execute(info, command);

                if (!answer)
                {
                    return;
                }

                // Write result to user
                if (res.ResultType == CommandResultType.String)
                {
                    var sRes = (StringCommandResult)res;
                    if (!string.IsNullOrEmpty(sRes.Content))
                    {
                        info.Write(sRes.Content).UnwrapThrow();
                    }
                }
                else if (res.ResultType == CommandResultType.Json)
                {
                    var sRes = (JsonCommandResult)res;
                    info.Write("\nJson str: \n" + sRes.JsonObject).UnwrapThrow();
                    info.Write("\nJson val: \n" + sRes.JsonObject.Serialize()).UnwrapThrow();
                }
            }
            catch (CommandException ex)
            {
                Log.Debug(ex, "Command Error ({0})", ex.Message);
                if (answer)
                {
                    info.Write(string.Format(strings.error_call_error, ex.Message));                         // XXX check return
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Unexpected command error: {0}", ex.UnrollException());
                if (answer)
                {
                    info.Write(string.Format(strings.error_call_unexpected_error, ex.Message));                         // XXX check return
                }
            }
        }
Example #25
0
            public string PropagiateLoad(ExecutionInformation info, string parameter)
            {
                var result = info.Session.Bot.PlaylistManager.LoadPlaylistFrom(parameter, audioType);

                if (!result)
                {
                    return(result);
                }

                result.Value.CreatorDbId = info.Session.Client.DatabaseId;
                info.Session.Set <PlaylistManager, Playlist>(result.Value);
                return("Ok");
            }
Example #26
0
        public static ExecutionInformation GetExecInfo(string matcher)
        {
            var execInfo = new ExecutionInformation();

            execInfo.AddModule(new CallerInfo(false)
            {
                SkipRightsChecks = true, CommandComplexityMax = int.MaxValue
            });
            execInfo.AddModule(new InvokerData((Uid)"InvokerUid"));
            execInfo.AddModule(Filter.GetFilterByName(matcher));
            execInfo.AddModule(cmdMgr);
            return(execInfo);
        }
Example #27
0
        private ExecutionInformation CreateExecInfo(InvokerData invoker = null, UserSession session = null)
        {
            var info = new ExecutionInformation(Injector.CloneRealm <DependencyRealm>());

            if (invoker != null)
            {
                info.AddDynamicObject(invoker);
            }
            if (session != null)
            {
                info.AddDynamicObject(session);
            }
            return(info);
        }
        public string GetCommandLineArguments(ExecutionInformation executionInformation)
        {
            string ToArgument(Parameter param)
            {
                var prefix = param.Name.Length > 1 ? "--" : "-";
                var value  = GetArgumentValueString(param, executionInformation.ArgumentValues[param.Name]);

                return($"{prefix}{param.Name} {value}");
            }

            var parameters = executionInformation.EntryPoint.Parameters.OrderBy(param => param.Position);

            return(string.Join(" ", parameters.Select(ToArgument)));
        }
Example #29
0
        public static string ExecuteCommandWithArgs(ExecutionInformation info, string command, string args)
        {
            StringBuilder builder = new StringBuilder();

            builder.Append("!").Append(command);
            if (args != null)
            {
                builder.Append(' ').Append(args);
            }
            string cmd = builder.ToString();

            Log.Info($"Vote succeeded, executing command: {cmd}");
            return(CommandManager.ExecuteCommand(info, cmd));
        }
Example #30
0
 public virtual ICommandResult Execute(ExecutionInformation info, IReadOnlyList <ICommand> arguments, IReadOnlyList <CommandResultType> returnTypes)
 {
     if (result is null)
     {
         result = innerCommand.Execute(info, arguments, returnTypes);
         return(result);
     }
     // Check if we can return that type
     if (!returnTypes.Contains(result.ResultType))
     {
         throw new CommandException("The cached result can't be returned", CommandExceptionReason.NoReturnMatch);
     }
     return(result);
 }
Example #31
0
		public string CommandQuit(ExecutionInformation info)
		{
			info.Session.SetResponse(ResponseQuit, null);
			return "Do you really want to quit? !(yes|no)";
		}
Example #32
0
		public string CommandPlay(ExecutionInformation info, string parameter)
		{
			if (string.IsNullOrEmpty(parameter))
			{
				AudioFramework.Pause = false;
				return null;
			}
			else
			{
				ClientData client = QueryConnection.GetClientById(info.TextMessage.InvokerId);
				return FactoryManager.LoadAndPlay(new PlayData(info.Session, client, parameter, false));
			}
		}
Example #33
0
		private bool ResponseHistoryClean(ExecutionInformation info)
		{
			Answer answer = TextUtil.GetAnswer(info.TextMessage.Message);
			if (answer == Answer.Yes)
			{
				if (info.IsAdmin.Value)
				{
					HistoryManager.CleanHistoryFile();
					info.Session.Write("Cleanup done!");
				}
				else
					info.Session.Write("Command can only be answered by an admin.");
			}
			return answer != Answer.Unknown;
		}
Example #34
0
		public string CommandVolume(ExecutionInformation info, string parameter)
		{
			bool relPos = parameter.StartsWith("+");
			bool relNeg = parameter.StartsWith("-");
			string numberString = (relPos || relNeg) ? parameter.Remove(0, 1) : parameter;

			int volume;
			if (!int.TryParse(numberString, out volume))
				return CommandHelp(info, "volume");

			int newVolume;
			if (relPos) newVolume = AudioFramework.Volume + volume;
			else if (relNeg) newVolume = AudioFramework.Volume - volume;
			else newVolume = volume;

			if (newVolume < 0 || newVolume > AudioFramework.MaxVolume)
				return "The volume level must be between 0 and " + AudioFramework.MaxVolume;

			if (newVolume <= AudioFramework.MaxUserVolume || newVolume < AudioFramework.Volume)
				AudioFramework.Volume = newVolume;
			else if (newVolume <= AudioFramework.MaxVolume)
			{
				info.Session.SetResponse(ResponseVolume, newVolume);
				return "Careful you are requesting a very high volume! Do you want to apply this? !(yes|no)";
			}
			return null;
		}
Example #35
0
		public string CommandTwitch(ExecutionInformation info, string parameter)
		{
			ClientData client = QueryConnection.GetClientById(info.TextMessage.InvokerId);
			return FactoryManager.LoadAndPlay(AudioType.Twitch, new PlayData(info.Session, client, parameter, false));
		}
Example #36
0
		private bool ResponseQuit(ExecutionInformation info)
		{
			Answer answer = TextUtil.GetAnswer(info.TextMessage.Message);
			if (answer == Answer.Yes)
			{
				if (info.IsAdmin.Value)
					CommandQuitForce(info);
				else
					info.Session.Write("Command can only be answered by an admin.");
			}
			return answer != Answer.Unknown;
		}
Example #37
0
		public string CommandQuiz(ExecutionInformation info, string parameter)
		{
			if (string.IsNullOrEmpty(parameter))
				return "Quizmode is " + (QuizMode ? "on" : "off");
			else if (parameter == "on")
			{
				QuizMode = true;
				QueryConnection.ChangeDescription("<Quiztime!>");
			}
			else if (parameter == "off")
			{
				if (info.Session.IsPrivate)
					return "No cheatig! Everybody has to see it!";
				QuizMode = false;
				QueryConnection.ChangeDescription(AudioFramework.CurrentPlayData.Resource.ResourceTitle);
			}
			else
				CommandHelp(info, "quiz");
			return null;
		}
Example #38
0
		public string CommandHistoryClean(ExecutionInformation info)
		{
			info.Session.SetResponse(ResponseHistoryClean, null);
			return $"Dou want to clean the history file now? This might take a while and make the bot unresponsive in meanwhile. !(yes|no)";
		}
Example #39
0
		public string CommandHistoryHelp(ExecutionInformation info) => CommandHelp(info, "history");
Example #40
0
		public string CommandHistoryDelete(ExecutionInformation info, uint id)
		{
			AudioLogEntry ale = HistoryManager.GetEntryById(id);
			if (ale == null)
				return "Could not find track with this id";
			info.Session.SetResponse(ResponseHistoryDelete, ale);
			return $"Do you really want to delete the entry with the id {id}? !(yes|no)";
		}
Example #41
0
		public string CommandHelp(ExecutionInformation info, params string[] parameter)
		{
			if (parameter.Length == 0)
			{
				var strb = new StringBuilder();
				strb.Append("\n========= Welcome to the TS3AudioBot ========="
					+ "\nIf you need any help with a special command use !help <commandName>."
					+ "\nHere are all possible commands:\n");
				foreach (var botCom in CommandManager.AllCommands.Select(c => c.InvokeName).GroupBy(n => n.Split(' ')[0]))
					strb.Append(botCom.Key).Append(", ");
				strb.Length -= 2;
				return strb.ToString();
			}
			else
			{
				CommandGroup group = CommandManager.CommandSystem.RootCommand;
				ICommand target = null;
				for (int i = 0; i < parameter.Length; i++)
				{
					var possibilities = XCommandSystem.FilterList(group.Commands, parameter[i]).ToList();
					if (possibilities.Count == 0)
						return "No matching command found! Try !help to get a list of all commands.";
					else if (possibilities.Count > 1)
						return "Requested command is ambiguous between: " + string.Join(", ", possibilities.Select(kvp => kvp.Key));
					else if (possibilities.Count == 1)
					{
						target = possibilities.First().Value;
						if (i < parameter.Length - 1)
						{
							group = target as CommandGroup;
							if (group == null)
								return "The command has no further subfunctions after " + string.Join(" ", parameter, 0, i);
						}
					}
				}

				var targetB = target as BotCommand;
				if (targetB != null)
					return targetB.GetHelp();

				var targetCG = target as CommandGroup;
				if (targetCG != null)
					return "The command contains the following subfunctions: " + string.Join(", ", targetCG.Commands.Select(g => g.Key));

				var targetOFC = target as OverloadedFunctionCommand;
				if (targetOFC != null)
				{
					var strb = new StringBuilder();
					foreach (var botCom in targetOFC.Functions.OfType<BotCommand>())
						strb.Append(botCom.GetHelp());
					return strb.ToString();
				}

				return "Seems like something went wrong. No help can be shown for this command path.";
			}
		}
Example #42
0
		public string CommandGetUserId(ExecutionInformation info, string parameter)
		{
			ClientData client = QueryConnection.GetClientByName(parameter);
			if (client == null)
				return "No user found...";
			else
				return $"Client: UID:{client.ClientId} DBID:{client.DatabaseId} ChanID:{client.ChannelId}";
		}
Example #43
0
		public void CommandQuitForce(ExecutionInformation info)
		{
			info.Session.Write("Goodbye!");
			Dispose();
			Log.Write(Log.Level.Info, "Exiting...");
		}
Example #44
0
		public string CommandSeek(ExecutionInformation info, string parameter)
		{
			TimeSpan span;
			bool parsed = false;
			if (parameter.Contains(":"))
			{
				string[] splittime = parameter.Split(':');
				if (splittime.Length == 2)
				{
					int seconds = -1, minutes;
					parsed = int.TryParse(splittime[0], out minutes) && int.TryParse(splittime[1], out seconds);
					if (parsed)
						span = TimeSpan.FromSeconds(seconds) + TimeSpan.FromMinutes(minutes);
					else
						span = TimeSpan.MinValue;
				}
				else span = TimeSpan.MinValue;
			}
			else
			{
				int seconds;
				parsed = int.TryParse(parameter, out seconds);
				span = TimeSpan.FromSeconds(seconds);
			}

			if (!parsed)
				return CommandHelp(info, "seek");

			if (!AudioFramework.Seek(span))
				return "The point of time is not within the songlenth.";
			return null;
		}
Example #45
0
		public void CommandQuitReset(ExecutionInformation info)
		{
			throw new NotImplementedException();
		}
Example #46
0
		public ICommandResult CommandTake(ExecutionInformation info, IEnumerable<ICommand> arguments, IEnumerable<CommandResultType> returnTypes)
		{
			var argList = arguments.ToList();

			if (argList.Count < 2)
				throw new CommandException("Expected at least 2 parameters");

			int start = 0;
			int count = 0;
			string delimiter = null;

			// Get count
			var res = ((StringCommandResult)argList[0].Execute(info, Enumerable.Empty<ICommand>(), new[] { CommandResultType.String })).Content;
			if (!int.TryParse(res, out count) || count < 0)
				throw new CommandException("Count must be an integer >= 0");

			if (argList.Count > 2)
			{
				// Get start
				res = ((StringCommandResult)argList[1].Execute(info, Enumerable.Empty<ICommand>(), new[] { CommandResultType.String })).Content;
				if (!int.TryParse(res, out start) || start < 0)
					throw new CommandException("Start must be an integer >= 0");
			}

			if (argList.Count > 3)
				// Get delimiter
				delimiter = ((StringCommandResult)argList[2].Execute(info, Enumerable.Empty<ICommand>(), new[] { CommandResultType.String })).Content;

			string text = ((StringCommandResult)argList[Math.Min(argList.Count - 1, 3)]
				.Execute(info, Enumerable.Empty<ICommand>(), new[] { CommandResultType.String })).Content;

			IEnumerable<string> splitted;
			if (delimiter == null)
				splitted = text.Split();
			else
				splitted = text.Split(new[] { delimiter }, StringSplitOptions.None);
			if (splitted.Count() < start + count)
				throw new CommandException("Not enough arguments to take");
			splitted = splitted.Skip(start).Take(count);

			foreach (var returnType in returnTypes)
			{
				if (returnType == CommandResultType.String)
					return new StringCommandResult(string.Join(delimiter ?? " ", splitted));
			}

			throw new CommandException("Can't find a fitting return type for take");
		}
Example #47
0
		public string CommandRepeat(ExecutionInformation info, string parameter)
		{
			if (string.IsNullOrEmpty(parameter))
				return "Repeat is " + (AudioFramework.Repeat ? "on" : "off");
			else if (parameter == "on")
				AudioFramework.Repeat = true;
			else if (parameter == "off")
				AudioFramework.Repeat = false;
			else
				return CommandHelp(info, "repeat");
			return null;
		}
Example #48
0
		private void TextCallback(object sender, TextMessage textMessage)
		{
			Log.Write(Log.Level.Debug, "MB Got message from {0}: {1}", textMessage.InvokerName, textMessage.Message);

			textMessage.Message = textMessage.Message.TrimStart(new[] { ' ' });
			if (!textMessage.Message.StartsWith("!"))
				return;
			BobController.HasUpdate();

			QueryConnection.RefreshClientBuffer(true);

			// get the current session
			BotSession session = SessionManager.GetSession(textMessage.Target, textMessage.InvokerId);
			if (textMessage.Target == MessageTarget.Private && session == SessionManager.DefaultSession)
			{
				Log.Write(Log.Level.Debug, "MB User {0} created auto-private session with the bot", textMessage.InvokerName);
				try
				{
					session = SessionManager.CreateSession(this, textMessage.InvokerId);
				}
				catch (SessionManagerException smex)
				{
					Log.Write(Log.Level.Error, smex.ToString());
					return;
				}
			}

			var isAdmin = new Lazy<bool>(() => HasInvokerAdminRights(textMessage));
			var execInfo = new ExecutionInformation(session, textMessage, isAdmin);

			// check if the user has an open request
			if (session.ResponseProcessor != null)
			{
				if (session.ResponseProcessor(execInfo))
				{
					session.ClearResponse();
					return;
				}
			}

			// parse (and execute) the command
			ASTNode parsedAst = CommandParser.ParseCommandRequest(textMessage.Message);
			if (parsedAst.Type == ASTType.Error)
			{
				PrintAstError(session, (ASTError)parsedAst);
			}
			else
			{
				var command = CommandManager.CommandSystem.AstToCommandResult(parsedAst);

				try
				{
					var res = command.Execute(execInfo, Enumerable.Empty<ICommand>(),
						new[] { CommandResultType.String, CommandResultType.Empty });
					if (res.ResultType == CommandResultType.String)
					{
						var sRes = (StringCommandResult)res;
						// Write result to user
						if (!string.IsNullOrEmpty(sRes.Content))
							session.Write(sRes.Content);
					}
				}
				catch (CommandException ex)
				{
					session.Write("Error: " + ex.Message);
				}
				catch (Exception ex)
				{
					session.Write("An unexpected error occured: " + ex.Message);
					Log.Write(Log.Level.Error, "MB Unexpected command error: ", ex);
				}
			}
		}
Example #49
0
		public string CommandSong(ExecutionInformation info)
		{
			if (AudioFramework.CurrentPlayData == null)
				return "There is nothing on right now...";
			else if (QuizMode && AudioFramework.CurrentPlayData.Invoker.ClientId != info.TextMessage.InvokerId)
				return "Sorry, you have to guess!";
			else
				return $"[url={FactoryManager.RestoreLink(AudioFramework.CurrentPlayData)}]{AudioFramework.CurrentPlayData.Resource.ResourceTitle}[/url]";
		}
Example #50
0
		public ICommandResult CommandIf(ExecutionInformation info, IEnumerable<ICommand> arguments, IEnumerable<CommandResultType> returnTypes)
		{
			var argList = arguments.ToList();
			if (argList.Count < 4)
				throw new CommandException("Expected at least 4 arguments");
			var arg0 = ((StringCommandResult)argList[0].Execute(info, Enumerable.Empty<ICommand>(), new[] { CommandResultType.String })).Content;
			var cmp = ((StringCommandResult)argList[1].Execute(info, Enumerable.Empty<ICommand>(), new[] { CommandResultType.String })).Content;
			var arg1 = ((StringCommandResult)argList[2].Execute(info, Enumerable.Empty<ICommand>(), new[] { CommandResultType.String })).Content;

			Func<double, double, bool> comparer;
			switch (cmp)
			{
			case "<": comparer = (a, b) => a < b; break;
			case ">": comparer = (a, b) => a > b; break;
			case "<=": comparer = (a, b) => a <= b; break;
			case ">=": comparer = (a, b) => a >= b; break;
			case "==": comparer = (a, b) => a == b; break;
			case "!=": comparer = (a, b) => a != b; break;
			default: throw new CommandException("Unknown comparison operator");
			}

			double d0, d1;
			bool cmpResult;
			// Try to parse arguments into doubles
			if (double.TryParse(arg0, NumberStyles.Number, CultureInfo.InvariantCulture, out d0)
				&& double.TryParse(arg1, NumberStyles.Number, CultureInfo.InvariantCulture, out d1))
				cmpResult = comparer(d0, d1);
			else
				cmpResult = comparer(arg0.CompareTo(arg1), 0);

			// If branch
			if (cmpResult)
				return argList[3].Execute(info, Enumerable.Empty<ICommand>(), returnTypes);
			// Else branch
			if (argList.Count > 4)
				return argList[4].Execute(info, Enumerable.Empty<ICommand>(), returnTypes);

			// Try to return nothing
			if (returnTypes.Contains(CommandResultType.Empty))
				return new EmptyCommandResult();
			throw new CommandException("If found nothing to return");
		}
Example #51
0
		public string CommandTest(ExecutionInformation info)
		{
			if (!info.Session.IsPrivate)
				return "Please use as private, admins too!";
			else
			{
				info.Session.Write("Good boy!");
				// stresstest
				for (int i = 0; i < 10; i++)
					info.Session.Write(i.ToString());
				return "Test end";
			}
		}
Example #52
0
		public string CommandKickme(ExecutionInformation info, string parameter)
		{
			try
			{
				if (string.IsNullOrEmpty(parameter) || parameter == "near")
					QueryConnection.KickClientFromChannel(info.TextMessage.InvokerId);
				else if (parameter == "far")
					QueryConnection.KickClientFromServer(info.TextMessage.InvokerId);
				return null;
			}
			catch (QueryCommandException ex)
			{
				Log.Write(Log.Level.Info, "Could not kick: {0}", ex);
				return "I'm not strong enough, master!";
			}
		}
Example #53
0
		public void CommandUnsubscribe(ExecutionInformation info)
		{
			BobController.WhisperClientUnsubscribe(info.TextMessage.InvokerId);
		}
Example #54
0
		private bool ResponseVolume(ExecutionInformation info)
		{
			Answer answer = TextUtil.GetAnswer(info.TextMessage.Message);
			if (answer == Answer.Yes)
			{
				if (info.IsAdmin.Value)
				{
					var respInt = info.Session.ResponseData as int?;
					if (!respInt.HasValue)
					{
						Log.Write(Log.Level.Error, "responseData is not an int.");
						return true;
					}
					AudioFramework.Volume = respInt.Value;
				}
				else
				{
					info.Session.Write("Command can only be answered by an admin.");
				}
			}
			return answer != Answer.Unknown;
		}
Example #55
0
		public string CommandLoop(ExecutionInformation info, string parameter)
		{
			if (string.IsNullOrEmpty(parameter))
				return "Loop is " + (AudioFramework.Loop ? "on" : "off");
			else if (parameter == "on")
				AudioFramework.Loop = true;
			else if (parameter == "off")
				AudioFramework.Loop = false;
			else
				return CommandHelp(info, "loop");
			return null;
		}
Example #56
0
		private bool ResponseHistoryDelete(ExecutionInformation info)
		{
			Answer answer = TextUtil.GetAnswer(info.TextMessage.Message);
			if (answer == Answer.Yes)
			{
				if (info.IsAdmin.Value)
				{
					var ale = info.Session.ResponseData as AudioLogEntry;
					if (ale == null)
					{
						Log.Write(Log.Level.Error, "No entry provided.");
						return true;
					}
					HistoryManager.RemoveEntry(ale);
				}
				else
				{
					info.Session.Write("Command can only be answered by an admin.");
				}
			}
			return answer != Answer.Unknown;
		}
Example #57
0
		public string CommandHistoryLast(ExecutionInformation info, int? amount)
		{
			if (amount.HasValue)
			{
				var query = new SeachQuery { MaxResults = amount.Value };
				return HistoryManager.SearchParsed(query);
			}
			else
			{
				var ale = HistoryManager.Search(new SeachQuery { MaxResults = 1 }).FirstOrDefault();
				if (ale != null)
				{
					ClientData client = QueryConnection.GetClientById(info.TextMessage.InvokerId);
					return FactoryManager.RestoreAndPlay(ale, new PlayData(info.Session, client, null, false));
				}
				else return "There is no song in the history";
			}
		}
Example #58
0
		public void CommandPM(ExecutionInformation info)
		{
			BotSession ownSession = SessionManager.CreateSession(this, info.TextMessage.InvokerId);
			ownSession.Write("Hi " + info.TextMessage.InvokerName);
		}
Example #59
0
		public ICommandResult CommandEval(ExecutionInformation info, IEnumerable<ICommand> arguments, IEnumerable<CommandResultType> returnTypes)
		{
			// Evaluate the first argument on the rest of the arguments
			if (!arguments.Any())
				throw new CommandException("Need at least one argument to evaluate");
			var leftArguments = arguments.Skip(1);
			var arg0 = arguments.First().Execute(info, Enumerable.Empty<ICommand>(), new[] { CommandResultType.Command, CommandResultType.String });
			if (arg0.ResultType == CommandResultType.Command)
				return ((CommandCommandResult)arg0).Command.Execute(info, leftArguments, returnTypes);

			// We got a string back so parse and evaluate it
			var args = ((StringCommandResult)arg0).Content;

			// Add the rest of the arguments
			args += string.Join(" ", arguments.Select(a =>
				((StringCommandResult)a.Execute(info, Enumerable.Empty<ICommand>(), new[] { CommandResultType.String })).Content));

			var cmd = CommandManager.CommandSystem.AstToCommandResult(CommandParser.ParseCommandRequest(args));
			return cmd.Execute(info, leftArguments, returnTypes);
		}
Example #60
0
		public string CommandHistoryQueue(ExecutionInformation info, uint id)
		{
			var ale = HistoryManager.GetEntryById(id);
			if (ale == null)
				return "Could not find track with this id";
			ClientData client = QueryConnection.GetClientById(info.TextMessage.InvokerId);
			return FactoryManager.RestoreAndPlay(ale, new PlayData(info.Session, client, null, true));
		}