CommandMap.java 10.4 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;
Melledy's avatar
Melledy committed
4
import emu.grasscutter.game.player.Player;
KingRainbow44's avatar
KingRainbow44 committed
5
6
7
8
import org.reflections.Reflections;

import java.util.*;

Jaida Wu's avatar
Jaida Wu committed
9
@SuppressWarnings({"UnusedReturnValue", "unused"})
KingRainbow44's avatar
KingRainbow44 committed
10
public final class CommandMap {
Jaida Wu's avatar
Jaida Wu committed
11
    private final Map<String, CommandHandler> commands = new HashMap<>();
12
    private final Map<String, CommandHandler> aliases = new HashMap<>();
Jaida Wu's avatar
Jaida Wu committed
13
    private final Map<String, Command> annotations = new HashMap<>();
AnimeGitB's avatar
AnimeGitB committed
14
    private final Map<String, Integer> targetPlayerIds = new HashMap<>();
AnimeGitB's avatar
AnimeGitB committed
15
    private static final String consoleId = "console";
4Benj_'s avatar
4Benj_ committed
16

Jaida Wu's avatar
Jaida Wu committed
17
18
19
20
21
22
23
24
    public CommandMap() {
        this(false);
    }

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

KingRainbow44's avatar
KingRainbow44 committed
25
26
27
28
29
30
    public static CommandMap getInstance() {
        return Grasscutter.getGameServer().getCommandMap();
    }

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

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

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

    /**
     * Removes a registered command handler.
Jaida Wu's avatar
Jaida Wu committed
56
     *
KingRainbow44's avatar
KingRainbow44 committed
57
58
59
60
     * @param label The command label.
     * @return Instance chaining.
     */
    public CommandMap unregisterCommand(String label) {
61
        Grasscutter.getLogger().debug("Unregistered command: " + label);
62

63
        CommandHandler handler = this.commands.get(label);
Jaida Wu's avatar
Jaida Wu committed
64
65
        if (handler == null) return this;

66
        Command annotation = handler.getClass().getAnnotation(Command.class);
67
        this.annotations.remove(label);
KingRainbow44's avatar
KingRainbow44 committed
68
        this.commands.remove(label);
Jaida Wu's avatar
Jaida Wu committed
69

KingRainbow44's avatar
KingRainbow44 committed
70
        // Unregister aliases.
Jaida Wu's avatar
Jaida Wu committed
71
        if (annotation.aliases().length > 0) {
KingRainbow44's avatar
KingRainbow44 committed
72
            for (String alias : annotation.aliases()) {
73
                this.aliases.remove(alias);
74
                this.annotations.remove(alias);
KingRainbow44's avatar
KingRainbow44 committed
75
76
            }
        }
Jaida Wu's avatar
Jaida Wu committed
77

78
        return this;
KingRainbow44's avatar
KingRainbow44 committed
79
80
    }

81
82
83
    public List<Command> getAnnotationsAsList() {
        return new LinkedList<>(this.annotations.values());
    }
84
85
86
87
88

