public async Task <Result> Handle(Command request, CancellationToken cancellationToken)
        {
            try
            {
                var id     = request.ServerId.ToUpperInvariant();
                var server = _polychatService.GetOnlineServerOrDefault(id);

                if (server is null)
                {
                    return(new NotFoundError($"Could not find server with ID: {id}"));
                }

                var msg = new GenericCommand
                {
                    DiscordCommandName = "tps",
                    DefaultCommand     = "forge tps",
                    DiscordChannelId   = request.ChannelId.ToString()
                };

                await _polychatService.SendMessage(server, msg);

                return(Result.FromSuccess());
            }
            catch (Exception e)
            {
                return(e);
            }
        }
Пример #2
0
            public async Task <Result> Handle(Command request, CancellationToken cancellationToken)
            {
                try
                {
                    var msg = new GenericCommand
                    {
                        DiscordCommandName = "exec",
                        DefaultCommand     = "$args",
                        Args             = { request.McCmdArgs },
                        DiscordChannelId = request.ChannelId.ToString()
                    };

                    if (request.ServerId.Equals("<all>"))
                    {
                        await _polychatService.BroadcastMessage(msg);

                        return(Result.FromSuccess());
                    }

                    var server = _polychatService.GetOnlineServerOrDefault(request.ServerId.ToUpperInvariant());

                    if (server is null)
                    {
                        return(new NotFoundError($"Could not find server with ID: {request.ServerId}"));
                    }

                    await _polychatService.SendMessage(server, msg);

                    return(Result.FromSuccess());
                }
                catch (Exception e)
                {
                    return(e);
                }
            }
Пример #3
0
            protected override async Task Handle(TcpRequest <ServerStatus> request, CancellationToken cancellationToken)
            {
                var msg         = request.Message;
                var serverId    = new PolychatServerIdString(msg.ServerId);
                var sanitisedId = serverId.ToSanitisedUppercase();
                var server      = _polychatService.GetOnlineServerOrDefault(sanitisedId);

                if (server is not null)
                {
                    await _polychatService.ForwardMessage(sanitisedId, msg);

                    if (
                        msg.Status is
                        ServerStatus.Types.ServerStatusEnum.Stopped or ServerStatus.Types.ServerStatusEnum.Crashed
                        )
                    {
                        _polychatService.RemoveOnlineServer(sanitisedId);
                        _logger.LogInformation("Removed server {id} from the list of online servers.", sanitisedId);
                        request.ConnectedClient.StopListening();
                    }

                    var getChatChannelResult =
                        await _channelApi.GetChannelAsync(new(_polychatSettings.ChatChannelId), cancellationToken);

                    if (!getChatChannelResult.IsSuccess)
                    {
                        throw new Exception(getChatChannelResult.Error.Message);
                    }

                    var message           = $"Server {msg.Status.ToString().ToLowerInvariant()}.";
                    var chatMessage       = new PolychatChatMessageString(sanitisedId, message);
                    var sendMessageResult =
                        await _channelApi.CreateMessageAsync(new(_polychatSettings.ChatChannelId),
                                                             chatMessage.ToDiscordFormattedString(), ct : cancellationToken);

                    if (!sendMessageResult.IsSuccess)
                    {
                        throw new Exception(getChatChannelResult.Error?.Message ??
                                            "Could not forward message to Discord.");
                    }

                    _logger.LogInformation("Server {id} changed status to {newStatus}", sanitisedId,
                                           msg.Status);
                }
                else
                {
                    if (msg.Status == ServerStatus.Types.ServerStatusEnum.Started)
                    {
                        _logger.LogWarning(
                            "Server {id} has unexpectedly sent ServerStatus message before sending ServerInfo message.",
                            sanitisedId);
                    }
                    else
                    {
                        throw new KeyNotFoundException($"Could not find server {sanitisedId} in the list of online servers");
                    }
                }
            }
Пример #4
0
            protected override async Task Handle(TcpRequest <ServerPlayerStatusChangedEvent> request, CancellationToken cancellationToken)
            {
                var serverId    = new PolychatServerIdString(request.Message.NewPlayersOnline.ServerId);
                var sanitisedId = serverId.ToSanitisedUppercase();
                var server      = _polychatService.GetOnlineServerOrDefault(sanitisedId);

                if (server is null)
                {
                    throw new KeyNotFoundException($"Could not find server {sanitisedId} in the list of online servers");
                }

                var playersOnline  = request.Message.NewPlayersOnline.PlayersOnline;
                var newPlayersList = request.Message.NewPlayersOnline.PlayerNames.ToList();

                if (request.Message.NewPlayerStatus is ServerPlayerStatusChangedEvent.Types.PlayerStatus.Left &&
                    newPlayersList.Contains(request.Message.PlayerUsername)
                    )
                {
                    newPlayersList.Remove(request.Message.PlayerUsername);
                    playersOnline = playersOnline == 0 ? playersOnline : playersOnline - 1;
                }
                else if (request.Message.NewPlayerStatus is ServerPlayerStatusChangedEvent.Types.PlayerStatus.Joined &&
                         !newPlayersList.Contains(request.Message.PlayerUsername)
                         )
                {
                    newPlayersList.Add(request.Message.PlayerUsername);
                    playersOnline += 1;
                }

                server.PlayersOnline     = playersOnline;
                server.OnlinePlayerNames = newPlayersList;

                _polychatService.AddOrUpdateOnlineServer(sanitisedId, server);
                await _polychatService.ForwardMessage(sanitisedId, request.Message);

                var messageStr = new PolychatChatMessageString(
                    sanitisedId,
                    $"{request.Message.PlayerUsername} has {request.Message.NewPlayerStatus.ToString().ToLower()} the game.");
                var getChatChannelResult =
                    await _channelApi.GetChannelAsync(new(_polychatSettings.ChatChannelId), cancellationToken);

                if (!getChatChannelResult.IsSuccess)
                {
                    throw new Exception(getChatChannelResult.Error.Message);
                }

                var sendMessageResult = await _channelApi.CreateMessageAsync(
                    new(_polychatSettings.ChatChannelId),
                    messageStr.ToDiscordFormattedString(),
                    ct : cancellationToken);

                if (!sendMessageResult.IsSuccess)
                {
                    throw new Exception(getChatChannelResult.Error?.Message ?? "Could not forward message to Discord.");
                }
            }
            protected override void Handle(TcpRequest <ServerPlayersOnline> request)
            {
                var serverId    = new PolychatServerIdString(request.Message.ServerId);
                var sanitisedId = serverId.ToSanitisedUppercase();
                var server      = _polychatService.GetOnlineServerOrDefault(sanitisedId);

                if (server is null)
                {
                    throw new KeyNotFoundException($"Could not find server {sanitisedId} in the list of online servers");
                }

                server.PlayersOnline     = request.Message.PlayersOnline;
                server.OnlinePlayerNames = request.Message.PlayerNames.ToList();

                _polychatService.AddOrUpdateOnlineServer(sanitisedId, server);
            }
