CommandMap.java 9.45 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.*;

11
12
import static emu.grasscutter.utils.Language.translate;

Jaida Wu's avatar
Jaida Wu committed
13
@SuppressWarnings({"UnusedReturnValue", "unused"})
KingRainbow44's avatar
KingRainbow44 committed
14
public final class CommandMap {
Jaida Wu's avatar
Jaida Wu committed
15
16
    private final Map<String, CommandHandler> commands = new HashMap<>();
    private final Map<String, Command> annotations = new HashMap<>();
AnimeGitB's avatar
AnimeGitB committed
17
    private final Map<String, Integer> targetPlayerIds = new HashMap<>();
AnimeGitB's avatar
AnimeGitB committed
18
    private static final String consoleId = "console";
Jaida Wu's avatar
Jaida Wu committed
19
20
21
22
23
24
25
26
    public CommandMap() {
        this(false);
    }

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

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

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

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

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

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

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

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

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

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

Jaida Wu's avatar
Jaida Wu committed
91
92
93
    public HashMap<String, CommandHandler> getHandlers() {
        return new LinkedHashMap<>(this.commands);
    }
94

KingRainbow44's avatar
KingRainbow44 committed
95
96
    /**
     * Returns a handler by label/alias.
Jaida Wu's avatar
Jaida Wu committed
97
     *
KingRainbow44's avatar
KingRainbow44 committed
98
99
100
101
102
103
104
     * @param label The command label.
     * @return The command handler.
     */
    public CommandHandler getHandler(String label) {
        return this.commands.get(label);
    }

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

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

KingRainbow44's avatar
KingRainbow44 committed
159
160
        // Get command handler.
        CommandHandler handler = this.commands.get(label);
Jaida Wu's avatar
Jaida Wu committed
161
        if (handler == null) {
162
            CommandHandler.sendMessage(player, translate("commands.generic.unknown_command", label));
Jaida Wu's avatar
Jaida Wu committed
163
            return;
KingRainbow44's avatar
KingRainbow44 committed
164
        }
Jaida Wu's avatar
Jaida Wu committed
165

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

200
        // Check for permission.
Jaida Wu's avatar
Jaida Wu committed
201
        if (player != null) {
202
            String permissionNode = this.annotations.get(label).permission();
AnimeGitB's avatar
AnimeGitB committed
203
            String permissionNodeTargeted = this.annotations.get(label).permissionTargeted();
204
            Account account = player.getAccount();
AnimeGitB's avatar
AnimeGitB committed
205
206
            if (player != targetPlayer) {  // Additional permission required for targeting another player
                if (!permissionNodeTargeted.isEmpty() && !account.hasPermission(permissionNodeTargeted)) {
207
                    CommandHandler.sendMessage(player, translate("commands.generic.permission_error"));
AnimeGitB's avatar
AnimeGitB committed
208
209
210
                    return;
                }
            }
BaiSugar's avatar
BaiSugar committed
211
            if (!permissionNode.isEmpty() && !account.hasPermission(permissionNode)) {
212
                CommandHandler.sendMessage(player, translate("commands.generic.permission_error"));
Jaida Wu's avatar
Jaida Wu committed
213
                return;
214
215
            }
        }
Jaida Wu's avatar
Jaida Wu committed
216

KingRainbow44's avatar
KingRainbow44 committed
217
        // Invoke execute method for handler.
BaiSugar's avatar
BaiSugar committed
218
        boolean threading  = this.annotations.get(label).threading();
AnimeGitB's avatar
AnimeGitB committed
219
220
        final Player targetPlayerF = targetPlayer;  // Is there a better way to do this?
        Runnable runnable = () -> handler.execute(player, targetPlayerF, args);
BaiSugar's avatar
BaiSugar committed
221
        if(threading) {
222
223
            new Thread(runnable).start();
        } else {
BaiSugar's avatar
BaiSugar committed
224
225
            runnable.run();
        }
KingRainbow44's avatar
KingRainbow44 committed
226
227
228
229
230
231
232
    }

    /**
     * Scans for all classes annotated with {@link Command} and registers them.
     */
    private void scan() {
        Reflections reflector = Grasscutter.reflector;
233
        Set<Class<?>> classes = reflector.getTypesAnnotatedWith(Command.class);
KingRainbow44's avatar
KingRainbow44 committed
234
235
        classes.forEach(annotated -> {
            try {
236
237
                Command cmdData = annotated.getAnnotation(Command.class);
                Object object = annotated.newInstance();
KingRainbow44's avatar
KingRainbow44 committed
238
239
                if (object instanceof CommandHandler)
                    this.registerCommand(cmdData.label(), (CommandHandler) object);
240
241
242
243
                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
244
245
246
        });
    }
}