forked from Maxlego08/zEssentials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathZCommandManager.java
More file actions
375 lines (311 loc) · 15.3 KB
/
Copy pathZCommandManager.java
File metadata and controls
375 lines (311 loc) · 15.3 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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package fr.maxlego08.essentials.commands;
import fr.maxlego08.essentials.ZEssentialsPlugin;
import fr.maxlego08.essentials.api.commands.CommandManager;
import fr.maxlego08.essentials.api.commands.CommandResultType;
import fr.maxlego08.essentials.api.commands.EssentialsCommand;
import fr.maxlego08.essentials.api.messages.Message;
import fr.maxlego08.essentials.api.user.User;
import fr.maxlego08.essentials.zutils.utils.TimerBuilder;
import fr.maxlego08.essentials.zutils.utils.ZUtils;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandMap;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
public class ZCommandManager extends ZUtils implements CommandManager {
private static CommandMap commandMap;
private static Constructor<? extends PluginCommand> constructor;
static {
try {
Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");
bukkitCommandMap.setAccessible(true);
commandMap = (CommandMap) bukkitCommandMap.get(Bukkit.getServer());
constructor = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class);
constructor.setAccessible(true);
} catch (Exception exception) {
Bukkit.getLogger().severe("[zEssentials] Failed to initialize command map or PluginCommand constructor: " + exception.getMessage());
exception.printStackTrace();
}
}
protected final List<EssentialsCommand> commands = new ArrayList<>();
private final ZEssentialsPlugin plugin;
public ZCommandManager(ZEssentialsPlugin plugin) {
this.plugin = plugin;
}
@Override
public void registerCommand(EssentialsCommand command) {
this.commands.add(command);
}
@Override
public void registerCommand(String string, EssentialsCommand command) {
command.addSubCommand(string);
this.commands.add(command);
this.plugin.getCommand(string).setExecutor(this);
this.plugin.getCommand(string).setTabCompleter(this);
}
@Override
public boolean onCommand(@NotNull CommandSender sender, @NotNull Command cmd, @NotNull String label, String[] args) {
for (EssentialsCommand command : this.commands) {
if (command.getSubCommands().contains(cmd.getName().toLowerCase())) {
if ((args.length == 0 || command.isIgnoreParent()) && command.getParent() == null) {
CommandResultType type = processRequirements(command, sender, args);
if (!type.equals(CommandResultType.CONTINUE)) return true;
}
} else if (args.length >= 1 && command.getParent() != null && canExecute(args, cmd.getName().toLowerCase(), command)) {
CommandResultType type = processRequirements(command, sender, args);
if (!type.equals(CommandResultType.CONTINUE)) return true;
}
}
message(sender, Message.COMMAND_NO_ARG);
return true;
}
private boolean canExecute(String[] args, String cmd, EssentialsCommand command) {
for (int index = args.length - 1; index > -1; index--) {
if (command.getSubCommands().contains(args[index].toLowerCase())) {
if (command.isIgnoreArgs() && (command.getParent() == null || canExecute(args, cmd, command.getParent(), index - 1)))
return true;
if (index < args.length - 1) return false;
return canExecute(args, cmd, command.getParent(), index - 1);
}
}
return false;
}
private boolean canExecute(String[] args, String cmd, EssentialsCommand command, int index) {
if (index < 0 && command.getSubCommands().contains(cmd.toLowerCase())) return true;
else if (index < 0) return false;
else if (command.getSubCommands().contains(args[index].toLowerCase())) {
return canExecute(args, cmd, command.getParent(), index - 1);
} else return false;
}
private CommandResultType processRequirements(EssentialsCommand command, CommandSender sender, String[] strings) {
if (!(sender instanceof Player) && !command.isConsoleCanUse()) {
message(sender, Message.COMMAND_NO_CONSOLE);
return CommandResultType.DEFAULT;
}
if (command.getPermission() == null || sender.hasPermission(command.getPermission())) {
CommandResultType returnType = command.prePerform(this.plugin, sender, strings);
if (returnType == CommandResultType.SYNTAX_ERROR) {
message(sender, Message.COMMAND_SYNTAX_ERROR, "%syntax%", command.getSyntax());
} else if (returnType == CommandResultType.NO_PERMISSION) {
message(sender, Message.COMMAND_NO_PERMISSION);
}
return returnType;
}
message(sender, Message.COMMAND_NO_PERMISSION);
return CommandResultType.DEFAULT;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String str, String[] args) {
for (EssentialsCommand command : commands) {
if (command.getSubCommands().contains(cmd.getName().toLowerCase()) && command.getParent() == null) {
return processTab(sender, command, args);
} else {
String[] newArgs = Arrays.copyOf(args, args.length - 1);
if (newArgs.length >= 1 && command.getParent() != null && canExecute(newArgs, cmd.getName().toLowerCase(), command)) {
return processTab(sender, command, args);
}
}
}
return List.of();
}
public List<String> processTab(CommandSender sender, EssentialsCommand command, String[] args) {
CommandResultType type = command.getTabCompleter();
if (type.equals(CommandResultType.DEFAULT)) {
String startWith = args[args.length - 1];
List<String> tabCompleter = new ArrayList<>();
for (EssentialsCommand vCommand : this.commands) {
if ((vCommand.getParent() != null && vCommand.getParent() == command)) {
String cmd = vCommand.getSubCommands().getFirst();
if (vCommand.getPermission() == null || sender.hasPermission(vCommand.getPermission())) {
if (startWith.isEmpty() || cmd.startsWith(startWith)) {
tabCompleter.add(cmd);
}
}
}
}
return tabCompleter.isEmpty() ? List.of() : tabCompleter;
} else if (type.equals(CommandResultType.SUCCESS)) {
var list = command.toTab(this.plugin, sender, args);
return list == null ? List.of() : list.stream().limit(100).toList();
}
return List.of();
}
private YamlConfiguration getCommandConfiguration() {
File file = new File(plugin.getDataFolder(), "commands.yml");
if (!file.exists()) {
try {
if (!file.createNewFile()) {
this.plugin.getLogger().severe("The commands.yml file cannot be created.");
return null;
}
} catch (IOException exception) {
exception.printStackTrace();
}
}
return YamlConfiguration.loadConfiguration(file);
}
public void saveCommandConfiguration(YamlConfiguration configuration) {
File file = new File(plugin.getDataFolder(), "commands.yml");
try {
configuration.save(file);
} catch (IOException exception) {
exception.printStackTrace();
}
}
@Override
public void saveCommands() {
YamlConfiguration configuration = getCommandConfiguration();
if (configuration == null) return;
List<EssentialsCommand> essentialsCommands = getSortCommands();
AtomicBoolean atomicBoolean = new AtomicBoolean(false);
essentialsCommands.forEach(essentialsCommand -> {
String commandName = getCommandName(essentialsCommand);
ConfigurationSection configurationSection = configuration.getConfigurationSection(commandName);
if (configurationSection != null) return;
configuration.set(commandName + ".enable", true);
configuration.set(commandName + ".commands", essentialsCommand.getSubCommands());
configuration.set(commandName + ".permission", essentialsCommand.getPermission());
atomicBoolean.set(true);
});
if (atomicBoolean.get()) {
this.saveCommandConfiguration(configuration);
}
}
private String getCommandName(EssentialsCommand command) {
String className = command.getClass().getSimpleName();
StringBuilder transformedName = new StringBuilder();
for (int i = 0; i < className.length(); i++) {
char currentChar = className.charAt(i);
if (Character.isUpperCase(currentChar)) {
if (i != 0) {
transformedName.append('-');
}
transformedName.append(Character.toLowerCase(currentChar));
} else {
transformedName.append(currentChar);
}
}
return transformedName.toString();
}
/**
* Register spigot command without plugin.yml This method will allow
* registering a command in the spigot without using the plugin.yml This saves
* time and understanding, the plugin.yml file is clearer
*
* @param mainCommand - Main command
* @param essentialsCommand - Command object
* @param aliases - Command aliases
*/
public void registerCommand(Plugin plugin, String mainCommand, EssentialsCommand essentialsCommand, List<String> aliases) {
YamlConfiguration configuration = getCommandConfiguration();
if (configuration != null) {
String commandName = getCommandName(essentialsCommand);
ConfigurationSection configurationSection = configuration.getConfigurationSection(commandName);
if (configurationSection != null) {
if (!configurationSection.getBoolean("enable", true)) {
return;
}
List<String> commands = configurationSection.getStringList("commands");
if (commands.isEmpty()) {
this.plugin.getLogger().severe("Command " + commandName + " doesnt have commands !");
} else {
mainCommand = commands.remove(0);
aliases = commands;
}
essentialsCommand.setPermission(configurationSection.getString("permission"));
}
}
try {
if (constructor == null || commandMap == null) {
this.plugin.getLogger().severe("Cannot register command '" + mainCommand + "': CommandMap or PluginCommand constructor is not initialized!");
return;
}
PluginCommand command = constructor.newInstance(mainCommand, plugin);
command.setExecutor(this);
command.setTabCompleter(this);
command.setAliases(aliases);
if (essentialsCommand.getPermission() != null) {
command.setPermission(essentialsCommand.getPermission());
}
essentialsCommand.addSubCommand(mainCommand);
essentialsCommand.addSubCommand(aliases);
commands.add(essentialsCommand);
if (!commandMap.register(command.getName(), plugin.getDescription().getName(), command)) {
plugin.getLogger().warning("Unable to add the command /" + mainCommand + " (already registered by another plugin). Use /zessentials:" + mainCommand + " instead.");
}
if (essentialsCommand.getPermission() != null) {
Permission existingPermission = Bukkit.getPluginManager().getPermission(essentialsCommand.getPermission());
if (existingPermission != null) {
Bukkit.getPluginManager().removePermission(existingPermission);
}
Bukkit.getPluginManager().addPermission(new Permission(essentialsCommand.getPermission(), essentialsCommand.getDescription() == null ? "No description" : essentialsCommand.getDescription()));
}
} catch (Exception exception) {
this.plugin.getLogger().severe("Failed to register command '" + mainCommand + "': " + exception.getMessage());
exception.printStackTrace();
}
}
@Override
public int countCommands() {
return this.commands.size();
}
@Override
public List<EssentialsCommand> getCommands() {
return this.commands;
}
@Override
public List<EssentialsCommand> getSortCommands() {
List<EssentialsCommand> essentialsCommands = new ArrayList<>();
this.commands.stream().filter(e -> e.getParent() == null).sorted(Comparator.comparing(EssentialsCommand::getMainCommand)).forEach(command -> {
essentialsCommands.add(command);
essentialsCommands.addAll(this.commands.stream().filter(e -> e.getMainParent() == command).sorted(Comparator.comparing(EssentialsCommand::getMainCommand)).toList());
});
return essentialsCommands;
}
private boolean isEssentialsCommand(String command) {
return this.commands.stream().anyMatch(e -> e.getParent() == null && e.getSubCommands().contains(command));
}
@EventHandler
public void onCommand(PlayerCommandPreprocessEvent event) {
var player = event.getPlayer();
String[] split = event.getMessage().substring(1).split(" ");
String key = split.length > 0 ? split[0].toLowerCase() : "";
if (isEssentialsCommand(key)) {
return;
}
User user = this.plugin.getUser(player.getUniqueId());
int cooldownSeconds = 0;
var configuration = this.plugin.getConfiguration();
if (user != null && (!user.hasPermission(fr.maxlego08.essentials.api.commands.Permission.ESSENTIALS_BYPASS_COOLDOWN) || !configuration.isEnableCooldownBypass())) {
Optional<Integer> optional = configuration.getCooldown(player, key);
if (optional.isPresent()) {
cooldownSeconds = optional.get();
if (user.isCooldown(key)) {
event.setCancelled(true);
long milliSeconds = user.getCooldown(key) - System.currentTimeMillis();
message(player, Message.COOLDOWN, "%cooldown%", TimerBuilder.getStringTime(milliSeconds));
} else {
user.addCooldown(key, cooldownSeconds);
}
}
}
}
}