/
BukkitScriptEvent.java
593 lines (557 loc) · 22.6 KB
/
BukkitScriptEvent.java
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
package com.denizenscript.denizen.events;
import com.denizenscript.denizen.flags.FlagManager;
import com.denizenscript.denizen.objects.*;
import com.denizenscript.denizen.objects.notable.NotableManager;
import com.denizenscript.denizen.tags.BukkitTagContext;
import com.denizenscript.denizen.utilities.DenizenAPI;
import com.denizenscript.denizen.utilities.implementation.BukkitScriptEntryData;
import com.denizenscript.denizencore.objects.core.ScriptTag;
import com.denizenscript.denizencore.utilities.Deprecations;
import com.denizenscript.denizencore.utilities.debugging.Debug;
import com.denizenscript.denizencore.events.ScriptEvent;
import com.denizenscript.denizencore.utilities.CoreUtilities;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.*;
import org.bukkit.event.*;
import org.bukkit.plugin.EventExecutor;
import org.bukkit.plugin.IllegalPluginAccessException;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.RegisteredListener;
import org.bukkit.scheduler.BukkitRunnable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.regex.Pattern;
public abstract class BukkitScriptEvent extends ScriptEvent {
public boolean couldMatchItem(String text) {
if (text.equals("item")) {
return true;
}
if (MaterialTag.matches(text) || ItemTag.matches(text)) {
return true;
}
if (text.contains("*")) {
return true;
}
if (text.startsWith("regex:")) {
return true;
}
// This one must be last.
if (text.contains("|")) {
for (String subMatch : text.split("\\|")) {
if (!couldMatchItem(subMatch)) {
return false;
}
}
return true;
}
return false;
}
public BukkitTagContext getTagContext(ScriptPath path) {
BukkitTagContext context = (BukkitTagContext) getScriptEntryData().getTagContext();
context.script = new ScriptTag(path.container);
return context;
}
public static Class<? extends Event> getRegistrationClass(Class<? extends Event> clazz) {
try {
clazz.getDeclaredMethod("getHandlerList");
return clazz;
}
catch (NoSuchMethodException var3) {
if (clazz.getSuperclass() != null && !clazz.getSuperclass().equals(Event.class) && Event.class.isAssignableFrom(clazz.getSuperclass())) {
return getRegistrationClass(clazz.getSuperclass().asSubclass(Event.class));
}
else {
throw new IllegalPluginAccessException("Unable to find handler list for event " + clazz.getName() + ". Static getHandlerList method required!");
}
}
}
public static HandlerList getEventListeners(Class<? extends Event> type) {
try {
Method method = getRegistrationClass(type).getDeclaredMethod("getHandlerList");
method.setAccessible(true);
return (HandlerList) method.invoke(null);
}
catch (Exception var3) {
throw new IllegalPluginAccessException(var3.toString());
}
}
private static Field REGISTERED_LISTENER_EXECUTOR_FIELD;
static {
try {
REGISTERED_LISTENER_EXECUTOR_FIELD = RegisteredListener.class.getDeclaredField("executor");
REGISTERED_LISTENER_EXECUTOR_FIELD.setAccessible(true);
}
catch (NoSuchFieldException ex) {
Debug.echoError(ex);
}
}
public static EventExecutor getExecutor(RegisteredListener listener) {
try {
return (EventExecutor) REGISTERED_LISTENER_EXECUTOR_FIELD.get(listener);
}
catch (IllegalAccessException ex) {
Debug.echoError(ex);
}
return null;
}
public HashMap<EventPriority, BukkitScriptEvent> priorityHandlers;
public List<Map.Entry<RegisteredListener, HandlerList>> registeredHandlers;
// <--[language]
// @name Bukkit Event Priority
// @group Script Events
// @description
// Script events that are backed by standard Bukkit events are able to control what underlying Bukkit event priority
// they register as.
// This can be useful, for example, if a different plugin is cancelling the event at a later priority,
// and you're writing a script that needs to un-cancel the event.
// This can be done using the "bukkit_priority" switch.
// Valid priorities, in order of execution, are: LOWEST, LOW, NORMAL, HIGH, HIGHEST, MONITOR.
// Monitor is executed last, and is intended to only be used when reading the results of an event but not changing it.
// The default priority is "normal".
// -->
@Override
public void fire() {
if (!Bukkit.isPrimaryThread()) {
if (Debug.verbose) {
Debug.log("Event is firing async: " + getName());
}
BukkitScriptEvent altEvent = (BukkitScriptEvent) clone();
new BukkitRunnable() {
@Override
public void run() {
altEvent.fire();
}
}.runTask(DenizenAPI.getCurrentInstance());
return;
}
super.fire();
}
public void fire(Event event) {
if (event instanceof Cancellable) {
Cancellable cancellable = (Cancellable) event;
cancelled = cancellable.isCancelled();
boolean wasCancelled = cancelled;
fire();
if (cancelled != wasCancelled) {
cancellable.setCancelled(cancelled);
}
}
else {
cancelled = false;
fire();
}
}
@Override
public void destroy() {
if (priorityHandlers != null) {
for (BukkitScriptEvent event : priorityHandlers.values()) {
event.destroy();
}
priorityHandlers = null;
}
if (registeredHandlers != null) {
for (Map.Entry<RegisteredListener, HandlerList> handler : registeredHandlers) {
handler.getValue().unregister(handler.getKey());
}
registeredHandlers = null;
}
}
@Override
public void init() {
if (this instanceof Listener) {
initListener((Listener) this);
}
}
public void initListener(Listener listener) {
if (priorityHandlers == null) {
priorityHandlers = new HashMap<>();
}
for (ScriptPath path : new ArrayList<>(eventPaths)) {
String bukkitPriority = path.switches.get("bukkit_priority");
if (bukkitPriority != null) {
try {
EventPriority priority = EventPriority.valueOf(bukkitPriority.toUpperCase());
BukkitScriptEvent handler = priorityHandlers.get(priority);
if (handler == null) {
handler = (BukkitScriptEvent) clone();
handler.eventPaths = new ArrayList<>();
handler.priorityHandlers = null;
handler.registeredHandlers = null;
priorityHandlers.put(priority, handler);
handler.initForPriority(priority, (Listener) handler);
}
handler.eventPaths.add(path);
eventPaths.remove(path);
}
catch (IllegalArgumentException ex) {
Debug.echoError("Invalid 'bukkit_priority' switch for event '" + path.event + "' in script '" + path.container.getName() + "'.");
Debug.echoError(ex);
}
}
}
if (!eventPaths.isEmpty()) {
initForPriority(EventPriority.NORMAL, listener);
}
}
public void initForPriority(EventPriority priority, Listener listener) {
if (registeredHandlers == null) {
registeredHandlers = new ArrayList<>();
}
Plugin plugin = DenizenAPI.getCurrentInstance();
for (Map.Entry<Class<? extends Event>, Set<RegisteredListener>> entry :
plugin.getPluginLoader().createRegisteredListeners(listener, plugin).entrySet()) {
for (RegisteredListener registeredListener : entry.getValue()) {
RegisteredListener newListener = new RegisteredListener(listener, getExecutor(registeredListener), priority, plugin, false);
HandlerList handlers = getEventListeners(getRegistrationClass(entry.getKey()));
handlers.register(newListener);
registeredHandlers.add(new HashMap.SimpleEntry<>(newListener, handlers));
}
}
}
public boolean runInCheck(ScriptPath path, Location location) {
return runInCheck(path, location, "in");
}
public boolean runInCheck(ScriptPath path, Location location, String innote) {
String it = path.switches.get(innote);
if (it == null) {
int index;
for (index = 0; index < path.eventArgsLower.length; index++) {
if (path.eventArgsLower[index].equals(innote)) {
break;
}
}
if (index >= path.eventArgsLower.length) {
// No 'in ...' specified
return true;
}
if (location == null) {
return false;
}
Deprecations.inAreaSwitchFormat.warn();
it = path.eventArgLowerAt(index + 1);
if (it.equals("notable")) {
String subit = path.eventArgLowerAt(index + 2);
if (subit.equals("cuboid")) {
return CuboidTag.getNotableCuboidsContaining(location).size() > 0;
}
else if (subit.equals("ellipsoid")) {
return EllipsoidTag.getNotableEllipsoidsContaining(location).size() > 0;
}
else {
Debug.echoError("Invalid event 'IN ...' check [" + getName() + "] ('in notable ???'): '" + path.event + "' for " + path.container.getName());
return false;
}
}
}
if (location == null) {
return false;
}
String lower = CoreUtilities.toLowerCase(it);
if (lower.equals("cuboid")) {
return CuboidTag.getNotableCuboidsContaining(location).size() > 0;
}
else if (lower.equals("ellipsoid")) {
return EllipsoidTag.getNotableEllipsoidsContaining(location).size() > 0;
}
else if (WorldTag.matches(it)) {
return CoreUtilities.toLowerCase(location.getWorld().getName()).equals(lower);
}
else if (CuboidTag.matches(it)) {
CuboidTag cuboid = CuboidTag.valueOf(it);
if (cuboid == null || !cuboid.isUnique()) {
Debug.echoError("Invalid event 'in:<area>' switch [" + getName() + "] (invalid cuboid): '" + path.event + "' for " + path.container.getName());
return false;
}
return cuboid.isInsideCuboid(location);
}
else if (EllipsoidTag.matches(it)) {
EllipsoidTag ellipsoid = EllipsoidTag.valueOf(it);
if (ellipsoid == null || !ellipsoid.isUnique()) {
Debug.echoError("Invalid event 'in:<area>' switch [" + getName() + "] (invalid ellipsoid): '" + path.event + "' for " + path.container.getName());
return false;
}
return ellipsoid.contains(location);
}
else {
Debug.echoError("Invalid event 'in:<area>' switch [" + getName() + "] ('in:???'): '" + path.event + "' for " + path.container.getName());
return false;
}
}
public boolean tryLocation(LocationTag location, String comparedto) {
if (comparedto == null || comparedto.length() == 0) {
Debug.echoError("Null or empty location string to compare");
return false;
}
if (comparedto.equals("notable")) {
return true;
}
comparedto = "l@" + comparedto;
LocationTag loc = LocationTag.valueOf(comparedto);
if (loc == null) {
Debug.echoError("Invalid location in location comparison string: " + comparedto);
return false;
}
return loc.getBlock().equals(location.getBlock());
}
public boolean runWithCheck(ScriptPath path, ItemTag held) {
String with = path.switches.get("with");
if (with != null) {
if (with.equalsIgnoreCase("item")) {
return true;
}
if (held == null || !tryItem(held, with)) {
return false;
}
}
return true;
}
public boolean runFlaggedCheck(ScriptPath path, PlayerTag player) {
return runFlaggedCheck(path, "flagged", player);
}
public boolean runFlaggedCheck(ScriptPath path, String switchName, PlayerTag player) {
String flagged = path.switches.get(switchName);
if (flagged == null) {
return true;
}
if (player == null) {
return false;
}
if (!FlagManager.playerHasFlag(player, flagged)) {
return false;
}
return true;
}
public boolean runPermissionCheck(ScriptPath path, PlayerTag player) {
return runPermissionCheck(path, "permission", player);
}
public boolean runPermissionCheck(ScriptPath path, String switchName, PlayerTag player) {
String perm = path.switches.get(switchName);
if (perm == null) {
return true;
}
if (player == null || !player.isOnline()) {
return false;
}
if (!player.getPlayerEntity().hasPermission(perm)) {
return false;
}
return true;
}
// <--[language]
// @name Player Event Switches
// @group Script Events
// @description
// There are a few special switches available to any script event with a linked player.
//
// The "flagged:<flag name>" will limit the event to only fire when the player has the flag with the specified name.
// It can be used like "on player breaks block flagged:nobreak:" (that would be used alongside "- flag player nobreak").
//
// The "permission:<perm key>" will limit the event to only fire when the player has the specified permission key.
// It can be used like "on player breaks block permission:denizen.my.perm:"
//
// Note that these switches will be ignored for events that do not have a linked player.
// Be cautious with events that will only sometimes have a linked player.
// -->
public boolean runAutomaticPlayerSwitches(ScriptPath path) {
BukkitScriptEntryData data = (BukkitScriptEntryData) getScriptEntryData();
if (!data.hasPlayer()) {
return true;
}
if (!runFlaggedCheck(path, data.getPlayer())) {
return false;
}
if (!runPermissionCheck(path, data.getPlayer())) {
return false;
}
return true;
}
@Override
public boolean matches(ScriptPath path) {
if (!runAutomaticPlayerSwitches(path)) {
return false;
}
return true;
}
// <--[language]
// @name Safety In Events
// @group Script Events
// @description
// One of the more common issues in Denizen scripts (particularly ones relating to inventories) is
// *event safety*. That is, using commands inside an event that don't get along with the event.
//
// The most common example of this is editing a player's inventory, within an inventory-related event.
// Generally speaking, this problem becomes relevant any time an edit is made to something involved with an event,
// within the firing of that event.
// Take the following examples:
// <code>
// on player clicks in inventory:
// - take iteminhand
// on entity damaged:
// - remove <context.entity>
// </code>
//
// In both examples above, something related to the event (the player's inventory, and the entity being damaged)
// is being modified within the event itself.
// These break due a rather important reason: The event is firing before and/or during the change to the object.
// Most events operate this way. A series of changes *to the object* are pending, and will run immediately after
// your script does... the problems resultant can range from your changes being lost to situational issues
// (eg an inventory suddenly being emptied entirely) to even server crashes!
// The second example event also is a good example of another way this can go wrong:
// Many scripts and plugins will listen to the entity damage event, in ways that are simply unable to handle
// the damaged entity just being gone now (when the event fires, it's *guaranteed* the entity is still present
// but that remove command breaks the guarantee!).
//
// The solution to this problem is simple: Just wait a tick. Literally.
// <code>
// on player clicks in inventory:
// - wait 1t
// - take iteminhand
// on entity damaged:
// - wait 1t
// - if <context.entity.is_spawned||false>:
// - remove <context.entity>
// </code>
//
// By waiting a tick, you cause your script to run *after* the event, and thus outside of the problem area.
// And thus should be fine. One limitation you should note is demonstrated in the second example event:
// The normal guarantees of the event are no longer present (eg that the entity is still valid) and as such
// you should validate these expectations remain true after the event (as seen with the 'if is_spawned' check).
//
// -->
public boolean tryInventory(InventoryTag inv, String comparedto) {
comparedto = CoreUtilities.toLowerCase(comparedto);
if (comparedto.equals("inventory")) {
return true;
}
if (comparedto.equals("notable")) {
return NotableManager.isSaved(inv);
}
Pattern regexd = regexHandle(comparedto);
if (equalityCheck(inv.getInventoryType().name(), comparedto, regexd)) {
return true;
}
if (equalityCheck(inv.getIdType(), comparedto, regexd)) {
return true;
}
if (equalityCheck(inv.getIdHolder(), comparedto, regexd)) {
return true;
}
if (inv.scriptName != null && equalityCheck(inv.scriptName, comparedto, regexd)) {
return true;
}
String notedId = NotableManager.getSavedId(inv);
if (notedId != null && equalityCheck(notedId, comparedto, regexd)) {
return true;
}
return false;
}
public boolean tryItem(ItemTag item, String comparedto) {
if (comparedto == null || comparedto.isEmpty() || item == null) {
return false;
}
comparedto = CoreUtilities.toLowerCase(comparedto);
if (comparedto.equals("item")) {
return true;
}
if (comparedto.equals("potion") && CoreUtilities.toLowerCase(item.getItemStack().getType().name()).contains("potion")) {
return true;
}
MaterialTag quickOf = MaterialTag.quickOfNamed(comparedto);
if (quickOf != null) {
MaterialTag mat = item.getMaterial();
if (quickOf.getMaterial() != mat.getMaterial()) {
return false;
}
if (quickOf.equals(mat)) {
return true;
}
}
Pattern regexd = regexHandle(comparedto);
item = new ItemTag(item.getItemStack().clone());
item.setAmount(1);
if (equalityCheck(item.identify().substring("i@".length()), comparedto, regexd)) {
return true;
}
else if (equalityCheck(item.identifyMaterialNoIdentifier(), comparedto, regexd)) {
return true;
}
else if (equalityCheck(item.identifySimple().substring("i@".length()), comparedto, regexd)) {
return true;
}
item.setDurability((short) 0);
if (equalityCheck(item.identifyMaterialNoIdentifier(), comparedto, regexd)) {
return true;
}
return false;
}
public boolean tryMaterial(MaterialTag mat, String comparedto) {
if (comparedto == null || comparedto.isEmpty() || mat == null) {
return false;
}
comparedto = CoreUtilities.toLowerCase(comparedto);
if (comparedto.equals("block") || comparedto.equals("material")) {
return true;
}
MaterialTag quickOf = MaterialTag.quickOfNamed(comparedto);
if (quickOf != null) {
if (quickOf.getMaterial() != mat.getMaterial()) {
return false;
}
if (quickOf.equals(mat)) {
return true;
}
}
Pattern regexd = regexHandle(comparedto);
if (equalityCheck(mat.realName(), comparedto, regexd)) {
return true;
}
else if (equalityCheck(mat.identifyNoIdentifier(), comparedto, regexd)) {
return true;
}
else if (equalityCheck(mat.identifySimpleNoIdentifier(), comparedto, regexd)) {
return true;
}
else if (equalityCheck(mat.identifyFullNoIdentifier(), comparedto, regexd)) {
return true;
}
return false;
}
public boolean tryEntity(EntityTag entity, String comparedto) {
if (comparedto == null || comparedto.isEmpty() || entity == null) {
return false;
}
Entity bEntity = entity.getBukkitEntity();
comparedto = CoreUtilities.toLowerCase(comparedto);
if (comparedto.equals("entity")) {
return true;
}
else if (comparedto.equals("npc")) {
return entity.isCitizensNPC();
}
else if (comparedto.equals("player")) {
return entity.isPlayer();
}
else if (comparedto.equals("vehicle")) {
return bEntity instanceof Vehicle;
}
else if (comparedto.equals("fish")) {
return bEntity instanceof Fish;
}
else if (comparedto.equals("projectile")) {
return bEntity instanceof Projectile;
}
else if (comparedto.equals("hanging")) {
return bEntity instanceof Hanging;
}
Pattern regexd = regexHandle(comparedto);
if (entity.getEntityScript() != null && equalityCheck(entity.getEntityScript(), comparedto, regexd)) {
return true;
}
else if (equalityCheck(entity.getEntityType().getLowercaseName(), comparedto, regexd)) {
return true;
}
return false;
}
}