forked from CloudburstMC/Nukkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleCommandMap.java
More file actions
318 lines (266 loc) · 12.6 KB
/
SimpleCommandMap.java
File metadata and controls
318 lines (266 loc) · 12.6 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package cn.nukkit.command;
import cn.nukkit.Server;
import cn.nukkit.command.data.CommandParameter;
import cn.nukkit.command.defaults.*;
import cn.nukkit.command.simple.*;
import cn.nukkit.lang.TranslationContainer;
import cn.nukkit.utils.TextFormat;
import cn.nukkit.utils.Utils;
import java.lang.reflect.Method;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
/**
* @author MagicDroidX
* Nukkit Project
*/
public class SimpleCommandMap implements CommandMap {
protected final Map<String, Command> knownCommands = new HashMap<>();
private final Server server;
public SimpleCommandMap(Server server) {
this.server = server;
this.setDefaultCommands();
}
private void setDefaultCommands() {
this.register("nukkit", new VersionCommand("version"));
this.register("nukkit", new PluginsCommand("plugins"));
this.register("nukkit", new HelpCommand("help"));
this.register("nukkit", new StopCommand("stop"));
this.register("nukkit", new TellCommand("tell"));
this.register("nukkit", new BanCommand("ban"));
this.register("nukkit", new BanIpCommand("ban-ip"));
this.register("nukkit", new BanListCommand("banlist"));
this.register("nukkit", new PardonCommand("pardon"));
this.register("nukkit", new PardonIpCommand("pardon-ip"));
this.register("nukkit", new ListCommand("list"));
this.register("nukkit", new KickCommand("kick"));
this.register("nukkit", new OpCommand("op"));
this.register("nukkit", new DeopCommand("deop"));
this.register("nukkit", new SaveCommand("save"));
this.register("nukkit", new GiveCommand("give"));
this.register("nukkit", new ClearCommand("clear"));
this.register("nukkit", new EffectCommand("effect"));
this.register("nukkit", new EnchantCommand("enchant"));
this.register("nukkit", new GamemodeCommand("gamemode"));
this.register("nukkit", new KillCommand("kill"));
this.register("nukkit", new SetWorldSpawnCommand("setworldspawn"));
this.register("nukkit", new TeleportCommand("tp"));
this.register("nukkit", new TimeCommand("time"));
this.register("nukkit", new ReloadCommand("reload"));
this.register("nukkit", new WeatherCommand("weather"));
this.register("nukkit", new XpCommand("xp"));
this.register("nukkit", new StatusCommand("status"));
this.register("nukkit", new SummonCommand("summon"));
this.register("nukkit", new WhitelistCommand("whitelist"));
this.register("nukkit", new GameruleCommand("gamerule"));
this.register("nukkit", new ConvertCommand("convert"));
this.register("nukkit", new DefaultGamemodeCommand("defaultgamemode"));
this.register("nukkit", new SayCommand("say"));
this.register("nukkit", new MeCommand("me"));
this.register("nukkit", new DifficultyCommand("difficulty"));
this.register("nukkit", new ParticleCommand("particle"));
this.register("nukkit", new SpawnpointCommand("spawnpoint"));
this.register("nukkit", new TitleCommand("title"));
this.register("nukkit", new SeedCommand("seed"));
this.register("nukkit", new PlaySoundCommand("playsound"));
this.register("nukkit", new GarbageCollectorCommand("gc"));
}
@Override
public void registerAll(String fallbackPrefix, List<? extends Command> commands) {
for (Command command : commands) {
this.register(fallbackPrefix, command);
}
}
@Override
public boolean register(String fallbackPrefix, Command command) {
return this.register(fallbackPrefix, command, null);
}
@Override
public boolean register(String fallbackPrefix, Command command, String label) {
if (label == null) {
label = command.getName();
}
label = label.trim().toLowerCase(Locale.ROOT);
fallbackPrefix = fallbackPrefix.trim().toLowerCase(Locale.ROOT);
boolean registered = this.registerAlias(command, false, fallbackPrefix, label);
List<String> aliases = new ArrayList<>(Arrays.asList(command.getAliases()));
for (Iterator<String> iterator = aliases.iterator(); iterator.hasNext(); ) {
String alias = iterator.next();
if (!this.registerAlias(command, true, fallbackPrefix, alias)) {
iterator.remove();
}
}
command.setAliases(aliases.toArray(new String[0]));
if (!registered) {
command.setLabel(fallbackPrefix + ':' + label);
}
command.register(this);
return registered;
}
@Override
public void registerSimpleCommands(Object object) {
for (Method method : object.getClass().getDeclaredMethods()) {
cn.nukkit.command.simple.Command def = method.getAnnotation(cn.nukkit.command.simple.Command.class);
if (def != null) {
SimpleCommand sc = new SimpleCommand(object, method, def.name(), def.description(), def.usageMessage(), def.aliases());
Arguments args = method.getAnnotation(Arguments.class);
if (args != null) {
sc.setMaxArgs(args.max());
sc.setMinArgs(args.min());
}
CommandPermission perm = method.getAnnotation(CommandPermission.class);
if (perm != null) {
sc.setPermission(perm.value());
}
if (method.isAnnotationPresent(ForbidConsole.class)) {
sc.setForbidConsole(true);
}
CommandParameters commandParameters = method.getAnnotation(CommandParameters.class);
if (commandParameters != null) {
Map<String, CommandParameter[]> map = Arrays.stream(commandParameters.parameters())
.collect(Collectors.toMap(Parameters::name, parameters -> Arrays.stream(parameters.parameters())
.map(parameter -> new CommandParameter(parameter.name(), parameter.type(), parameter.optional()))
.distinct()
.toArray(CommandParameter[]::new)));
sc.commandParameters.putAll(map);
}
this.register(def.name(), sc);
}
}
}
private boolean registerAlias(Command command, boolean isAlias, String fallbackPrefix, String label) {
this.knownCommands.put(fallbackPrefix + ':' + label, command);
//if you're registering a command alias that is already registered, then return false
Command existingCommand = this.knownCommands.get(label);
boolean alreadyRegistered = existingCommand != null;
boolean existingCommandIsNotVanilla = alreadyRegistered && !(existingCommand instanceof VanillaCommand);
//basically, if we're an alias and it's already registered, or we're a vanilla command, then we can't override it
if ((command instanceof VanillaCommand || isAlias) && alreadyRegistered && existingCommandIsNotVanilla) {
return false;
}
// If you're registering a name (alias or label) which is identical to another command who's primary name is the same
// So basically we can't override the main name of a command, but we can override aliases if we're not an alias
// Added the last statement which will allow us to override a VanillaCommand unconditionally
if (alreadyRegistered && existingCommand.getLabel() != null && existingCommand.getLabel().equals(label) && existingCommandIsNotVanilla) {
return false;
}
// You can now assume that the command is either uniquely named, or overriding another command's alias (and is not itself, an alias)
if (!isAlias) {
command.setLabel(label);
}
// Then we need to check if there isn't any command conflicts with vanilla commands
ArrayList<String> toRemove = new ArrayList<>();
for (Entry<String, Command> entry : knownCommands.entrySet()) {
Command cmd = entry.getValue();
if (cmd.getLabel().equalsIgnoreCase(command.getLabel()) && !cmd.equals(command)) { // If the new command conflicts... (But if it isn't the same command)
if (cmd instanceof VanillaCommand) { // And if the old command is a vanilla command...
// Remove it!
toRemove.add(entry.getKey());
}
}
}
// Now we loop the toRemove list to remove the command conflicts from the knownCommands map
for (String cmd : toRemove) {
knownCommands.remove(cmd);
}
this.knownCommands.put(label, command);
return true;
}
private static ArrayList<String> parseArguments(String cmdLine) {
StringBuilder sb = new StringBuilder(cmdLine);
ArrayList<String> args = new ArrayList<>();
boolean notQuoted = true;
int start = 0;
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == '\\') {
sb.deleteCharAt(i);
continue;
}
if (sb.charAt(i) == ' ' && notQuoted) {
String arg = sb.substring(start, i);
if (!arg.isEmpty()) {
args.add(arg);
}
start = i + 1;
} else if (sb.charAt(i) == '"') {
sb.deleteCharAt(i);
--i;
notQuoted = !notQuoted;
}
}
String arg = sb.substring(start);
if (!arg.isEmpty()) {
args.add(arg);
}
return args;
}
@Override
public boolean dispatch(CommandSender sender, String cmdLine) {
ArrayList<String> parsed = parseArguments(cmdLine);
if (parsed.isEmpty()) {
return false;
}
String sentCommandLabel = parsed.remove(0).toLowerCase(Locale.ROOT);
String[] args = parsed.toArray(new String[0]);
Command target = this.getCommand(sentCommandLabel);
if (target == null) {
return false;
}
try {
target.execute(sender, sentCommandLabel, args);
} catch (Exception e) {
sender.sendMessage(new TranslationContainer(TextFormat.RED + "%commands.generic.exception"));
this.server.getLogger().critical(this.server.getLanguage().translateString("nukkit.command.exception", cmdLine, target.toString(), Utils.getExceptionMessage(e)), e);
}
return true;
}
@Override
public void clearCommands() {
for (Command command : this.knownCommands.values()) {
command.unregister(this);
}
this.knownCommands.clear();
this.setDefaultCommands();
}
@Override
public Command getCommand(String name) {
return this.knownCommands.get(name);
}
public Map<String, Command> getCommands() {
return knownCommands;
}
public void registerServerAliases() {
Map<String, List<String>> values = this.server.getCommandAliases();
for (Map.Entry<String, List<String>> entry : values.entrySet()) {
String alias = entry.getKey();
List<String> commandStrings = entry.getValue();
if (alias.contains(" ") || alias.contains(":")) {
this.server.getLogger().warning(this.server.getLanguage().translateString("nukkit.command.alias.illegal", alias));
continue;
}
List<String> targets = new ArrayList<>();
StringBuilder bad = new StringBuilder();
for (String commandString : commandStrings) {
String[] args = commandString.split(" ");
Command command = this.getCommand(args[0]);
if (command == null) {
if (bad.length() > 0) {
bad.append(", ");
}
bad.append(commandString);
} else {
targets.add(commandString);
}
}
if (bad.length() > 0) {
this.server.getLogger().warning(this.server.getLanguage().translateString("nukkit.command.alias.notFound", new String[]{alias, bad.toString()}));
continue;
}
if (!targets.isEmpty()) {
this.knownCommands.put(alias.toLowerCase(Locale.ROOT), new FormattedCommandAlias(alias.toLowerCase(Locale.ROOT), targets));
} else {
this.knownCommands.remove(alias.toLowerCase(Locale.ROOT));
}
}
}
}