Пример #6
0
    protected override async Task OnExecute(CancellationToken ct)
    {
        var upcomingRestarts = await _mediator.Send(new GetUpcoming.Query(), ct);

        foreach (var(serverId, job) in upcomingRestarts)
        {
            var server = _ps.GetOnlineServerOrDefault(serverId);

            if (server is null)
            {
                _logger.LogWarning("Server {ServerId} scheduled to restart was already offline", serverId);
                return;
            }

            await _mediator.Send(new Notify.Command(server, job.NextExecution !.Value - DateTime.UtcNow), ct);
        }
    }
    public async Task Execute(string serverId)
    {
        var server = _polychatService.GetOnlineServerOrDefault(serverId);

        if (server is null)
        {
            _logger.LogWarning("Server {ServerId} scheduled to restart was already offline", serverId);
            return;
        }

        for (var i = 5; i > 0; i--)
        {
            await _mediator.Send(new Notify.Command(server, TimeSpan.FromSeconds(i)));

            await Task.Delay(1000);
        }

        await _mediator.Send(new SendRestartCommand.Command(serverId, new(_settings.ChatChannelId)));

        _telemetryClient?.TrackEvent("SERVER_RESTART", new Dictionary <string, string> {
            ["ServerID"] = serverId
        });
    }
Пример #8
0
        /// <inheritdoc />
        public async Task <Result <MemberApplication> > Handle(Command request, CancellationToken cancellationToken)
        {
            var app = await _context.MemberApplications
                      .FirstOrDefaultAsync(
                a => a.MemberApplicationId == request.Id && a.GuildId == request.GuildId.Value,
                cancellationToken);

            if (app is null)
            {
                return(new NotFoundError($"Application with ID `{request.Id}` does not exist"));
            }

            var getRoles = await _guildApi.GetGuildRolesAsync(request.GuildId, cancellationToken);

            if (!getRoles.IsSuccess)
            {
                return(Result <MemberApplication> .FromError(getRoles.Error));
            }

            var role = getRoles.Entity
                       .FirstOrDefault(r =>
                                       r.Name.Contains($"[{request.ServerPrefix.ToUpper()}]"));

            if (role is null)
            {
                return(new NotFoundError(
                           $"Could not find a role corresponding to the server prefix: `{request.ServerPrefix}`."));
            }

            var userId = new Snowflake(app.AuthorDiscordId);
            var getUserToPromoteResult =
                await _guildApi.GetGuildMemberAsync(request.GuildId, userId, cancellationToken);

            if (!getUserToPromoteResult.IsSuccess)
            {
                return(Result <MemberApplication> .FromError(getUserToPromoteResult.Error));
            }
            if (getUserToPromoteResult.Entity is null)
            {
                return(new NotFoundError($"Could not find a user with ID: `{app.AuthorDiscordId}`."));
            }

            foreach (var ign in request.Igns)
            {
                var proto = new GenericCommand
                {
                    DiscordChannelId   = request.ChannelId.ToString(),
                    DiscordCommandName = "promote",
                    DefaultCommand     = "ranks add $1 member",
                    Args = { ign }
                };
                var id     = request.ServerPrefix.ToUpperInvariant();
                var server = _ps.GetOnlineServerOrDefault(id);

                if (server is null)
                {
                    return(Result <MemberApplication> .FromError(
                               new NotFoundError($"Could not find server with ID {id}")));
                }

                await _ps.SendMessage(server, proto);
            }

            var addRoleResult =
                await _guildApi.AddGuildMemberRoleAsync(request.GuildId, userId, role.ID, new(), cancellationToken);

            if (!addRoleResult.IsSuccess)
            {
                return(Result <MemberApplication> .FromError(addRoleResult));
            }

            app.AppStatus = ApplicationStatus.Approved;
            await _context.SaveChangesAsync(cancellationToken);

            return(Result <MemberApplication> .FromSuccess(app));
        }