Beispiel #1
0
        public async Task RecordExecution(ICommandActor actor, string command, DateTime time)
        {
            if (actor.Type == KnownActorTypes.Console)
            {
                return;
            }

            string actorId = GetFullId(actor);

            if (m_Records.TryGetValue(actorId, out var records))
            {
                var record = records.FirstOrDefault(x => x.Command == command);

                if (record == null)
                {
                    records.Add(new CooldownRecord(command, time));
                }
                else
                {
                    record.Executed = time;
                }
            }
            else
            {
                m_Records.Add(actorId, new List <CooldownRecord>()
                {
                    new CooldownRecord(command, time)
                });
            }

            await SavePersistedRecord(actorId, command, time);
        }
 protected override void GenerateAggregateClient()
 {
     if (DomainId != null)
     {
         AggregateClient = Clients.CreateCommandActor(ContainerName, DomainName, null);
     }
 }
Beispiel #3
0
        public async Task <DateTime?> LastExecuted(ICommandActor actor, string command)
        {
            if (actor.Type == KnownActorTypes.Console)
            {
                return(null);
            }

            if (await m_PermissionChecker.CheckPermissionAsync(actor,
                                                               $"{m_PluginAccessor.Instance.OpenModComponentId}:immune") == PermissionGrantResult.Grant)
            {
                return(null);
            }

            string actorId = GetFullId(actor);

            if (m_Records.TryGetValue(actorId, out List <CooldownRecord> records))
            {
                var record = records.FirstOrDefault(x => x.Command == command);

                if (record != null)
                {
                    return(record.Executed);
                }
            }

            return((await GetPersistedRecords(actorId))?.FirstOrDefault(x => x.Command == command)?.Executed);
        }
Beispiel #4
0
        public async Task <DateTime?> GetLastExecutedAsync(ICommandActor actor, string command)
        {
            if (actor.Type == KnownActorTypes.Console)
            {
                return(null);
            }

            if (await m_PermissionChecker.CheckPermissionAsync(actor, "OpenMod.Core:cooldowns.immune") == PermissionGrantResult.Grant)
            {
                return(null);
            }

            await LoadPersistedRecords();

            var actorId = GetActorFullId(actor);

            if (m_Records.TryGetValue(actorId, out List <CooldownRecord> records))
            {
                var record = records.FirstOrDefault(x => x.Command == command);

                if (record != null)
                {
                    return(record.Executed);
                }
            }

            return(null);
        }
        public ICommandContext CreateContext(ICommandActor actor, string[] args, string prefix, IReadOnlyCollection <ICommandRegistration> commandRegistrations)
        {
            if (actor == null)
            {
                throw new ArgumentNullException(nameof(actor));
            }

            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            var rootCommand = GetCommandRegistration(actor, args[0], commandRegistrations.Where(d => d.ParentId == null));

            if (rootCommand == null)
            {
                var exceptionContext = new CommandContext(null, actor, args.First(), prefix, args.Skip(1).ToList(), m_LifetimeScope.BeginLifetimeScopeEx());
                var localizer        = m_LifetimeScope.Resolve <IOpenModStringLocalizer>();
                exceptionContext.Exception = new CommandNotFoundException(localizer["commands:errors:not_found", new { CommandName = args[0], Args = args }]);
                //await actor.PrintMessageAsync(Color.Red, exceptionContext.Exception.Message);
                return(exceptionContext);
            }

            var scope       = rootCommand.Component.LifetimeScope.BeginLifetimeScopeEx("AutofacWebRequest");
            var rootContext = new CommandContext(rootCommand, actor, args.First(), prefix, args.Skip(1).ToList(), scope);

            return(BuildContextTree(rootContext, commandRegistrations));
        }
        //
        // Chat stuff
        //

        public async Task TellAsync(ICommandActor actor, string message, Color color)
        {
            if (!Thread.CurrentThread.IsGameThread())
            {
                await UniTask.SwitchToMainThread();
            }
            Tell(actor, message, color);
        }
        public bool SupportsActor(ICommandActor actor)
        {
            if (m_CommandActorTypes.Count == 0)
            {
                return(true);
            }

            return(m_CommandActorTypes.Any(d => d.IsInstanceOfType(actor)));
        }
        private ICommandRegistration GetCommandRegistration(ICommandActor actor, string name, IEnumerable <ICommandRegistration> commandRegistrations)
        {
            var baseQuery = commandRegistrations.Where(d => d.SupportsActor(actor));

            // todo: could be done in a single iteration
            // ReSharper disable PossibleMultipleEnumeration
            return(baseQuery.FirstOrDefault(d => d.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
                   ?? baseQuery.FirstOrDefault(d => d.Aliases != null && d.Aliases.Any(e => e.Equals(name, StringComparison.OrdinalIgnoreCase))));
            // ReSharper restore PossibleMultipleEnumeration
        }
 public CommandContext(ICommandRegistration command, ICommandActor actor, string alias, string prefix, ICollection <string> args, ILifetimeScope scope)
 {
     CommandPrefix       = prefix ?? string.Empty;
     CommandAlias        = alias;
     LifetimeScope       = scope;
     CommandRegistration = command;
     ServiceProvider     = scope?.Resolve <IServiceProvider>();
     Actor       = actor;
     RootContext = this;
     Parameters  = new CommandParameters(this, args);
     Data        = new Dictionary <string, object>();
 }
Beispiel #10
0
        private bool ParseLine(string line, ICommandActor actor)
        {
            var current = new LineCommand();

            if (current.Parse(line))
            {
                return(actor.ActionLine(current));;
            }
            else
            {
                return(false);
            }
        }
Beispiel #11
0
        public async Task <TimeSpan?> GetCooldownSpan(ICommandActor actor, string commandId)
        {
            var roles = await m_PermissionRoleStore.GetRolesAsync(actor);

            if (roles == null || roles.Count == 0)
            {
                return(null);
            }

            TimeSpan?span     = null;
            int      priority = 0;

            foreach (var role in roles)
            {
                try
                {
                    // Skip as result won't matter
                    if (span.HasValue && priority >= role.Priority)
                    {
                        continue;
                    }

                    var data =
                        (await m_PermissionRolesDataStore.GetRoleDataAsync <List <object> >(role.Id,
                                                                                            "cooldowns"))?.OfType <Dictionary <object, object> >();

                    if (data == null)
                    {
                        continue;
                    }

                    foreach (var dict in data)
                    {
                        var currentSpan = dict.ToObject <CooldownSpan>();

                        if (currentSpan.Command.Equals(commandId, StringComparison.OrdinalIgnoreCase))
                        {
                            span     = currentSpan.GetParsedCooldown();
                            priority = role.Priority;
                        }
                    }
                }
                catch (Exception ex)
                {
                    m_Logger.LogError(ex, "Error occurred while parsing command cooldown");
                    throw;
                }
            }

            return(span);
        }
        public bool SupportsActor(ICommandActor actor)
        {
            if (actor == null)
            {
                throw new ArgumentNullException(nameof(actor));
            }

            if (m_CommandActorTypes == null || m_CommandActorTypes.Count == 0)
            {
                return(true);
            }

            return(m_CommandActorTypes.Any(d => d.IsInstanceOfType(actor)));
        }
        public void Tell(ICommandActor actor, string message, Color color)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            if (actor is UnturnedUser untUser)
            {
                Tell(untUser.Player.SteamPlayer, message, color);
            }
            else
            {
                actor.PrintMessageAsync(message);
            }
        }
