-
-
Notifications
You must be signed in to change notification settings - Fork 449
Expand file tree
/
Copy pathCommands.java
More file actions
307 lines (272 loc) · 11 KB
/
Copy pathCommands.java
File metadata and controls
307 lines (272 loc) · 11 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
package ch.njol.skript.command;
import ch.njol.skript.ScriptLoader;
import ch.njol.skript.Skript;
import ch.njol.skript.SkriptConfig;
import ch.njol.skript.lang.Effect;
import ch.njol.skript.lang.TriggerItem;
import ch.njol.skript.lang.parser.ParserInstance;
import ch.njol.skript.localization.ArgsMessage;
import ch.njol.skript.localization.Message;
import ch.njol.skript.log.RetainingLogHandler;
import ch.njol.skript.log.SkriptLogger;
import ch.njol.skript.variables.Variables;
import com.google.common.base.Preconditions;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.help.HelpMap;
import org.bukkit.help.HelpTopic;
import org.bukkit.plugin.SimplePluginManager;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NotNull;
import org.skriptlang.skript.bukkit.text.TextComponentParser;
import org.skriptlang.skript.lang.script.Script;
import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.regex.Pattern;
//TODO option to disable replacement of <color>s in command arguments?
/**
* @author Peter Güttinger
*/
@SuppressWarnings("deprecation")
public abstract class Commands {
public final static ArgsMessage m_too_many_arguments = new ArgsMessage("commands.too many arguments");
public final static Message m_internal_error = new Message("commands.internal error");
public final static Message m_correct_usage = new Message("commands.correct usage");
/**
* A Converter flag declaring that a Converter cannot be used for parsing command arguments.
*/
public static final int CONVERTER_NO_COMMAND_ARGUMENTS = 8;
private final static Map<String, ScriptCommand> commands = new HashMap<>();
@Nullable
private static SimpleCommandMap commandMap = null;
@Nullable
private static Map<String, Command> cmKnownCommands;
@Nullable
private static Set<String> cmAliases;
static {
init(); // separate method for the annotation
}
public static Set<String> getScriptCommands(){
return commands.keySet();
}
@Nullable
public static SimpleCommandMap getCommandMap(){
return commandMap;
}
@SuppressWarnings({"unchecked", "removal"})
private static void init() {
try {
if (Bukkit.getPluginManager() instanceof SimplePluginManager) {
Field commandMapField = SimplePluginManager.class.getDeclaredField("commandMap");
commandMapField.setAccessible(true);
commandMap = (SimpleCommandMap) commandMapField.get(Bukkit.getPluginManager());
Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands");
knownCommandsField.setAccessible(true);
cmKnownCommands = (Map<String, Command>) knownCommandsField.get(commandMap);
try {
Field aliasesField = SimpleCommandMap.class.getDeclaredField("aliases");
aliasesField.setAccessible(true);
cmAliases = (Set<String>) aliasesField.get(commandMap);
} catch (NoSuchFieldException ignored) {}
}
} catch (SecurityException e) {
Skript.error("Please disable the security manager");
commandMap = null;
} catch (Exception e) {
Skript.outdatedError(e);
commandMap = null;
}
}
@Nullable
public static List<Argument<?>> currentArguments = null;
@SuppressWarnings("null")
private final static Pattern escape = Pattern.compile("[" + Pattern.quote("(|)<>%\\") + "]");
@SuppressWarnings("null")
private final static Pattern unescape = Pattern.compile("\\\\[" + Pattern.quote("(|)<>%\\") + "]");
public static String escape(String string) {
return "" + escape.matcher(string).replaceAll("\\\\$0");
}
public static String unescape(String string) {
return "" + unescape.matcher(string).replaceAll("$0");
}
static boolean handleEffectCommand(CommandSender sender, String command) {
if (!(Skript.testing() || sender instanceof ConsoleCommandSender || sender.hasPermission("skript.effectcommands") || SkriptConfig.allowOpsToUseEffectCommands.value() && sender.isOp()))
return false;
try {
command = "" + command.substring(SkriptConfig.effectCommandToken.value().length()).trim();
RetainingLogHandler log = SkriptLogger.startRetainingLog();
try {
// Call the event on the Bukkit API for addon developers.
EffectCommandEvent effectCommand = new EffectCommandEvent(sender, command);
Bukkit.getPluginManager().callEvent(effectCommand);
command = effectCommand.getCommand();
ParserInstance parserInstance = ParserInstance.get();
parserInstance.setCurrentEvent("effect command", EffectCommandEvent.class);
Effect effect = Effect.parse(command, null);
parserInstance.deleteCurrentEvent();
TextComponentParser textParser = TextComponentParser.instance();
if (effect != null) {
log.clear(); // ignore warnings and stuff
log.printLog();
if (!effectCommand.isCancelled()) {
sender.sendMessage(textParser.parse("<gray>Executing '" + textParser.escape(command) + "'"));
if (SkriptConfig.logEffectCommands.value() && !(sender instanceof ConsoleCommandSender))
Skript.info(sender.getName() + " issued effect command: " + textParser.escape(command));
TriggerItem.walk(effect, effectCommand);
Variables.removeLocals(effectCommand);
} else {
sender.sendMessage(textParser.parse("<red>Your effect command '" + textParser.escape(command) + "' was cancelled."));
}
} else {
if (sender == Bukkit.getConsoleSender()) // log as SEVERE instead of INFO like printErrors below
// No need to escape command here, logger will do it
SkriptLogger.LOGGER.severe("Error in: " + command);
else
sender.sendMessage(textParser.parse("<red>Error in: <gray>" + textParser.escape(command)));
// TODO errors likely need to be escaped too
log.printErrors(sender, "(No specific information is available)");
}
} finally {
log.stop();
}
return true;
} catch (Exception e) {
Skript.exception(e, "Unexpected error while executing effect command '" + TextComponentParser.instance().escape(command) + "' by '" + sender.getName() + "'");
sender.sendRichMessage("<red>An internal error occurred while executing this effect. Please refer to the server log for details.");
return true;
}
}
@Nullable
public static ScriptCommand getScriptCommand(String key) {
return commands.get(key);
}
/**
* @deprecated Use {@link #scriptCommandExists(String)} instead.
*/
@Deprecated(since = "2.8.0", forRemoval = true)
public static boolean skriptCommandExists(String command) {
return scriptCommandExists(command);
}
public static boolean scriptCommandExists(String command) {
ScriptCommand scriptCommand = commands.get(command);
return scriptCommand != null && scriptCommand.getName().equals(command);
}
public static void registerCommand(ScriptCommand command) {
// Validate that there are no duplicates
ScriptCommand existingCommand = commands.get(command.getLabel());
if (existingCommand != null && existingCommand.getLabel().equals(command.getLabel())) {
Script script = existingCommand.getScript();
Skript.error("A command with the name /" + existingCommand.getName() + " is already defined"
+ (script != null ? (" in " + script.getConfig().getFileName()) : "")
);
return;
}
if (commandMap != null) {
assert cmKnownCommands != null;// && cmAliases != null;
command.register(commandMap, cmKnownCommands, cmAliases);
}
commands.put(command.getLabel(), command);
for (String alias : command.getActiveAliases()) {
commands.put(alias.toLowerCase(Locale.ENGLISH), command);
}
command.registerHelp();
}
@Deprecated(since = "2.7.0", forRemoval = true)
public static int unregisterCommands(File script) {
int numCommands = 0;
for (ScriptCommand c : new ArrayList<>(commands.values())) {
if (c.getScript() != null && c.getScript().equals(ScriptLoader.getScript(script))) {
numCommands++;
unregisterCommand(c);
}
}
return numCommands;
}
public static void unregisterCommand(ScriptCommand scriptCommand) {
scriptCommand.unregisterHelp();
if (commandMap != null) {
assert cmKnownCommands != null;// && cmAliases != null;
scriptCommand.unregister(commandMap, cmKnownCommands, cmAliases);
}
commands.values().removeIf(command -> command == scriptCommand);
}
private static boolean registeredListeners = false;
public static void registerListeners() {
if (!registeredListeners) {
Bukkit.getPluginManager().registerEvents(new Listener() {
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerChat(AsyncPlayerChatEvent event) {
if ((!SkriptConfig.enableEffectCommands.value() && !Skript.testing()) || !event.getMessage().startsWith(SkriptConfig.effectCommandToken.value()))
return;
if (!event.isAsynchronous()) {
if (handleEffectCommand(event.getPlayer(), event.getMessage()))
event.setCancelled(true);
} else {
Future<Boolean> f = Bukkit.getScheduler().callSyncMethod(Skript.getInstance(), () -> handleEffectCommand(event.getPlayer(), event.getMessage()));
try {
while (true) {
try {
if (f.get())
event.setCancelled(true);
break;
} catch (InterruptedException ignored) {
}
}
} catch (ExecutionException e) {
Skript.exception(e);
}
}
}
}, Skript.getInstance());
registeredListeners = true;
}
}
/**
* copied from CraftBukkit (org.bukkit.craftbukkit.help.CommandAliasHelpTopic)
*/
public static final class CommandAliasHelpTopic extends HelpTopic {
private final String aliasFor;
private final HelpMap helpMap;
public CommandAliasHelpTopic(String alias, String aliasFor, HelpMap helpMap) {
this.aliasFor = aliasFor.startsWith("/") ? aliasFor : "/" + aliasFor;
this.helpMap = helpMap;
name = alias.startsWith("/") ? alias : "/" + alias;
Preconditions.checkState(!name.equals(this.aliasFor), "Command " + name + " cannot be alias for itself");
shortText = ChatColor.YELLOW + "Alias for " + ChatColor.WHITE + this.aliasFor;
}
@Override
@NotNull
public String getFullText(CommandSender forWho) {
StringBuilder fullText = new StringBuilder(shortText);
HelpTopic aliasForTopic = helpMap.getHelpTopic(aliasFor);
if (aliasForTopic != null) {
fullText.append("\n");
fullText.append(aliasForTopic.getFullText(forWho));
}
return "" + fullText;
}
@Override
public boolean canSee(CommandSender commandSender) {
if (amendedPermission != null)
return commandSender.hasPermission(amendedPermission);
HelpTopic aliasForTopic = helpMap.getHelpTopic(aliasFor);
return aliasForTopic != null && aliasForTopic.canSee(commandSender);
}
}
}