CommandMap.java 5.5 KB
Newer Older
Jaida Wu's avatar
Jaida Wu committed
1
package emu.grasscutter.command;
KingRainbow44's avatar
KingRainbow44 committed
2
3

import emu.grasscutter.Grasscutter;
4
import emu.grasscutter.game.Account;
KingRainbow44's avatar
KingRainbow44 committed
5
6
7
8
9
import emu.grasscutter.game.GenshinPlayer;
import org.reflections.Reflections;

import java.util.*;

Jaida Wu's avatar
Jaida Wu committed
10
@SuppressWarnings({"UnusedReturnValue", "unused"})
KingRainbow44's avatar
KingRainbow44 committed
11
public final class CommandMap {
Jaida Wu's avatar
Jaida Wu committed
12
13
14
15
16
17
18
19
20
21
    private final Map<String, CommandHandler> commands = new HashMap<>();
    private final Map<String, Command> annotations = new HashMap<>();
    public CommandMap() {
        this(false);
    }

    public CommandMap(boolean scan) {
        if (scan) this.scan();
    }

KingRainbow44's avatar
KingRainbow44 committed
22
23
24
25
26
27
    public static CommandMap getInstance() {
        return Grasscutter.getGameServer().getCommandMap();
    }

    /**
     * Register a command handler.
Jaida Wu's avatar
Jaida Wu committed
28
29
     *
     * @param label   The command label.
KingRainbow44's avatar
KingRainbow44 committed
30
31
32
33
     * @param command The command handler.
     * @return Instance chaining.
     */
    public CommandMap registerCommand(String label, CommandHandler command) {
34
        Grasscutter.getLogger().debug("Registered command: " + label);
Jaida Wu's avatar
Jaida Wu committed
35

KingRainbow44's avatar
KingRainbow44 committed
36
        // Get command data.
37
        Command annotation = command.getClass().getAnnotation(Command.class);
38
        this.annotations.put(label, annotation);
KingRainbow44's avatar
KingRainbow44 committed
39
        this.commands.put(label, command);
Jaida Wu's avatar
Jaida Wu committed
40

KingRainbow44's avatar
KingRainbow44 committed
41
        // Register aliases.
Jaida Wu's avatar
Jaida Wu committed
42
        if (annotation.aliases().length > 0) {
KingRainbow44's avatar
KingRainbow44 committed
43
            for (String alias : annotation.aliases()) {
44
                this.commands.put(alias, command);
45
                this.annotations.put(alias, annotation);
KingRainbow44's avatar
KingRainbow44 committed
46
            }
Jaida Wu's avatar
Jaida Wu committed
47
48
        }
        return this;
KingRainbow44's avatar
KingRainbow44 committed
49
50
51
52
    }

