CommandMap.java 10 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;
Melledy's avatar
Melledy committed
5
6
import emu.grasscutter.game.player.Player;

KingRainbow44's avatar
KingRainbow44 committed
7
8
9
10
import org.reflections.Reflections;

import java.util.*;

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

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

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

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

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

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

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

    /**
     * Removes a registered command handler.
Jaida Wu's avatar
Jaida Wu committed
57
     *
KingRainbow44's avatar
KingRainbow44 committed
58
59
60
61
     * @param label The command label.
     * @return Instance chaining.
     */
    public CommandMap unregisterCommand(String label) {
62
63
        Grasscutter.getLogger().debug("Unregistered command: " + label);
        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.commands.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
84
85
86
    public List<Command> getAnnotationsAsList() { return new LinkedList<>(this.annotations.values()); }

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

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

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

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

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

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

KingRainbow44's avatar
KingRainbow44 committed
165
166
        // Get command handler.
        CommandHandler handler = this.commands.get(label);
Jaida Wu's avatar
Jaida Wu committed
167
        if (handler == null) {
168
            CommandHandler.sendTranslatedMessage(player, "commands.generic.unknown_command", label);
Jaida Wu's avatar
Jaida Wu committed
169
            return;
KingRainbow44's avatar
KingRainbow44 committed
170
        }
Jaida Wu's avatar
Jaida Wu committed
171

172
        // If any @UID argument is present, override targetPlayer with it.
AnimeGitB's avatar
AnimeGitB committed
173
174
        for (int i = 0; i < args.size(); i++) {
            String arg = args.get(i);
175
            if (arg.startsWith("@")) {
AnimeGitB's avatar
AnimeGitB committed
176
177
178
                arg = args.remove(i).substring(1);
                try {
                    int uid = Integer.parseInt(arg);
179
                    targetPlayer = Grasscutter.getGameServer().getPlayerByUid(uid, true);
AnimeGitB's avatar
AnimeGitB committed
180
                    if (targetPlayer == null) {
181
                        CommandHandler.sendTranslatedMessage(player, "commands.execution.player_exist_error");
AnimeGitB's avatar
AnimeGitB committed
182
183
184
185
                        return;
                    }
                    break;
                } catch (NumberFormatException e) {
186
                    CommandHandler.sendTranslatedMessage(player, "commands.execution.uid_error");
AnimeGitB's avatar
AnimeGitB committed
187
188
189
190
                    return;
                }
            }
        }
191
        
AnimeGitB's avatar
AnimeGitB committed
192
193
        // If there's still no targetPlayer at this point, use previously-set target
        if (targetPlayer == null) {
AnimeGitB's avatar
AnimeGitB committed
194
            if (targetPlayerIds.containsKey(playerId)) {
195
                targetPlayer = Grasscutter.getGameServer().getPlayerByUid(targetPlayerIds.get(playerId), true);  // We check every time in case the target is deleted after being targeted
AnimeGitB's avatar
AnimeGitB committed
196
                if (targetPlayer == null) {
197
                    CommandHandler.sendTranslatedMessage(player, "commands.execution.player_exist_error");
AnimeGitB's avatar
AnimeGitB committed
198
199
200
                    return;
                }
            } else {
201
202
                // If there's still no targetPlayer at this point, use executor.
                targetPlayer = player;
AnimeGitB's avatar
AnimeGitB committed
203
            }
AnimeGitB's avatar
AnimeGitB committed
204
205
        }

4Benj_'s avatar
4Benj_ committed
206
207
208
        // Check for permissions.
        if (!Grasscutter.getPermissionHandler().checkPermission(player, targetPlayer, this.annotations.get(label).permission(), this.annotations.get(label).permissionTargeted())) {
            return;
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
        }

        // Check if command has unfulfilled constraints on targetPlayer
        Command.TargetRequirement targetRequirement = this.annotations.get(label).targetRequirement();
        if (targetRequirement != Command.TargetRequirement.NONE) {
            if (targetPlayer == null) {
                CommandHandler.sendTranslatedMessage(player, "commands.execution.need_target");
                return;
            }
            if ((targetRequirement == Command.TargetRequirement.ONLINE) && !targetPlayer.isOnline()) {
                CommandHandler.sendTranslatedMessage(player, "commands.execution.need_target_online");
                return;
            }
            if ((targetRequirement == Command.TargetRequirement.OFFLINE) && targetPlayer.isOnline()) {
                CommandHandler.sendTranslatedMessage(player, "commands.execution.need_target_offline");
Jaida Wu's avatar
Jaida Wu committed
224
                return;
225
226
            }
        }
Jaida Wu's avatar
Jaida Wu committed
227

KingRainbow44's avatar
KingRainbow44 committed
228
        // Invoke execute method for handler.
BaiSugar's avatar
BaiSugar committed
229
        boolean threading  = this.annotations.get(label).threading();
AnimeGitB's avatar
AnimeGitB committed
230
231
        final Player targetPlayerF = targetPlayer;  // Is there a better way to do this?
        Runnable runnable = () -> handler.execute(player, targetPlayerF, args);
BaiSugar's avatar
BaiSugar committed
232
        if(threading) {
233
234
            new Thread(runnable).start();
        } else {
BaiSugar's avatar
BaiSugar committed
235
236
            runnable.run();
        }
KingRainbow44's avatar
KingRainbow44 committed
237
238
239
240
241
242
243
    }

    /**
     * Scans for all classes annotated with {@link Command} and registers them.
     */
    private void scan() {
        Reflections reflector = Grasscutter.reflector;
244
        Set<Class<?>> classes = reflector.getTypesAnnotatedWith(Command.class);
KingRainbow44's avatar
KingRainbow44 committed
245
246
        classes.forEach(annotated -> {
            try {
247
248
                Command cmdData = annotated.getAnnotation(Command.class);
                Object object = annotated.newInstance();
KingRainbow44's avatar
KingRainbow44 committed
249
250
                if (object instanceof CommandHandler)
                    this.registerCommand(cmdData.label(), (CommandHandler) object);
251
252
253
254
                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
255
256
257
        });
    }
}