    public HashMap<String, Command> getAnnotations() {
        return new LinkedHashMap<>(this.annotations);
    }

KingRainbow44's avatar
KingRainbow44 committed
89
90
    /**
     * Returns a list of all registered commands.
Jaida Wu's avatar
Jaida Wu committed
91
     *
KingRainbow44's avatar
KingRainbow44 committed
92
93
     * @return All command handlers as a list.
     */
94
    public List<CommandHandler> getHandlersAsList() {
KingRainbow44's avatar
KingRainbow44 committed
95
96
97
        return new LinkedList<>(this.commands.values());
    }

Jaida Wu's avatar
Jaida Wu committed
98
99
100
    public HashMap<String, CommandHandler> getHandlers() {
        return new LinkedHashMap<>(this.commands);
    }
101

KingRainbow44's avatar
KingRainbow44 committed
102
103
    /**
     * Returns a handler by label/alias.
Jaida Wu's avatar
Jaida Wu committed
104
     *
KingRainbow44's avatar
KingRainbow44 committed
105
106
107
108
109
110
111
     * @param label The command label.
     * @return The command handler.
     */
    public CommandHandler getHandler(String label) {
        return this.commands.get(label);
    }

KingRainbow44's avatar
KingRainbow44 committed
112
113
    /**
     * Invoke a command handler with the given arguments.
Jaida Wu's avatar
Jaida Wu committed
114
115
     *
     * @param player     The player invoking the command or null for the server console.
KingRainbow44's avatar
KingRainbow44 committed
116
117
     * @param rawMessage The messaged used to invoke the command.
     */
AnimeGitB's avatar
AnimeGitB committed
118
    public void invoke(Player player, Player targetPlayer, String rawMessage) {
119
        rawMessage = rawMessage.trim();
BaiSugar's avatar
BaiSugar committed
120
        if (rawMessage.length() == 0) {
121
            CommandHandler.sendTranslatedMessage(player, "commands.generic.not_specified");
BaiSugar's avatar
BaiSugar committed
122
            return;
123
        }
Jaida Wu's avatar
Jaida Wu committed
124

KingRainbow44's avatar
KingRainbow44 committed
125
126
        // Parse message.
        String[] split = rawMessage.split(" ");
127
        List<String> args = new LinkedList<>(Arrays.asList(split));
KingRainbow44's avatar
KingRainbow44 committed
128
        String label = args.remove(0);
AnimeGitB's avatar
AnimeGitB committed
129
        String playerId = (player == null) ? consoleId : player.getAccount().getId();
130

131
        // Check for special cases - currently only target command.
AnimeGitB's avatar
AnimeGitB committed
132
        String targetUidStr = null;
133
        if (label.startsWith("@")) { // @[UID]
AnimeGitB's avatar
AnimeGitB committed
134
            targetUidStr = label.substring(1);
135
        } else if (label.equalsIgnoreCase("target")) { // target [[@]UID]
AnimeGitB's avatar
AnimeGitB committed
136
137
138
139
140
141
142
            if (args.size() > 0) {
                targetUidStr = args.get(0);
                if (targetUidStr.startsWith("@")) {
                    targetUidStr = targetUidStr.substring(1);
                }
            } else {
                targetUidStr = "";
AnimeGitB's avatar
AnimeGitB committed
143
144
            }
        }
AnimeGitB's avatar
AnimeGitB committed
145
        if (targetUidStr != null) {
146
            if (targetUidStr.equals("")) { // Clears the default targetPlayer.
147
                this.targetPlayerIds.remove(playerId);
148
                CommandHandler.sendTranslatedMessage(player, "commands.execution.clear_target");
149
            } else { // Sets default targetPlayer to the UID provided.
AnimeGitB's avatar
AnimeGitB committed
150
151
                try {
                    int uid = Integer.parseInt(targetUidStr);
152
                    targetPlayer = Grasscutter.getGameServer().getPlayerByUid(uid, true);
AnimeGitB's avatar
AnimeGitB committed
153
                    if (targetPlayer == null) {
154
                        CommandHandler.sendTranslatedMessage(player, "commands.execution.player_exist_error");
AnimeGitB's avatar
AnimeGitB committed
155
                    } else {
156
                        this.targetPlayerIds.put(playerId, uid);
157
                        CommandHandler.sendTranslatedMessage(player, "commands.execution.set_target", targetUidStr);
158
                        CommandHandler.sendTranslatedMessage(player, targetPlayer.isOnline() ? "commands.execution.set_target_online" : "commands.execution.set_target_offline", targetUidStr);
AnimeGitB's avatar
AnimeGitB committed
159
160
                    }
                } catch (NumberFormatException e) {
161
                    CommandHandler.sendTranslatedMessage(player, "commands.execution.uid_error");
AnimeGitB's avatar
AnimeGitB committed
162
163
                }
            }
164
            return;
AnimeGitB's avatar
AnimeGitB committed
165
        }
AnimeGitB's avatar
AnimeGitB committed
166

KingRainbow44's avatar
KingRainbow44 committed
167
168
        // Get command handler.
        CommandHandler handler = this.commands.get(label);
169
170
171
172
173
        if(handler == null)
            // Try to get the handler by alias.
            handler = this.aliases.get(label);

        // Check if the handler is still null.
Jaida Wu's avatar
Jaida Wu committed
174
        if (handler == null) {
175
            CommandHandler.sendTranslatedMessage(player, "commands.generic.unknown_command", label);
Jaida Wu's avatar
Jaida Wu committed
176
            return;
KingRainbow44's avatar
KingRainbow44 committed
177
        }
Jaida Wu's avatar
Jaida Wu committed
178

179
180
181
        // Get the command's annotation.
        Command annotation = this.annotations.get(label);

182
        // If any @UID argument is present, override targetPlayer with it.
AnimeGitB's avatar
AnimeGitB committed
183
184
        for (int i = 0; i < args.size(); i++) {
            String arg = args.get(i);
185
            if (arg.startsWith("@")) {
AnimeGitB's avatar
AnimeGitB committed
186
187
188
                arg = args.remove(i).substring(1);
                try {
                    int uid = Integer.parseInt(arg);
189
                    targetPlayer = Grasscutter.getGameServer().getPlayerByUid(uid, true);
AnimeGitB's avatar
AnimeGitB committed
190
                    if (targetPlayer == null) {
191
                        CommandHandler.sendTranslatedMessage(player, "commands.execution.player_exist_error");
AnimeGitB's avatar
AnimeGitB committed
192
193
194
195
                        return;
                    }
                    break;
                } catch (NumberFormatException e) {
196
                    CommandHandler.sendTranslatedMessage(player, "commands.execution.uid_error");
AnimeGitB's avatar
AnimeGitB committed
197
198
199
200
                    return;
                }
            }
        }
201

AnimeGitB's avatar
AnimeGitB committed
202
203
        // If there's still no targetPlayer at this point, use previously-set target
        if (targetPlayer == null) {
204
205
            if (this.targetPlayerIds.containsKey(playerId)) {
                targetPlayer = Grasscutter.getGameServer().getPlayerByUid(this.targetPlayerIds.get(playerId), true);  // We check every time in case the target is deleted after being targeted
AnimeGitB's avatar
AnimeGitB committed
206
                if (targetPlayer == null) {
207
                    CommandHandler.sendTranslatedMessage(player, "commands.execution.player_exist_error");
AnimeGitB's avatar
AnimeGitB committed
208
209
210
                    return;
                }
            } else {
211
212
                // If there's still no targetPlayer at this point, use executor.
                targetPlayer = player;
AnimeGitB's avatar
AnimeGitB committed
213
            }
AnimeGitB's avatar
AnimeGitB committed
214
215
        }

4Benj_'s avatar
4Benj_ committed
216
        // Check for permissions.
217
        if (!Grasscutter.getPermissionHandler().checkPermission(player, targetPlayer, annotation.permission(), this.annotations.get(label).permissionTargeted())) {
4Benj_'s avatar
4Benj_ committed
218
            return;
219
220
221
        }

        // Check if command has unfulfilled constraints on targetPlayer
222
        Command.TargetRequirement targetRequirement = annotation.targetRequirement();
223
224
        if (targetRequirement != Command.TargetRequirement.NONE) {
            if (targetPlayer == null) {
225
                CommandHandler.sendTranslatedMessage(null, "commands.execution.need_target");
226
227
                return;
            }
228

229
230
231
232
            if ((targetRequirement == Command.TargetRequirement.ONLINE) && !targetPlayer.isOnline()) {
                CommandHandler.sendTranslatedMessage(player, "commands.execution.need_target_online");
                return;
            }
233

234
235
            if ((targetRequirement == Command.TargetRequirement.OFFLINE) && targetPlayer.isOnline()) {
                CommandHandler.sendTranslatedMessage(player, "commands.execution.need_target_offline");
Jaida Wu's avatar
Jaida Wu committed
236
                return;
237
238
            }
        }
Jaida Wu's avatar
Jaida Wu committed
239

240
241
242
243
        // Copy player and handler to final properties.
        final Player targetPlayerF = targetPlayer; // Is there a better way to do this?
        final CommandHandler handlerF = handler; // Is there a better way to do this?

KingRainbow44's avatar
KingRainbow44 committed
244
        // Invoke execute method for handler.
245
246
        Runnable runnable = () -> handlerF.execute(player, targetPlayerF, args);
        if (annotation.threading()) {
247
248
            new Thread(runnable).start();
        } else {
BaiSugar's avatar
BaiSugar committed
249
250
            runnable.run();
        }
KingRainbow44's avatar
KingRainbow44 committed
251
252
253
254
255
256
257
    }

    /**
     * Scans for all classes annotated with {@link Command} and registers them.
     */
    private void scan() {
        Reflections reflector = Grasscutter.reflector;
258
        Set<Class<?>> classes = reflector.getTypesAnnotatedWith(Command.class);
259

KingRainbow44's avatar
KingRainbow44 committed
260
261
        classes.forEach(annotated -> {
            try {
262
                Command cmdData = annotated.getAnnotation(Command.class);
263
                Object object = annotated.getDeclaredConstructor().newInstance();
KingRainbow44's avatar
KingRainbow44 committed
264
265
                if (object instanceof CommandHandler)
                    this.registerCommand(cmdData.label(), (CommandHandler) object);
266
267
268
269
                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
270
271
272
        });
    }
}