-
-
Notifications
You must be signed in to change notification settings - Fork 449
Expand file tree
/
Copy pathScriptCommand.java
More file actions
628 lines (562 loc) · 21.2 KB
/
Copy pathScriptCommand.java
File metadata and controls
628 lines (562 loc) · 21.2 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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
package ch.njol.skript.command;
import ch.njol.skript.ScriptLoader;
import ch.njol.skript.Skript;
import ch.njol.skript.SkriptConfig;
import ch.njol.skript.command.Commands.CommandAliasHelpTopic;
import ch.njol.skript.config.SectionNode;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.Trigger;
import ch.njol.skript.lang.Variable;
import ch.njol.skript.lang.VariableString;
import ch.njol.skript.lang.parser.ParserInstance;
import ch.njol.skript.lang.util.SimpleEvent;
import ch.njol.skript.lang.util.SimpleLiteral;
import ch.njol.skript.localization.Language;
import ch.njol.skript.localization.Message;
import ch.njol.skript.log.LogEntry;
import ch.njol.skript.log.ParseLogHandler;
import ch.njol.skript.log.SkriptLogger;
import ch.njol.skript.log.Verbosity;
import ch.njol.skript.util.Date;
import ch.njol.skript.util.EmptyStacktraceException;
import ch.njol.skript.util.Timespan;
import ch.njol.skript.variables.HintManager;
import ch.njol.skript.variables.Variables;
import ch.njol.util.StringUtils;
import com.google.common.base.Preconditions;
import net.kyori.adventure.text.Component;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.help.GenericCommandHelpTopic;
import org.bukkit.help.HelpMap;
import org.bukkit.help.HelpTopic;
import org.bukkit.help.HelpTopicComparator;
import org.bukkit.help.IndexHelpTopic;
import org.bukkit.plugin.Plugin;
import org.jetbrains.annotations.Nullable;
import org.skriptlang.skript.bukkit.text.TextComponentParser;
import org.skriptlang.skript.lang.script.Script;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
/**
* This class is used for user-defined commands.
* @deprecated There is no direct replacement for this command.
* The closest alternative is {@link org.skriptlang.skript.bukkit.command.custom.ScriptBrigadierCommand}.
*/
@Deprecated(since = "INSERT VERSION", forRemoval = true)
public class ScriptCommand implements TabExecutor {
public final static Message m_executable_by_players = new Message("commands.executable by players");
public final static Message m_executable_by_console = new Message("commands.executable by console");
private static final String DEFAULT_PREFIX = "skript";
final String name;
private final String label;
private final List<String> aliases;
private List<String> activeAliases;
private String permission;
private final Expression<? extends Component> permissionMessage;
private final String description;
private final String prefix;
@Nullable
private final Timespan cooldown;
private final Expression<? extends Component> cooldownMessage;
private final String cooldownBypass;
@Nullable
private final Expression<String> cooldownStorage;
final CommandUsage usage;
private final Trigger trigger;
private final String pattern;
private final List<Argument<?>> arguments;
public final static int PLAYERS = 0x1, CONSOLE = 0x2, BOTH = PLAYERS | CONSOLE;
final int executableBy;
private transient PluginCommand bukkitCommand;
private Map<UUID,Date> lastUsageMap = new HashMap<>();
//<editor-fold default-state="collapsed" desc="public ScriptCommand(... String usage ...)">
/**
* Creates a new ScriptCommand.
* Prefer using the CommandUsage class for the usage parameter.
*
* @param name /name
* @param pattern the Skript pattern used to parse the input into arguments.
* @param arguments the list of Arguments this command takes
* @param description description to display in /help
* @param prefix the prefix of the command
* @param usage message to display if the command was used incorrectly
* @param aliases /alias1, /alias2, ...
* @param permission permission or null if none
* @param permissionMessage message to display if the player doesn't have the given permission
* @param node the node to parse and load into a Trigger
*/
public ScriptCommand(
Script script, String name, String pattern, List<Argument<?>> arguments,
String description, @Nullable String prefix, String usage, List<String> aliases,
String permission, @Nullable VariableString permissionMessage, @Nullable Timespan cooldown,
@Nullable VariableString cooldownMessage, String cooldownBypass,
@Nullable VariableString cooldownStorage, int executableBy, SectionNode node
) {
this(script, name, pattern, arguments, description, prefix, new CommandUsage(null, usage),
aliases, permission, permissionMessage, cooldown, cooldownMessage, cooldownBypass,
cooldownStorage, executableBy, node);
}
//</editor-fold>
/**
* Creates a new ScriptCommand.
*
* @param name /name
* @param pattern the Skript pattern used to parse the input into arguments.
* @param arguments the list of Arguments this command takes
* @param description description to display in /help
* @param prefix the prefix of the command
* @param usage message to display if the command was used incorrectly
* @param aliases /alias1, /alias2, ...
* @param permission permission or null if none
* @param permissionMessage message to display if the player doesn't have the given permission
* @param node the node to parse and load into a Trigger
*/
public ScriptCommand(
Script script, String name, String pattern, List<Argument<?>> arguments,
String description, @Nullable String prefix, CommandUsage usage, List<String> aliases,
String permission, @Nullable VariableString permissionMessage, @Nullable Timespan cooldown,
@Nullable VariableString cooldownMessage, String cooldownBypass,
@Nullable VariableString cooldownStorage, int executableBy, SectionNode node
) {
Preconditions.checkNotNull(name);
Preconditions.checkNotNull(pattern);
Preconditions.checkNotNull(arguments);
Preconditions.checkNotNull(description);
Preconditions.checkNotNull(usage);
Preconditions.checkNotNull(aliases);
Preconditions.checkNotNull(node);
this.name = name;
label = "" + name.toLowerCase(Locale.ENGLISH);
this.permission = permission;
if (permissionMessage == null) {
VariableString defaultMsg = VariableString.newInstance(Language.get("commands.no permission message"));
assert defaultMsg != null;
permissionMessage = defaultMsg;
}
//noinspection unchecked
this.permissionMessage = permissionMessage.getConvertedExpression(Component.class);
if (prefix != null) {
for (char c : prefix.toCharArray()) {
if (Character.isWhitespace(c)) {
Skript.warning("command /" + name + " has a whitespace in its prefix. Defaulting to '" + ScriptCommand.DEFAULT_PREFIX + "'.");
prefix = ScriptCommand.DEFAULT_PREFIX;
break;
}
// char 167 is §
if (c == 167) {
Skript.warning("command /" + name + " has a section character in its prefix. Defaulting to '" + ScriptCommand.DEFAULT_PREFIX + "'.");
prefix = ScriptCommand.DEFAULT_PREFIX;
break;
}
}
} else {
prefix = DEFAULT_PREFIX;
}
this.prefix = prefix;
this.cooldown = cooldown;
if (cooldownMessage == null) {
VariableString defaultMsg = VariableString.newInstance(Language.get("commands.cooldown message"));
assert defaultMsg != null;
cooldownMessage = defaultMsg;
}
//noinspection unchecked
this.cooldownMessage = cooldownMessage.getConvertedExpression(Component.class);
this.cooldownBypass = cooldownBypass;
this.cooldownStorage = cooldownStorage;
// remove aliases that are the same as the command
aliases.removeIf(label::equalsIgnoreCase);
this.aliases = aliases;
activeAliases = new ArrayList<>(aliases);
TextComponentParser textComponentParser = TextComponentParser.instance();
this.description = textComponentParser.toLegacyString(textComponentParser.parseSafe(description));
this.usage = usage;
this.executableBy = executableBy;
this.pattern = pattern;
this.arguments = arguments;
HintManager hintManager = ParserInstance.get().getHintManager();
try {
hintManager.enterScope(false);
for (Argument<?> argument : arguments) {
String hintName = argument.getName();
if (hintName == null) {
continue;
}
if (!argument.isSingle()) {
hintName += Variable.SEPARATOR + "*";
}
hintManager.set(hintName, argument.getType());
}
trigger = new Trigger(script, "command /" + name, new SimpleEvent(), ScriptLoader.loadItems(node));
trigger.setLineNumber(node.getLine());
} finally {
hintManager.exitScope();
}
bukkitCommand = setupBukkitCommand();
}
private PluginCommand setupBukkitCommand() {
try {
final Constructor<PluginCommand> c = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class);
c.setAccessible(true);
final PluginCommand bukkitCommand = c.newInstance(name, Skript.getInstance());
bukkitCommand.setAliases(aliases);
bukkitCommand.setDescription(description);
bukkitCommand.setLabel(label);
bukkitCommand.setPermission(permission);
bukkitCommand.setUsage(usage.getUsage());
bukkitCommand.setExecutor(this);
return bukkitCommand;
} catch (final Exception e) {
Skript.outdatedError(e);
throw new EmptyStacktraceException();
}
}
@Override
public boolean onCommand(final @Nullable CommandSender sender, final @Nullable Command command, final @Nullable String label, final @Nullable String[] args) {
if (sender == null || label == null || args == null)
return false;
execute(sender, label, StringUtils.join(args, " "));
return true;
}
public boolean execute(final CommandSender sender, final String commandLabel, final String rest) {
if (sender instanceof Player) {
if ((executableBy & PLAYERS) == 0) {
sender.sendMessage("" + m_executable_by_console);
return false;
}
} else {
if ((executableBy & CONSOLE) == 0) {
sender.sendMessage("" + m_executable_by_players);
return false;
}
}
final ScriptCommandEvent event = new ScriptCommandEvent(ScriptCommand.this, sender, commandLabel, rest);
if (!checkPermissions(sender, event))
return false;
cooldownCheck : {
if (sender instanceof Player && cooldown != null) {
Player player = ((Player) sender);
UUID uuid = player.getUniqueId();
// Cooldown bypass
if (!cooldownBypass.isEmpty() && player.hasPermission(cooldownBypass)) {
setLastUsage(uuid, event, null);
break cooldownCheck;
}
if (getLastUsage(uuid, event) != null) {
if (getRemainingMilliseconds(uuid, event) <= 0) {
if (!SkriptConfig.keepLastUsageDates.value())
setLastUsage(uuid, event, null);
} else {
Component msg = cooldownMessage.getSingle(event);
if (msg != null)
sender.sendMessage(msg);
return false;
}
}
}
}
Runnable runnable = () -> {
// save previous last usage date to check if the execution has set the last usage date
Date previousLastUsage = null;
if (sender instanceof Player)
previousLastUsage = getLastUsage(((Player) sender).getUniqueId(), event);
// execute the command - may modify the last usage date
execute2(event, sender, commandLabel, rest);
if (sender instanceof Player && !event.isCooldownCancelled()) {
Date lastUsage = getLastUsage(((Player) sender).getUniqueId(), event);
// check if the execution has set the last usage date
// if not, set it to the current date. if it has, we leave it alone so as not to affect the remaining/elapsed time (#5862)
if (Objects.equals(lastUsage, previousLastUsage))
setLastUsage(((Player) sender).getUniqueId(), event, new Date());
}
};
if (Bukkit.isPrimaryThread()) {
runnable.run();
} else {
// must not wait for the command to complete as some plugins call commands in such a way that the server will deadlock
Bukkit.getScheduler().scheduleSyncDelayedTask(Skript.getInstance(), runnable);
}
return true; // Skript prints its own error message anyway
}
boolean execute2(final ScriptCommandEvent event, final CommandSender sender, final String commandLabel, final String rest) {
final ParseLogHandler log = SkriptLogger.startParseLogHandler();
try {
final boolean ok = false;
if (!ok) {
final LogEntry e = log.getError();
if (e != null)
sender.sendMessage(ChatColor.DARK_RED + e.toString());
sender.sendMessage(usage.getUsageComponent(event));
log.clear();
return false;
}
log.clearError();
} finally {
log.stop();
}
if (Skript.log(Verbosity.VERY_HIGH))
Skript.info("# /" + name + " " + rest);
final long startTrigger = System.nanoTime();
if (!trigger.execute(event))
sender.sendMessage(Commands.m_internal_error.toString());
if (Skript.log(Verbosity.VERY_HIGH))
Skript.info("# " + name + " took " + 1. * (System.nanoTime() - startTrigger) / 1000000. + " milliseconds");
return true;
}
public boolean checkPermissions(CommandSender sender, String commandLabel, String arguments) {
return checkPermissions(sender, new ScriptCommandEvent(this, sender, commandLabel, arguments));
}
public boolean checkPermissions(CommandSender sender, Event event) {
if (!permission.isEmpty() && !sender.hasPermission(permission)) {
Component message = permissionMessage.getSingle(event);
assert message != null;
sender.sendMessage(message);
return false;
}
return true;
}
public void sendHelp(final CommandSender sender) {
if (!description.isEmpty())
sender.sendMessage(description);
sender.sendMessage(ChatColor.GOLD + "Usage" + ChatColor.RESET + ": " + usage.getUsage());
}
/**
* Gets the arguments this command takes.
*
* @return The internal list of arguments. Do not modify it!
*/
public List<Argument<?>> getArguments() {
return arguments;
}
public String getPattern() {
return pattern;
}
@Nullable
private transient Command overridden = null;
private transient Map<String, Command> overriddenAliases = new HashMap<>();
public void register(SimpleCommandMap commandMap, Map<String, Command> knownCommands, @Nullable Set<String> aliases) {
synchronized (commandMap) {
overriddenAliases.clear();
overridden = knownCommands.put(label, bukkitCommand);
if (aliases != null)
aliases.remove(label);
final Iterator<String> as = activeAliases.iterator();
while (as.hasNext()) {
final String lowerAlias = as.next().toLowerCase(Locale.ENGLISH);
if (knownCommands.containsKey(lowerAlias) && (aliases == null || !aliases.contains(lowerAlias))) {
as.remove();
continue;
}
overriddenAliases.put(lowerAlias, knownCommands.put(lowerAlias, bukkitCommand));
if (aliases != null)
aliases.add(lowerAlias);
}
bukkitCommand.setAliases(activeAliases);
commandMap.register(prefix, bukkitCommand);
}
}
public void unregister(SimpleCommandMap commandMap, Map<String, Command> knownCommands, @Nullable Set<String> aliases) {
synchronized (commandMap) {
knownCommands.remove(label);
knownCommands.remove(prefix + ":" + label);
if (aliases != null)
aliases.removeAll(activeAliases);
for (final String alias : activeAliases) {
knownCommands.remove(alias);
knownCommands.remove(prefix + ":" + alias);
}
activeAliases = new ArrayList<>(this.aliases);
bukkitCommand.unregister(commandMap);
bukkitCommand.setAliases(this.aliases);
if (overridden != null) {
knownCommands.put(label, overridden);
overridden = null;
}
for (final Entry<String, Command> e : overriddenAliases.entrySet()) {
if (e.getValue() == null)
continue;
knownCommands.put(e.getKey(), e.getValue());
if (aliases != null)
aliases.add(e.getKey());
}
overriddenAliases.clear();
}
}
private transient Collection<HelpTopic> helps = new ArrayList<>();
public void registerHelp() {
helps.clear();
final HelpMap help = Bukkit.getHelpMap();
final HelpTopic t = new GenericCommandHelpTopic(bukkitCommand);
help.addTopic(t);
helps.add(t);
final HelpTopic aliases = help.getHelpTopic("Aliases");
if (aliases instanceof IndexHelpTopic) {
aliases.getFullText(Bukkit.getConsoleSender()); // CraftBukkit has a lazy IndexHelpTopic class (org.bukkit.craftbukkit.help.CustomIndexHelpTopic) - maybe its used for aliases as well
try {
final Field topics = IndexHelpTopic.class.getDeclaredField("allTopics");
topics.setAccessible(true);
@SuppressWarnings("unchecked")
final ArrayList<HelpTopic> as = new ArrayList<>((Collection<HelpTopic>) topics.get(aliases));
for (final String alias : activeAliases) {
final HelpTopic at = new CommandAliasHelpTopic("/" + alias, "/" + getLabel(), help);
as.add(at);
helps.add(at);
}
Collections.sort(as, HelpTopicComparator.helpTopicComparatorInstance());
topics.set(aliases, as);
} catch (final Exception e) {
Skript.outdatedError(e);//, "error registering aliases for /" + getName());
}
}
}
public void unregisterHelp() {
Bukkit.getHelpMap().getHelpTopics().removeAll(helps);
final HelpTopic aliases = Bukkit.getHelpMap().getHelpTopic("Aliases");
if (aliases != null && aliases instanceof IndexHelpTopic) {
try {
final Field topics = IndexHelpTopic.class.getDeclaredField("allTopics");
topics.setAccessible(true);
@SuppressWarnings("unchecked")
final ArrayList<HelpTopic> as = new ArrayList<>((Collection<HelpTopic>) topics.get(aliases));
as.removeAll(helps);
topics.set(aliases, as);
} catch (final Exception e) {
Skript.outdatedError(e);//, "error unregistering aliases for /" + getName());
}
}
helps.clear();
}
public String getName() {
return name;
}
public String getPrefix() {
return prefix;
}
public String getLabel() {
return label;
}
@Nullable
public Timespan getCooldown() {
return cooldown;
}
@Nullable
private String getStorageVariableName(Event event) {
assert cooldownStorage != null;
String variableString = cooldownStorage.getSingle(event);
if (variableString == null)
return null;
if (variableString.startsWith("{"))
variableString = variableString.substring(1);
if (variableString.endsWith("}"))
variableString = variableString.substring(0, variableString.length() - 1);
return variableString;
}
@Nullable
public Date getLastUsage(UUID uuid, Event event) {
if (cooldownStorage == null) {
return lastUsageMap.get(uuid);
} else {
String name = getStorageVariableName(event);
assert name != null;
Object variable = Variables.getVariable(name, null, false);
if (variable != null && !(variable instanceof Date)) {
Skript.warning("Variable {" + name + "} was not a date! You may be using this variable elsewhere. " +
"This warning is letting you know that this variable is now overridden for the command storage.");
return null;
}
return (Date) variable;
}
}
public void setLastUsage(UUID uuid, Event event, @Nullable Date date) {
if (cooldownStorage != null) {
// Using a variable
String name = getStorageVariableName(event);
assert name != null;
Variables.setVariable(name, date, null, false);
} else {
// Use the map
if (date == null)
lastUsageMap.remove(uuid);
else
lastUsageMap.put(uuid, date);
}
}
public long getRemainingMilliseconds(UUID uuid, Event event) {
Date lastUsage = getLastUsage(uuid, event);
if (lastUsage == null)
return 0;
Timespan cooldown = this.cooldown;
assert cooldown != null;
long remaining = cooldown.getAs(Timespan.TimePeriod.MILLISECOND) - getElapsedMilliseconds(uuid, event);
if (remaining < 0)
remaining = 0;
return remaining;
}
public void setRemainingMilliseconds(UUID uuid, Event event, long milliseconds) {
Timespan cooldown = this.cooldown;
assert cooldown != null;
long cooldownMs = cooldown.getAs(Timespan.TimePeriod.MILLISECOND);
if (milliseconds > cooldownMs)
milliseconds = cooldownMs;
setElapsedMilliSeconds(uuid, event, cooldownMs - milliseconds);
}
public long getElapsedMilliseconds(UUID uuid, Event event) {
Date lastUsage = getLastUsage(uuid, event);
return lastUsage == null ? 0 : Date.now().getTime() - lastUsage.getTime();
}
public void setElapsedMilliSeconds(UUID uuid, Event event, long milliseconds) {
Date date = Date.now();
date.subtract(new Timespan(milliseconds));
setLastUsage(uuid, event, date);
}
public String getCooldownBypass() {
return cooldownBypass;
}
public List<String> getAliases() {
return aliases;
}
public List<String> getActiveAliases() {
return activeAliases;
}
public PluginCommand getBukkitCommand() {
return bukkitCommand;
}
@Nullable
public Script getScript() {
return trigger.getScript();
}
@Nullable
@Override
public List<String> onTabComplete(@Nullable CommandSender sender, @Nullable Command command, @Nullable String alias, @Nullable String[] args) {
assert args != null;
int argIndex = args.length - 1;
if (argIndex >= arguments.size())
return Collections.emptyList(); // Too many arguments, nothing to complete
Argument<?> arg = arguments.get(argIndex);
Class<?> argType = arg.getType();
if (argType.equals(Player.class) || argType.equals(OfflinePlayer.class))
return null; // Default completion
return Collections.emptyList(); // No tab completion here!
}
}