    /**
     * Removes a registered command handler.
Jaida Wu's avatar
Jaida Wu committed
53
     *
KingRainbow44's avatar
KingRainbow44 committed
54
55
56
57
     * @param label The command label.
     * @return Instance chaining.
     */
    public CommandMap unregisterCommand(String label) {
58
59
        Grasscutter.getLogger().debug("Unregistered command: " + label);
        CommandHandler handler = this.commands.get(label);
Jaida Wu's avatar
Jaida Wu committed
60
61
        if (handler == null) return this;

62
        Command annotation = handler.getClass().getAnnotation(Command.class);
63
        this.annotations.remove(label);
KingRainbow44's avatar
KingRainbow44 committed
64
        this.commands.remove(label);
Jaida Wu's avatar
Jaida Wu committed
65

KingRainbow44's avatar
KingRainbow44 committed
66
        // Unregister aliases.
Jaida Wu's avatar
Jaida Wu committed
67
        if (annotation.aliases().length > 0) {
KingRainbow44's avatar
KingRainbow44 committed
68
            for (String alias : annotation.aliases()) {
69
                this.commands.remove(alias);
70
                this.annotations.remove(alias);
KingRainbow44's avatar
KingRainbow44 committed
71
72
            }
        }
Jaida Wu's avatar
Jaida Wu committed
73

74
        return this;
KingRainbow44's avatar
KingRainbow44 committed
75
76
    }

KingRainbow44's avatar
KingRainbow44 committed
77
78
    /**
     * Returns a list of all registered commands.
Jaida Wu's avatar
Jaida Wu committed
79
     *
KingRainbow44's avatar
KingRainbow44 committed
80
81
     * @return All command handlers as a list.
     */
82
    public List<CommandHandler> getHandlersAsList() {
KingRainbow44's avatar
KingRainbow44 committed
83
84
85
        return new LinkedList<>(this.commands.values());
    }

Jaida Wu's avatar
Jaida Wu committed
86
87
88
    public HashMap<String, CommandHandler> getHandlers() {
        return new LinkedHashMap<>(this.commands);
    }
89

KingRainbow44's avatar
KingRainbow44 committed
90
91
    /**
     * Returns a handler by label/alias.
Jaida Wu's avatar
Jaida Wu committed
92
     *
KingRainbow44's avatar
KingRainbow44 committed
93
94
95
96
97
98
99
     * @param label The command label.
     * @return The command handler.
     */
    public CommandHandler getHandler(String label) {
        return this.commands.get(label);
    }

KingRainbow44's avatar
KingRainbow44 committed
100
101
    /**
     * Invoke a command handler with the given arguments.
Jaida Wu's avatar
Jaida Wu committed
102
103
     *
     * @param player     The player invoking the command or null for the server console.
KingRainbow44's avatar
KingRainbow44 committed
104
105
106
     * @param rawMessage The messaged used to invoke the command.
     */
    public void invoke(GenshinPlayer player, String rawMessage) {
107
        rawMessage = rawMessage.trim();
BaiSugar's avatar
BaiSugar committed
108
109
110
        if (rawMessage.length() == 0) {
            CommandHandler.sendMessage(player, "No command specified.");
            return;
111
        }
Jaida Wu's avatar
Jaida Wu committed
112

KingRainbow44's avatar
KingRainbow44 committed
113
        // Remove prefix if present.
Jaida Wu's avatar
Jaida Wu committed
114
        if (!Character.isLetter(rawMessage.charAt(0)))
KingRainbow44's avatar
KingRainbow44 committed
115
            rawMessage = rawMessage.substring(1);
Jaida Wu's avatar
Jaida Wu committed
116

KingRainbow44's avatar
KingRainbow44 committed
117
118
        // Parse message.
        String[] split = rawMessage.split(" ");
119
        List<String> args = new LinkedList<>(Arrays.asList(split));
KingRainbow44's avatar
KingRainbow44 committed
120
121
122
        String label = args.remove(0);
        // Get command handler.
        CommandHandler handler = this.commands.get(label);
Jaida Wu's avatar
Jaida Wu committed
123
124
125
        if (handler == null) {
            CommandHandler.sendMessage(player, "Unknown command: " + label);
            return;
KingRainbow44's avatar
KingRainbow44 committed
126
        }
Jaida Wu's avatar
Jaida Wu committed
127

128
        // Check for permission.
Jaida Wu's avatar
Jaida Wu committed
129
        if (player != null) {
130
131
            String permissionNode = this.annotations.get(label).permission();
            Account account = player.getAccount();
BaiSugar's avatar
BaiSugar committed
132
            if (!permissionNode.isEmpty() && !account.hasPermission(permissionNode)) {
Jaida Wu's avatar
Jaida Wu committed
133
134
                CommandHandler.sendMessage(player, "You do not have permission to run this command.");
                return;
135
136
            }
        }
Jaida Wu's avatar
Jaida Wu committed
137

KingRainbow44's avatar
KingRainbow44 committed
138
        // Invoke execute method for handler.
BaiSugar's avatar
BaiSugar committed
139
140
141
142
143
144
145
146
147
        boolean threading  = this.annotations.get(label).threading();
        Runnable runnable = () -> handler.execute(player, args);
        if(threading) {
            Thread command = new Thread(runnable);
            command.start();
        }
        else {
            runnable.run();
        }
KingRainbow44's avatar
KingRainbow44 committed
148
149
150
151
152
153
154
    }

    /**
     * Scans for all classes annotated with {@link Command} and registers them.
     */
    private void scan() {
        Reflections reflector = Grasscutter.reflector;
155
        Set<Class<?>> classes = reflector.getTypesAnnotatedWith(Command.class);
KingRainbow44's avatar
KingRainbow44 committed
156
157
        classes.forEach(annotated -> {
            try {
158
159
                Command cmdData = annotated.getAnnotation(Command.class);
                Object object = annotated.newInstance();
KingRainbow44's avatar
KingRainbow44 committed
160
161
                if (object instanceof CommandHandler)
                    this.registerCommand(cmdData.label(), (CommandHandler) object);
162
163
164
165
                else Grasscutter.getLogger().error("Class " + annotated.getName() + " is not a CommandHandler!");
            } catch (Exception exception) {
                Grasscutter.getLogger().error("Failed to register command handler for " + annotated.getSimpleName(), exception);
            }
KingRainbow44's avatar
KingRainbow44 committed
166
167
168
        });
    }
}