forked from EssentialsX/Essentials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUser.java
More file actions
1360 lines (1168 loc) · 48 KB
/
User.java
File metadata and controls
1360 lines (1168 loc) · 48 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
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.earth2me.essentials;
import com.earth2me.essentials.adventure.AdventureUtil;
import com.earth2me.essentials.adventure.ComponentHolder;
import com.earth2me.essentials.commands.IEssentialsCommand;
import com.earth2me.essentials.craftbukkit.Inventories;
import com.earth2me.essentials.economy.EconomyLayer;
import com.earth2me.essentials.economy.EconomyLayers;
import com.earth2me.essentials.messaging.IMessageRecipient;
import com.earth2me.essentials.messaging.SimpleMessageRecipient;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.NumberUtil;
import com.earth2me.essentials.utils.TriState;
import com.earth2me.essentials.utils.VersionUtil;
import com.google.common.collect.Lists;
import net.ess3.api.IEssentials;
import net.ess3.api.MaxMoneyException;
import net.ess3.api.TranslatableException;
import net.ess3.api.events.AfkStatusChangeEvent;
import net.ess3.api.events.JailStatusChangeEvent;
import net.ess3.api.events.MuteStatusChangeEvent;
import net.ess3.api.events.UserBalanceUpdateEvent;
import net.ess3.provider.PlayerLocaleProvider;
import net.essentialsx.api.v2.events.PreTransactionEvent;
import net.essentialsx.api.v2.events.TransactionEvent;
import net.essentialsx.api.v2.services.mail.MailSender;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Statistic;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.inventory.ItemStack;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.WeakHashMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tlLiteral;
import static com.earth2me.essentials.I18n.tlLocale;
public class User extends UserData implements Comparable<User>, IMessageRecipient, net.ess3.api.IUser {
private static final Statistic PLAY_ONE_TICK = EnumUtil.getStatistic("PLAY_ONE_MINUTE", "PLAY_ONE_TICK");
// User modules
private final IMessageRecipient messageRecipient;
private transient final AsyncTeleport teleport;
// User command confirmation strings
private final Map<User, BigDecimal> confirmingPayments = new WeakHashMap<>();
private String confirmingClearCommand;
private String lastHomeConfirmation;
// User teleport variables
private final transient LinkedHashMap<String, TpaRequest> teleportRequestQueue = new LinkedHashMap<>();
// User properties
private transient boolean vanished;
private boolean hidden = false;
private boolean leavingHidden = false;
private boolean rightClickJump = false;
private boolean invSee = false;
private boolean recipeSee = false;
private boolean enderSee = false;
private boolean ignoreMsg = false;
private Boolean toggleShout;
private boolean freeze = false;
// User afk variables
private String afkMessage;
private long afkSince;
private transient Location afkPosition = null;
// Timestamps
private transient long lastOnlineActivity;
private transient long lastThrottledAction;
private transient long lastActivity = System.currentTimeMillis();
private transient long teleportInvulnerabilityTimestamp = 0;
private long lastNotifiedAboutMailsMs;
private long lastHomeConfirmationTimestamp;
// Misc
private transient final List<String> signCopy = Lists.newArrayList("", "", "", "");
private transient long lastVanishTime = System.currentTimeMillis();
private transient int flightTick = -1;
private String lastLocaleString;
private Locale playerLocale;
public User(final Player base, final IEssentials ess) {
super(base, ess);
teleport = new AsyncTeleport(this, ess);
if (isAfk()) {
afkPosition = this.getLocation();
}
if (this.getBase().isOnline()) {
lastOnlineActivity = System.currentTimeMillis();
}
this.messageRecipient = new SimpleMessageRecipient(ess, this);
}
public void update(final Player base) {
setBase(base);
}
public IEssentials getEssentials() {
return ess;
}
@Override
public boolean isAuthorized(final IEssentialsCommand cmd) {
return isAuthorized(cmd, "essentials.");
}
@Override
public boolean isAuthorized(final IEssentialsCommand cmd, final String permissionPrefix) {
return isAuthorized(permissionPrefix + (cmd.getName().equals("r") ? "msg" : cmd.getName()));
}
@Override
public boolean isAuthorized(final String node) {
if (Essentials.TESTING) {
return false;
}
final boolean result = isAuthorizedCheck(node);
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "checking if " + base.getName() + " has " + node + " - " + result);
}
return result;
}
@Override
public boolean isAuthorizedCached(final String node) {
if (Essentials.TESTING) {
return false;
}
final boolean result = isAuthorizedCachedCheck(node);
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "checking if " + base.getName() + " has " + node + " (cached) - " + result);
}
return result;
}
@Override
public boolean isPermissionSet(final String node) {
if (Essentials.TESTING) {
return false;
}
final boolean result = isPermSetCheck(node);
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "checking if " + base.getName() + " has " + node + " (set-explicit) - " + result);
}
return result;
}
/**
* Checks if the given permission is explicitly defined and returns its value, otherwise
* {@link TriState#UNSET}.
*/
public TriState isAuthorizedExact(final String node) {
return isAuthorizedExactCheck(node);
}
private boolean isAuthorizedCheck(final String node) {
if (base instanceof OfflinePlayerStub) {
return false;
}
try {
return ess.getPermissionsHandler().hasPermission(base, node);
} catch (final Exception ex) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage(), ex);
} else {
ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage());
}
return false;
}
}
private boolean isAuthorizedCachedCheck(final String node) {
if (base instanceof OfflinePlayerStub) {
return false;
}
try {
return ess.getPermissionsHandler().hasPermissionCached(base, node);
} catch (final Exception ex) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage(), ex);
} else {
ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage());
}
return false;
}
}
private boolean isPermSetCheck(final String node) {
if (base instanceof OfflinePlayerStub) {
return false;
}
try {
return ess.getPermissionsHandler().isPermissionSet(base, node);
} catch (final Exception ex) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage(), ex);
} else {
ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage());
}
return false;
}
}
private TriState isAuthorizedExactCheck(final String node) {
if (base instanceof OfflinePlayerStub) {
return TriState.UNSET;
}
try {
return ess.getPermissionsHandler().isPermissionSetExact(base, node);
} catch (final Exception ex) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage(), ex);
} else {
ess.getLogger().log(Level.SEVERE, "Permission System Error: " + ess.getPermissionsHandler().getName() + " returned: " + ex.getMessage());
}
return TriState.UNSET;
}
}
@Override
public void healCooldown() throws Exception {
final Calendar now = new GregorianCalendar();
if (getLastHealTimestamp() > 0) {
final double cooldown = ess.getSettings().getHealCooldown();
final Calendar cooldownTime = new GregorianCalendar();
cooldownTime.setTimeInMillis(getLastHealTimestamp());
cooldownTime.add(Calendar.SECOND, (int) cooldown);
cooldownTime.add(Calendar.MILLISECOND, (int) ((cooldown * 1000.0) % 1000.0));
if (cooldownTime.after(now) && !isAuthorized("essentials.heal.cooldown.bypass")) {
throw new TranslatableException("timeBeforeHeal", DateUtil.formatDateDiff(cooldownTime.getTimeInMillis()));
}
}
setLastHealTimestamp(now.getTimeInMillis());
}
@Override
public void giveMoney(final BigDecimal value) throws MaxMoneyException {
giveMoney(value, null);
}
@Override
public void giveMoney(final BigDecimal value, final CommandSource initiator) throws MaxMoneyException {
giveMoney(value, initiator, UserBalanceUpdateEvent.Cause.UNKNOWN);
}
public void giveMoney(final BigDecimal value, final CommandSource initiator, final UserBalanceUpdateEvent.Cause cause) throws MaxMoneyException {
if (value.signum() == 0) {
return;
}
setMoney(getMoney().add(value), cause);
sendTl("addedToAccount", AdventureUtil.parsed(NumberUtil.displayCurrency(value, ess)));
if (initiator != null) {
initiator.sendTl("addedToOthersAccount", AdventureUtil.parsed(NumberUtil.displayCurrency(value, ess)), getDisplayName(), AdventureUtil.parsed(NumberUtil.displayCurrency(getMoney(), ess)));
}
}
@Override
public void payUser(final User reciever, final BigDecimal value) throws Exception {
payUser(reciever, value, UserBalanceUpdateEvent.Cause.UNKNOWN);
}
public void payUser(final User reciever, BigDecimal value, final UserBalanceUpdateEvent.Cause cause) throws Exception {
if (value.compareTo(BigDecimal.ZERO) < 1) {
throw new Exception(tlLocale(playerLocale, "payMustBePositive"));
}
if (canAfford(value)) {
// Call an event for pre-transaction
final PreTransactionEvent preTransactionEvent = new PreTransactionEvent(this.getSource(), reciever, value);
ess.getServer().getPluginManager().callEvent(preTransactionEvent);
if (preTransactionEvent.isCancelled()) {
return;
}
value = preTransactionEvent.getAmount();
setMoney(getMoney().subtract(value), cause);
reciever.setMoney(reciever.getMoney().add(value), cause);
sendTl("moneySentTo", AdventureUtil.parsed(NumberUtil.displayCurrency(value, ess)), reciever.getDisplayName());
reciever.sendTl("moneyRecievedFrom", AdventureUtil.parsed(NumberUtil.displayCurrency(value, ess)), getDisplayName());
final TransactionEvent transactionEvent = new TransactionEvent(this.getSource(), reciever, value);
ess.getServer().getPluginManager().callEvent(transactionEvent);
} else {
throw new ChargeException("notEnoughMoney", AdventureUtil.parsed(NumberUtil.displayCurrency(value, ess)));
}
}
@Override
public void takeMoney(final BigDecimal value) {
takeMoney(value, null);
}
@Override
public void takeMoney(final BigDecimal value, final CommandSource initiator) {
takeMoney(value, initiator, UserBalanceUpdateEvent.Cause.UNKNOWN);
}
public void takeMoney(final BigDecimal value, final CommandSource initiator, final UserBalanceUpdateEvent.Cause cause) {
if (value.signum() == 0) {
return;
}
try {
setMoney(getMoney().subtract(value), cause);
} catch (final MaxMoneyException ex) {
ess.getLogger().log(Level.WARNING, "Invalid call to takeMoney, total balance can't be more than the max-money limit.", ex);
}
sendTl("takenFromAccount", AdventureUtil.parsed(NumberUtil.displayCurrency(value, ess)));
if (initiator != null) {
initiator.sendTl("takenFromOthersAccount", AdventureUtil.parsed(NumberUtil.displayCurrency(value, ess)), getDisplayName(), AdventureUtil.parsed(NumberUtil.displayCurrency(getMoney(), ess)));
}
}
@Override
public boolean canAfford(final BigDecimal cost) {
return canAfford(cost, true);
}
public boolean canAfford(final BigDecimal cost, final boolean permcheck) {
if (cost.signum() <= 0) {
return true;
}
final BigDecimal remainingBalance = getMoney().subtract(cost);
if (!permcheck || isAuthorized("essentials.eco.loan")) {
return remainingBalance.compareTo(ess.getSettings().getMinMoney()) >= 0;
}
return remainingBalance.signum() >= 0;
}
public void dispose() {
ess.runTaskAsynchronously(this::_dispose);
}
private void _dispose() {
if (!base.isOnline()) {
this.base = new OfflinePlayerStub(getConfigUUID(), ess.getServer());
}
cleanup();
}
@Override
public Boolean canSpawnItem(final Material material) {
if (ess.getSettings().permissionBasedItemSpawn()) {
final String name = material.toString().toLowerCase(Locale.ENGLISH).replace("_", "");
if (isAuthorized("essentials.itemspawn.item-all") || isAuthorized("essentials.itemspawn.item-" + name))
return true;
if (VersionUtil.PRE_FLATTENING) {
//noinspection deprecation
final int id = material.getId();
return isAuthorized("essentials.itemspawn.item-" + id);
}
return false;
}
return isAuthorized("essentials.itemspawn.exempt") || !ess.getSettings().itemSpawnBlacklist().contains(material);
}
@Override
public void setLastLocation() {
setLastLocation(this.getLocation());
}
@Override
public void setLogoutLocation() {
setLogoutLocation(this.getLocation());
}
@Override
public void requestTeleport(final User player, final boolean here) {
final TpaRequest request = teleportRequestQueue.getOrDefault(player.getName(), new TpaRequest(player.getName(), player.getUUID()));
request.setTime(System.currentTimeMillis());
request.setHere(here);
request.setLocation(here ? player.getLocation() : this.getLocation());
// Handle max queue size
teleportRequestQueue.remove(request.getName());
if (teleportRequestQueue.size() >= ess.getSettings().getTpaMaxRequests()) {
final List<String> keys = new ArrayList<>(teleportRequestQueue.keySet());
teleportRequestQueue.remove(keys.get(keys.size() - 1));
}
// Add request to queue
teleportRequestQueue.put(request.getName(), request);
}
public Collection<String> getPendingTpaKeys() {
return teleportRequestQueue.keySet();
}
@Override
public boolean hasPendingTpaRequests(boolean inform, boolean excludeHere) {
return getNextTpaRequest(inform, false, excludeHere) != null;
}
public boolean hasOutstandingTpaRequest(String playerUsername, boolean here) {
final TpaRequest request = getOutstandingTpaRequest(playerUsername, false);
return request != null && request.isHere() == here;
}
public @Nullable TpaRequest getOutstandingTpaRequest(String playerUsername, boolean inform) {
if (!teleportRequestQueue.containsKey(playerUsername)) {
return null;
}
final long timeout = ess.getSettings().getTpaAcceptCancellation();
final TpaRequest request = teleportRequestQueue.get(playerUsername);
if (timeout < 1 || System.currentTimeMillis() - request.getTime() <= timeout * 1000) {
return request;
}
teleportRequestQueue.remove(playerUsername);
if (inform) {
sendTl("requestTimedOutFrom", ess.getUser(request.getRequesterUuid()).getDisplayName());
}
return null;
}
public TpaRequest removeTpaRequest(String playerUsername) {
return teleportRequestQueue.remove(playerUsername);
}
@Override
public TpaRequest getNextTpaRequest(boolean inform, boolean ignoreExpirations, boolean excludeHere) {
if (teleportRequestQueue.isEmpty()) {
return null;
}
final long timeout = ess.getSettings().getTpaAcceptCancellation();
final List<String> keys = new ArrayList<>(teleportRequestQueue.keySet());
Collections.reverse(keys);
TpaRequest nextRequest = null;
for (final String key : keys) {
final TpaRequest request = teleportRequestQueue.get(key);
if (timeout < 1 || (System.currentTimeMillis() - request.getTime()) <= TimeUnit.SECONDS.toMillis(timeout)) {
if (excludeHere && request.isHere()) {
continue;
}
if (ignoreExpirations) {
return request;
} else if (nextRequest == null) {
nextRequest = request;
}
} else {
if (inform) {
sendTl("requestTimedOutFrom", ess.getUser(request.getRequesterUuid()).getDisplayName());
}
teleportRequestQueue.remove(key);
}
}
return nextRequest;
}
public String getNick() {
return getNick(true, true);
}
/**
* Needed for backwards compatibility.
*/
public String getNick(@SuppressWarnings("unused") final boolean longNick) {
return getNick(true, true);
}
/**
* Needed for backwards compatibility.
*/
@SuppressWarnings("unused")
public String getNick(@SuppressWarnings("unused") final boolean longNick, final boolean withPrefix, final boolean withSuffix) {
return getNick(withPrefix, withSuffix);
}
public String getNick(final boolean withPrefix, final boolean withSuffix) {
final StringBuilder prefix = new StringBuilder();
final String nickname;
String suffix = "";
final String nick = getNickname();
if (ess.getSettings().isCommandDisabled("nick") || nick == null || nick.isEmpty() || nick.equals(getName())) {
nickname = getName();
} else if (nick.equalsIgnoreCase(getName())) {
nickname = nick;
} else {
if (isAuthorized("essentials.nick.hideprefix")) {
nickname = nick;
} else {
nickname = FormatUtil.replaceFormat(ess.getSettings().getNicknamePrefix()) + nick;
}
suffix = "§r";
}
if (this.getBase().isOp()) {
try {
final String opPrefix = ess.getSettings().getOperatorColor();
if (opPrefix != null && !opPrefix.isEmpty()) {
prefix.insert(0, opPrefix);
suffix = "§r";
}
} catch (final Exception e) {
if (ess.getSettings().isDebug()) {
e.printStackTrace();
}
}
}
if (ess.getSettings().addPrefixSuffix()) {
//These two extra toggles are not documented, because they are mostly redundant #EasterEgg
if (withPrefix || !ess.getSettings().disablePrefix()) {
final String ptext = FormatUtil.replaceFormat(ess.getPermissionsHandler().getPrefix(base));
prefix.insert(0, ptext);
suffix = "§r";
}
if (withSuffix || !ess.getSettings().disableSuffix()) {
final String stext = FormatUtil.replaceFormat(ess.getPermissionsHandler().getSuffix(base));
suffix = stext + "§r";
// :YEP: WHAT ARE THEY DOING?
// :YEP: STILL. LEGACY CODE.
// :YEP: BUT WHY?
// :YEP: I CAN'T BELIEVE THIS!
// Code from 1542 BC #EasterEgg
suffix = suffix.replace("§f§r", "§r").replace("§r§r", "§r");
}
}
final String strPrefix = prefix.toString();
String output = strPrefix + nickname + suffix;
if (output.charAt(output.length() - 1) == '§') {
output = output.substring(0, output.length() - 1);
}
return output;
}
public void setDisplayNick() {
if (base.isOnline() && ess.getSettings().changeDisplayName()) {
this.getBase().setDisplayName(getNick(true));
if (isAfk()) {
updateAfkListName();
} else if (ess.getSettings().changePlayerListName()) {
final String name = getNick(ess.getSettings().isAddingPrefixInPlayerlist(), ess.getSettings().isAddingSuffixInPlayerlist());
try {
this.getBase().setPlayerListName(name);
} catch (final IllegalArgumentException e) {
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "Playerlist for " + name + " was not updated. Name clashed with another online player.");
}
}
}
}
}
@Override
public String getDisplayName() {
//noinspection ConstantConditions
return super.getBase().getDisplayName() == null || (ess.getSettings().hideDisplayNameInVanish() && isHidden()) ? super.getBase().getName() : super.getBase().getDisplayName();
}
@Override
public String getFormattedNickname() {
final String rawNickname = getNickname();
if (rawNickname == null) {
return null;
}
return FormatUtil.replaceFormat(ess.getSettings().getNicknamePrefix() + rawNickname);
}
@Override
public AsyncTeleport getAsyncTeleport() {
return teleport;
}
public long getLastOnlineActivity() {
return lastOnlineActivity;
}
public void setLastOnlineActivity(final long timestamp) {
lastOnlineActivity = timestamp;
}
@Override
public BigDecimal getMoney() {
final long start = System.nanoTime();
final BigDecimal value = _getMoney();
final long elapsed = System.nanoTime() - start;
if (elapsed > ess.getSettings().getEconomyLagWarning()) {
ess.getLogger().log(Level.INFO, "Lag Notice - Slow Economy Response - Request took over {0}ms!", elapsed / 1000000.0);
}
return value;
}
@Override
public void setMoney(final BigDecimal value) throws MaxMoneyException {
setMoney(value, UserBalanceUpdateEvent.Cause.UNKNOWN);
}
private BigDecimal _getMoney() {
if (ess.getSettings().isEcoDisabled()) {
if (ess.getSettings().isDebug()) {
ess.getLogger().info("Internal economy functions disabled, aborting balance check.");
}
return BigDecimal.ZERO;
}
final EconomyLayer layer = EconomyLayers.getSelectedLayer();
if (layer != null && (layer.hasAccount(getBase()) || layer.createPlayerAccount(getBase()))) {
return layer.getBalance(getBase());
}
return super.getMoney();
}
public void setMoney(final BigDecimal value, final UserBalanceUpdateEvent.Cause cause) throws MaxMoneyException {
if (ess.getSettings().isEcoDisabled()) {
if (ess.getSettings().isDebug()) {
ess.getLogger().info("Internal economy functions disabled, aborting balance change.");
}
return;
}
final BigDecimal oldBalance = _getMoney();
final UserBalanceUpdateEvent updateEvent = new UserBalanceUpdateEvent(this.getBase(), oldBalance, value, cause);
ess.getServer().getPluginManager().callEvent(updateEvent);
final BigDecimal newBalance = updateEvent.getNewBalance();
final EconomyLayer layer = EconomyLayers.getSelectedLayer();
if (layer != null && (layer.hasAccount(getBase()) || layer.createPlayerAccount(getBase()))) {
layer.set(getBase(), newBalance);
}
super.setMoney(newBalance, true);
Trade.log("Update", "Set", "API", getName(), new Trade(newBalance, ess), null, null, null, newBalance, ess);
}
public void updateMoneyCache(final BigDecimal value) {
if (ess.getSettings().isEcoDisabled() || !EconomyLayers.isLayerSelected() || super.getMoney().equals(value)) {
return;
}
try {
super.setMoney(value, false);
} catch (final MaxMoneyException ex) {
// We don't want to throw any errors here, just updating a cache
}
}
@SuppressWarnings("deprecation")
@Override
public void setAfk(final boolean set) {
setAfk(set, AfkStatusChangeEvent.Cause.UNKNOWN);
}
@Override
public void setAfk(final boolean set, final AfkStatusChangeEvent.Cause cause) {
final AfkStatusChangeEvent afkEvent = new AfkStatusChangeEvent(this, set, cause);
ess.getServer().getPluginManager().callEvent(afkEvent);
if (afkEvent.isCancelled()) {
return;
}
this.getBase().setSleepingIgnored(this.isAuthorized("essentials.sleepingignored") || set && ess.getSettings().sleepIgnoresAfkPlayers());
if (set && !isAfk()) {
afkPosition = this.getLocation();
this.afkSince = System.currentTimeMillis();
} else if (!set && isAfk()) {
afkPosition = null;
this.afkMessage = null;
this.afkSince = 0;
}
_setAfk(set);
updateAfkListName();
}
private void updateAfkListName() {
if (ess.getSettings().isAfkListName()) {
if (isAfk()) {
final String afkName = ess.getSettings().getAfkListName().replace("{PLAYER}", getDisplayName()).replace("{USERNAME}", getName());
getBase().setPlayerListName(afkName);
} else {
getBase().setPlayerListName(null);
setDisplayNick();
}
}
}
@Deprecated
public boolean toggleAfk() {
return toggleAfk(AfkStatusChangeEvent.Cause.UNKNOWN);
}
public boolean toggleAfk(final AfkStatusChangeEvent.Cause cause) {
setAfk(!isAfk(), cause);
return isAfk();
}
@Override
public boolean isHiddenFrom(Player player) {
if (getBase() instanceof OfflinePlayerStub || player instanceof OfflinePlayerStub) {
return true;
}
return !player.canSee(getBase());
}
@Override
public boolean isHidden() {
return hidden;
}
@Override
public boolean isLeavingHidden() {
return leavingHidden;
}
@Override
public void setLeavingHidden(boolean leavingHidden) {
this.leavingHidden = leavingHidden;
}
@Override
public void setHidden(final boolean hidden) {
this.hidden = hidden;
if (hidden) {
setLastLogout(getLastOnlineActivity());
}
}
public boolean isHidden(final Player player) {
return hidden || isHiddenFrom(player);
}
@Override
public String getFormattedJailTime() {
return DateUtil.formatDateDiff(getOnlineJailedTime() > 0 ? getOnlineJailExpireTime() : getJailTimeout());
}
private long getOnlineJailExpireTime() {
return ((getOnlineJailedTime() - getBase().getStatistic(PLAY_ONE_TICK)) * 50) + System.currentTimeMillis();
}
//Returns true if status expired during this check
@SuppressWarnings("UnusedReturnValue")
public boolean checkJailTimeout(final long currentTime) {
if (getJailTimeout() > 0) {
if (getOnlineJailedTime() > 0) {
if (getOnlineJailedTime() > getBase().getStatistic(PLAY_ONE_TICK)) {
return false;
}
}
if (getJailTimeout() < currentTime && isJailed()) {
final JailStatusChangeEvent event = new JailStatusChangeEvent(this, null, false);
ess.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
setJailTimeout(0);
setOnlineJailedTime(0);
setJailed(false);
sendTl("haveBeenReleased");
setJail(null);
if (ess.getSettings().getTeleportWhenFreePolicy() == ISettings.TeleportWhenFreePolicy.BACK) {
final CompletableFuture<Boolean> future = new CompletableFuture<>();
getAsyncTeleport().back(future);
future.exceptionally(e -> {
getAsyncTeleport().respawn(null, TeleportCause.PLUGIN, new CompletableFuture<>());
return false;
});
} else if (ess.getSettings().getTeleportWhenFreePolicy() == ISettings.TeleportWhenFreePolicy.SPAWN) {
getAsyncTeleport().respawn(null, TeleportCause.PLUGIN, new CompletableFuture<>());
}
return true;
}
}
}
return false;
}
//Returns true if status expired during this check
@SuppressWarnings("UnusedReturnValue")
public boolean checkMuteTimeout(final long currentTime) {
if (getMuteTimeout() > 0 && getMuteTimeout() < currentTime && isMuted()) {
final MuteStatusChangeEvent event = new MuteStatusChangeEvent(this, null, false, getMuteTimeout(), getMuteReason());
ess.getServer().getPluginManager().callEvent(event);
if (!event.isCancelled()) {
setMuteTimeout(0);
sendTl("canTalkAgain");
setMuted(false);
setMuteReason(null);
return true;
}
}
return false;
}
@Override
public long getLastActivityTime() {
return this.lastActivity;
}
@Deprecated
public void updateActivity(final boolean broadcast) {
updateActivity(broadcast, AfkStatusChangeEvent.Cause.UNKNOWN);
}
public void updateActivity(final boolean broadcast, final AfkStatusChangeEvent.Cause cause) {
if (isAfk()) {
setAfk(false, cause);
if (broadcast && !isHidden() && !isAfk()) {
setDisplayNick();
if (ess.getSettings().broadcastAfkMessage()) {
ess.broadcastTl(this, u -> u == this, "userIsNotAway", getDisplayName());
}
sendTl("userIsNotAwaySelf", getDisplayName());
}
}
lastActivity = System.currentTimeMillis();
}
public void updateActivityOnMove(final boolean broadcast) {
if (ess.getSettings().cancelAfkOnMove()) {
updateActivity(broadcast, AfkStatusChangeEvent.Cause.MOVE);
}
}
public void updateActivityOnInteract(final boolean broadcast) {
if (ess.getSettings().cancelAfkOnInteract()) {
updateActivity(broadcast, AfkStatusChangeEvent.Cause.INTERACT);
}
}
public void updateActivityOnChat(final boolean broadcast) {
if (ess.getSettings().cancelAfkOnChat()) {
//Chat happens async, make sure we have a sync context
ess.scheduleSyncDelayedTask(() -> updateActivity(broadcast, AfkStatusChangeEvent.Cause.CHAT));
}
}
public void checkActivity() {
// Graceful time before the first afk check call.
if (System.currentTimeMillis() - lastActivity <= 10000) {
return;
}
final long autoafktimeout = ess.getSettings().getAutoAfkTimeout();
// Checks if the player has been inactive for longer than the configured auto-afk-timeout time.
if (autoafktimeout > 0
&& lastActivity > 0 && (lastActivity + (autoafktimeout * 1000)) < System.currentTimeMillis()
&& !isAuthorized("essentials.kick.exempt")
&& !isAuthorized("essentials.afk.kickexempt")) {
lastActivity = 0;
final double kickTime = autoafktimeout / 60.0;
// If `afk-timeout-command` in config.yml is empty, use default Essentials kicking behaviour instead of executing a command.
if (ess.getSettings().getAfkTimeoutCommands().isEmpty()) {
this.getBase().kickPlayer(ess.getAdventureFacet().miniToLegacy(playerTl("autoAfkKickReason", kickTime)));
for (final User user : ess.getOnlineUsers()) {
if (user.isAuthorized("essentials.kick.notify")) {
user.sendTl("playerKicked", Console.displayName(), getName(), user.playerTl("autoAfkKickReason", kickTime));
}
}
} else {
// If `afk-timeout-commands` in config.yml is populated, execute the command(s) instead of kicking the player.
for (final String command : ess.getSettings().getAfkTimeoutCommands()) {
if (command == null || command.isEmpty()){
continue;
}
// Replace placeholders in the command with actual values.
final String cmd = command.replace("{USERNAME}", getName()).replace("{KICKTIME}", String.valueOf(kickTime));
ess.getServer().dispatchCommand(ess.getServer().getConsoleSender(), cmd);
}
}
}
final long autoafk = ess.getSettings().getAutoAfk();
if (!isAfk() && autoafk > 0 && lastActivity + autoafk * 1000 < System.currentTimeMillis() && isAuthorizedCached("essentials.afk.auto")) {
setAfk(true, AfkStatusChangeEvent.Cause.ACTIVITY);
if (isAfk() && !isHidden()) {
setDisplayNick();
if (ess.getSettings().broadcastAfkMessage()) {
ess.broadcastTl(this, u -> u == this, "userIsAway", getDisplayName());
}
sendTl("userIsAwaySelf", getDisplayName());
}
}
}
public Location getAfkPosition() {
return afkPosition;
}
@Override
public boolean isGodModeEnabled() {
if (super.isGodModeEnabled()) {
// This enables the no-god-in-worlds functionality where the actual player god mode state is never modified in disabled worlds,
// but this method gets called every time the player takes damage. In the case that the world has god-mode disabled then this method
// will return false and the player will take damage, even though they are in god mode (isGodModeEnabledRaw()).
//noinspection ConstantConditions
if (!ess.getSettings().getNoGodWorlds().contains(this.getLocation().getWorld().getName())) {
return true;
}
}
if (isAfk()) {
// Protect AFK players by representing them in a god mode state to render them invulnerable to damage.
return ess.getSettings().getFreezeAfkPlayers();
}
return false;
}
public boolean isGodModeEnabledRaw() {
return super.isGodModeEnabled();
}
@Override
public String getGroup() {
final String result = ess.getPermissionsHandler().getGroup(base);
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "looking up groupname of " + base.getName() + " - " + result);
}
return result;
}
@Override
public boolean inGroup(final String group) {
final boolean result = ess.getPermissionsHandler().inGroup(base, group);
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "checking if " + base.getName() + " is in group " + group + " - " + result);
}
return result;
}
@Override
public boolean canBuild() {
if (this.getBase().isOp()) {
return true;
}
return ess.getPermissionsHandler().canBuild(base, getGroup());
}
@SuppressWarnings("deprecation")
@Override
@Deprecated
public long getTeleportRequestTime() {
final TpaRequest request = getNextTpaRequest(false, false, false);
return request == null ? 0L : request.getTime();
}
public boolean isInvSee() {
return invSee;
}
public void setInvSee(final boolean set) {
invSee = set;
}
public boolean isEnderSee() {
return enderSee;
}
public void setEnderSee(final boolean set) {
enderSee = set;
}
@Override
public void enableInvulnerabilityAfterTeleport() {
final long time = ess.getSettings().getTeleportInvulnerability();
if (time > 0) {
teleportInvulnerabilityTimestamp = System.currentTimeMillis() + time;
}
}