Beispiel #14
0
        private bool ParseLines(ICommandActor actor)
        {
            actor.PreAction();
            bool ret = true;

            while (!EndOfStream())
            {
                if (!ParseLine(ReadLine(), actor))
                {
                    ret = false;
                    break;
                }
            }
            actor.PostAction();
            return(ret);
        }
Beispiel #15
0
        public CommandContext(ICommandRegistration?command, ICommandActor actor, string alias, string prefix, ICollection <string> args, ILifetimeScope scope)
        {
            if (args == null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            CommandPrefix       = prefix ?? throw new ArgumentNullException(nameof(prefix));
            CommandAlias        = alias ?? throw new ArgumentNullException(nameof(alias));
            LifetimeScope       = scope ?? throw new ArgumentNullException(nameof(scope));
            CommandRegistration = command;
            ServiceProvider     = scope.Resolve <IServiceProvider>();
            Actor       = actor ?? throw new ArgumentNullException(nameof(actor));
            RootContext = this;
            Parameters  = new CommandParameters(this, args);
            Data        = new Dictionary <string, object>();
        }
        public ICommandContext CreateContext(ICommandActor actor, string[] args, string prefix, IEnumerable <ICommandRegistration> commandRegistrations)
        {
            var rootCommand = GetCommandRegistration(actor, args[0], commandRegistrations.Where(d => d.ParentId == null));

            if (rootCommand == null)
            {
                var exceptionContext = new CommandContext(null, actor, args.First(), prefix, args.Skip(1).ToList(), m_LifetimeScope.BeginLifetimeScope());
                var localizer        = m_LifetimeScope.Resolve <IOpenModStringLocalizer>();
                exceptionContext.Exception = new CommandNotFoundException(localizer["commands:errors:not_found", new { CommandName = args[0], Args = args }]);
                //await actor.PrintMessageAsync(Color.Red, exceptionContext.Exception.Message);
                return(exceptionContext);
            }

            var scope       = rootCommand.Component.LifetimeScope.BeginLifetimeScope($"Command context scope for \"{string.Join(" ", args)}\" by actor {actor.Type}/{actor.DisplayName} ({actor.Id})");
            var rootContext = new CommandContext(rootCommand, actor, args.First(), prefix, args.Skip(1).ToList(), scope);

            return(BuildContextTree(rootContext, commandRegistrations));
        }
Beispiel #17
0
        private async Task GetTarget()
        {
            try
            {
                m_TargetUser = await Context.Parameters.GetAsync <IUser>(0);

                m_IsSelf = Context.Actor.Equals(m_TargetUser);

                if (m_IsSelf && await IsDenied(PayToSelf))
                {
                    throw new UserFriendlyException(m_StringLocalizer["economy:fail:self_pay"]);
                }
            }
            catch (CommandParameterParseException)
            {
                throw new UserFriendlyException(m_StringLocalizer["economy:fail:user_not_found",
                                                                  new { Input = await Context.Parameters.GetAsync <string>(0) }]);
            }
        }
Beispiel #18
0
        private async Task GetTarget()
        {
            if (Context.Parameters.Length < 1 || await IsDenied(OthersPerm))
            {
                m_IsSelf     = true;
                m_TargetUser = Context.Actor;
                return;
            }

            try
            {
                m_TargetUser = await Context.Parameters.GetAsync <IUser>(0);

                m_IsSelf = Context.Actor.Equals(m_TargetUser);
            }
            catch (CommandParameterParseException)
            {
                throw new UserFriendlyException(m_StringLocalizer["economy:fail:user_not_found",
                                                                  new { Input = await Context.Parameters.GetAsync <string>(0) }]);
            }
        }
Beispiel #19
0
 public bool SupportsActor(ICommandActor actor)
 {
     return(m_CommandActorTypes.Any(d => d.IsInstanceOfType(actor)));
 }
Beispiel #20
0
 public bool SupportsActor(ICommandActor actor)
 {
     return(actor.Type == KnownActorTypes.Player || actor.Type == KnownActorTypes.Console);
 }
Beispiel #21
0
 private string GetActorFullId(ICommandActor actor)
 {
     return(actor.Type + "." + actor.Id);
 }
 public CommandExecutedEvent(ICommandActor actor, ICommandContext commandContext)
 {
     Actor          = actor;
     CommandContext = commandContext;
 }
 private ICommandRegistration GetCommandRegistration(ICommandActor actor, string name, IEnumerable <ICommandRegistration> commandRegistrations)
 {
     return(commandRegistrations.FirstOrDefault(d => d.SupportsActor(actor) &&
                                                (d.Name.Equals(name, StringComparison.OrdinalIgnoreCase) ||
                                                 (d.Aliases != null && d.Aliases.Any(e => e.Equals(name, StringComparison.OrdinalIgnoreCase))))));
 }
Beispiel #24
0
 private string GetFullId(ICommandActor actor) => actor.Type + "." + actor.Id;
        public async Task <ICommandContext> ExecuteAsync(ICommandActor actor, string[] args, string prefix)
        {
            if (args == null || args.Length == 0)
            {
                throw new Exception("Can not execute command with null or empty args");
            }

            var currentCommandAccessor = m_LifetimeScope.Resolve <ICurrentCommandContextAccessor>();
            var commandsRegistrations  = m_CommandStore.Commands;
            var logger = m_LifetimeScope.Resolve <ILogger <CommandExecutor> >();
            var commandContextBuilder = m_LifetimeScope.Resolve <ICommandContextBuilder>();
            var permissionChecker     = m_LifetimeScope.Resolve <IPermissionChecker>();
            var stringLocalizer       = m_LifetimeScope.Resolve <IOpenModStringLocalizer>();
            var commandContext        = commandContextBuilder.CreateContext(actor, args, prefix, commandsRegistrations);

            var commandExecutingEvent = new CommandExecutingEvent(actor, commandContext);
            await m_EventBus.EmitAsync(m_Runtime, this, commandExecutingEvent);

            if (commandExecutingEvent.IsCancelled)
            {
                return(commandExecutingEvent.CommandContext);
            }

            logger.LogInformation($"Actor {actor.Type}/{actor.DisplayName} ({actor.Id}) has executed command \"{string.Join(" ", args)}\".");

            try
            {
                if (commandContext.Exception != null)
                {
                    throw commandContext.Exception;
                }

                currentCommandAccessor.Context = commandContext;

                var permission = m_CommandPermissionBuilder.GetPermission(commandContext.CommandRegistration);
                if (!string.IsNullOrWhiteSpace(permission) && await permissionChecker.CheckPermissionAsync(actor, permission) != PermissionGrantResult.Grant)
                {
                    throw new NotEnoughPermissionException(permission, stringLocalizer);
                }

                var command = commandContext.CommandRegistration.Instantiate(commandContext.ServiceProvider);
                await command.ExecuteAsync();

                currentCommandAccessor.Context = null;
            }
            catch (UserFriendlyException ex)
            {
                await actor.PrintMessageAsync(ex.Message, Color.DarkRed);

                commandContext.Exception = ex;
            }
            catch (Exception ex)
            {
                await actor.PrintMessageAsync("An internal error occured during the command execution.", Color.DarkRed);

                logger.LogError(ex, $"Exception occured on command \"{string.Join(" ", args)}\" by actor {actor.Type}/{actor.DisplayName} ({actor.Id})");
                commandContext.Exception = ex;

#if DEBUG
                throw; // in debug mode we want to debug such exceptions instead of catching them
#endif
            }
            finally
            {
                var commandExecutedEvent = new CommandExecutedEvent(actor, commandContext);
                await m_EventBus.EmitAsync(m_Runtime, this, commandExecutedEvent);

                await commandContext.DisposeAsync();
            }

            return(commandContext);
        }
Beispiel #26
0
 /// <summary>
 /// ファイルの解析
 /// </summary>
 /// <param name="inputStream">ファイルストリーム</param>
 /// <param name="actor">コマンド処理用のインターフェースクラス</param>
 /// <returns>最後まで処理した場合true</returns>
 public bool Parse(Stream inputStream, ICommandActor actor)
 {
     inputStream_ = inputStream;
     return(ParseLines(actor));
 }
Beispiel #27
0
 public bool SupportsActor(ICommandActor actor)
 {
     return(BaseCommandRegistration.SupportsActor(actor));
 }
Beispiel #28
0
        public async Task <ICommandContext> ExecuteAsync(ICommandActor actor, string[] args, string prefix)
        {
            if (args == null || args.Length == 0)
            {
                throw new Exception("Cannot execute command with null or empty args.");
            }

            m_Logger.LogInformation("Actor {ActorType}/{ActorName} has executed command \"{Command}\"",
                                    actor.Type, actor.FullActorName, string.Join(" ", args));

            var currentCommandAccessor = m_LifetimeScope.Resolve <ICurrentCommandContextAccessor>();
            var commandContextBuilder  = m_LifetimeScope.Resolve <ICommandContextBuilder>();
            var stringLocalizer        = m_LifetimeScope.Resolve <IOpenModStringLocalizer>();

            var commandsRegistrations = await m_CommandStore.GetCommandsAsync();

            var commandContext        = commandContextBuilder.CreateContext(actor, args, prefix, commandsRegistrations);
            var commandExecutingEvent = new CommandExecutingEvent(actor, commandContext);
            await m_EventBus.EmitAsync(m_Runtime, this, commandExecutingEvent);

            if (commandExecutingEvent.IsCancelled)
            {
                return(commandExecutingEvent.CommandContext);
            }

            try
            {
                if (commandContext.Exception != null)
                {
                    throw commandContext.Exception;
                }

                currentCommandAccessor.Context = commandContext;

                var permission        = m_CommandPermissionBuilder.GetPermission(commandContext.CommandRegistration !);
                var permissionChecker = m_Runtime.LifetimeScope.Resolve <IPermissionChecker>();

                if (!string.IsNullOrWhiteSpace(permission) && await permissionChecker.CheckPermissionAsync(actor, permission) != PermissionGrantResult.Grant)
                {
                    throw new NotEnoughPermissionException(stringLocalizer, permission);
                }

                var sw = new Stopwatch();
                sw.Start();
                var command = commandContext.CommandRegistration !.Instantiate(commandContext.ServiceProvider);
                await command.ExecuteAsync();

                m_Logger.LogDebug("Command \"{Command}\" executed in {Ms}ms",
                                  string.Join(" ", args), sw.ElapsedMilliseconds);

                currentCommandAccessor.Context = null;
            }
            catch (UserFriendlyException ex)
            {
                commandContext.Exception = ex;
            }
            catch (Exception ex)
            {
                commandContext.Exception = ex;
            }
            finally
            {
                var commandExecutedEvent = new CommandExecutedEvent(actor, commandContext);
                await m_EventBus.EmitAsync(m_Runtime, this, commandExecutedEvent);

                if (commandContext.Exception != null && !commandExecutedEvent.ExceptionHandled)
                {
                    if (commandContext.Exception is UserFriendlyException)
                    {
                        await actor.PrintMessageAsync(commandContext.Exception.Message, Color.DarkRed);
                    }
                    else
                    {
                        await actor.PrintMessageAsync("An internal error occured during the command execution.", Color.DarkRed);

                        m_Logger.LogError(commandContext.Exception,
                                          "Exception occured on command \"{Command}\" by actor {ActorType}/{ActorName} ({ActorId})",
                                          string.Join(" ", args), actor.Type, actor.DisplayName, actor.Id);
                    }
                }

                await commandContext.DisposeAsync();
            }

            return(commandContext);
        }