aboutsummaryrefslogtreecommitdiff
path: root/mod/src/main/java/moe/ymc/acron/cmd/CmdResConsumer.java
blob: 36f76059d7d7794bd7992cc0e3d1a4d6cfdb58c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package moe.ymc.acron.cmd;

import com.mojang.brigadier.ResultConsumer;
import com.mojang.brigadier.context.CommandContext;
import io.netty.channel.Channel;
import moe.ymc.acron.s2c.response.EventCmdRes;
import moe.ymc.acron.serialization.Serializer;
import net.minecraft.server.command.ServerCommandSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;

public class CmdResConsumer implements ResultConsumer<ServerCommandSource> {
    private static final Logger LOGGER = LogManager.getLogger();

    private final @NotNull Channel channel;
    private final int id;

    private boolean hasResult;

    public CmdResConsumer(@NotNull Channel channel,
                  int id) {
        this.channel = channel;
        this.id = id;
    }

    @Override
    public void onCommandComplete(CommandContext<ServerCommandSource> context, boolean success, int result) {
        LOGGER.debug("onCommandComplete[{}]: {} {}",
                id,
                success,
                result);
        // Ignore any failed results because CommandDispatcher#execute does not reliably send error
        // results to the consumer.
        // For example, fail results are either not sent at all (pre-processing errors), or
        // sent before writing the result, which both violates the spec.
        // We will send the failed results in a custom mixin.
        if (success) {
            hasResult = true;
            channel.writeAndFlush(Serializer.serialize(new EventCmdRes(id, success, result)));
        }
    }

    public void sendResultIfNot() {
        if (!hasResult) {
            channel.writeAndFlush(Serializer.serialize(new EventCmdRes(id, false, -1)));
        }
    }
}