-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSyncInv.java
More file actions
1248 lines (1148 loc) · 55.3 KB
/
Copy pathSyncInv.java
File metadata and controls
1248 lines (1148 loc) · 55.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
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 de.minebench.syncinv;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
import com.lishid.openinv.OpenInv;
import com.lishid.openinv.command.OpenInvCommand;
import com.mojang.authlib.GameProfile;
import de.minebench.syncinv.listeners.MapCreationListener;
import de.minebench.syncinv.listeners.PlayerConnectionValidateLoginListener;
import de.minebench.syncinv.listeners.PlayerFreezeListener;
import de.minebench.syncinv.listeners.PlayerJoinListener;
import de.minebench.syncinv.listeners.PlayerQuitListener;
import de.minebench.syncinv.listeners.PlayerLoginListener;
import de.minebench.syncinv.messenger.Message;
import de.minebench.syncinv.messenger.MessageType;
import de.minebench.syncinv.messenger.PlayerDataQuery;
import de.minebench.syncinv.messenger.RedisMessenger;
import de.minebench.syncinv.messenger.ServerMessenger;
import org.apache.maven.artifact.versioning.ComparableVersion;
import org.bukkit.ChatColor;
import org.bukkit.GameRule;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.Sound;
import org.bukkit.Statistic;
import org.bukkit.World;
import org.bukkit.advancement.Advancement;
import org.bukkit.advancement.AdvancementProgress;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.map.MapCanvas;
import org.bukkit.map.MapRenderer;
import org.bukkit.map.MapView;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.IOException;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.util.AbstractMap;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.logging.Level;
/*
* SyncInv
* Copyright (c) 2021 Max Lee aka Phoenix616 (max@themoep.de)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
public final class SyncInv extends JavaPlugin {
/**
* Whether or not we should query the inventories from other servers
* or just move players to the server that has the latest data
*/
private boolean queryInventories;
/**
* Reference to the OpenInv plugin to load data for the query option
*/
private OpenInv openInv = null;
/**
* The messenger for communications between the servers
*/
private ServerMessenger messenger;
/**
* The cache for player data which should only get applied when the player is online
*/
private Cache<UUID, Map.Entry<PlayerData, Runnable>> playerDataCache;
/**
* Sync data with all servers in a group when a player logs out
*/
private boolean syncWithGroupOnLogout;
/**
* Store player data even if the player never joined the server
*/
private boolean storeUnknownPlayers;
/**
* The amount of seconds we should wait for a query to stopTimeout
*/
private int queryTimeout;
/**
* Should we apply data of queries that weren't answered by every server
*/
private boolean applyTimedOutQueries;
/**
* What to sync
*/
private EnumSet<SyncType> enabledSyncTypes;
/**
* The statistics filter mode
*/
private FilterMode statisticsFilterMode = FilterMode.DENY;
/**
* The statistics filter list
*/
private Set<Statistic> statisticsFilter = new HashSet<>();
/**
* Whether or not the plugin is currently disabling
*/
private boolean disabling = false;
/**
* Whether or not the plugin is in debugging mode
*/
private boolean debug;
/**
* The id of the newest map that was seen on this server
*/
private int newestMap = 0;
// Unknown player storing
private Function<GameProfile, OfflinePlayer> getOfflinePlayer = null;
private Method methodGetHandle = null;
// Offline player health setting
private Method methodSetHealth;
// Map syncing
private Field fieldWorldMap;
private Field fieldMapColor;
private Field fieldMapWorldId;
private File playerDataFolder;
@Override
public void onEnable() {
// Plugin startup logic
loadConfig();
playerDataFolder = getServer().getMinecraftVersion().startsWith("1.")
? new File(getServer().getWorlds().getFirst().getWorldFolder(), "playerdata")
: new File(new File(getServer().getWorlds().getFirst().getWorldFolder(), "players"), "data");
MethodHandle tempUUIDGetterHandle = null;
try {
tempUUIDGetterHandle = MethodHandles.privateLookupIn(GameProfile.class, MethodHandles.lookup()).findGetter(GameProfile.class, "id", UUID.class);
} catch (NoSuchFieldException | IllegalAccessException e) {
getLogger().log(Level.SEVERE, "Could not get MethodHandle to access uuids from GameProfile. If anything happens, we will be unable to log the uuids!", e);
}
// java being java. We can't assign a final variable in a try block.
final MethodHandle uuidGetterHandle = tempUUIDGetterHandle;
try {
Method methodGetOfflinePlayer = getServer().getClass().getMethod("getOfflinePlayer", GameProfile.class);
getOfflinePlayer = (gameProfile -> {
try {
return (OfflinePlayer) methodGetOfflinePlayer.invoke(getServer(), gameProfile);
} catch (IllegalAccessException | InvocationTargetException e) {
if (uuidGetterHandle != null) {
try {
logDebug("Could not create offline player for " + uuidGetterHandle.invoke(gameProfile) + "! " + e.getMessage());
} catch (Throwable ex) {
logDebug("Could not create offline player. " + e.getMessage());
logDebug("And uuid lookup failed: " + ex.getMessage());
}
}
}
return null;
});
} catch (NoSuchMethodException e) {
try {
Class nameAndIdClass = Class.forName("net.minecraft.server.players.NameAndId");
Constructor nameAndIdConstructor = nameAndIdClass.getConstructor(GameProfile.class);
Method methodGetOfflinePlayer = getServer().getClass().getMethod("getOfflinePlayer", nameAndIdClass);
getOfflinePlayer = (gameProfile -> {
try {
Object nameAndId = nameAndIdConstructor.newInstance(gameProfile);
return (OfflinePlayer) methodGetOfflinePlayer.invoke(getServer(), nameAndId);
} catch (IllegalAccessException | InvocationTargetException | InstantiationException e1) {
if (uuidGetterHandle != null) {
try {
logDebug("Could not create offline player for " + uuidGetterHandle.invoke(gameProfile) + "! " + e.getMessage());
} catch (Throwable e2) {
logDebug("Could not create offline player. " + e.getMessage());
logDebug("And uuid lookup failed: " + e2.getMessage());
}
}
}
return null;
});
} catch (NoSuchMethodException | ClassNotFoundException e2) {
if (storeUnknownPlayers) {
getLogger().log(Level.WARNING, "Could not load method required to store unknown players. Disabling it!", e);
storeUnknownPlayers = false;
}
}
}
playerDataCache = CacheBuilder.newBuilder().expireAfterWrite(queryTimeout, TimeUnit.SECONDS).build();
try {
messenger = new RedisMessenger(this);
messenger.hello();
} catch (Exception e) {
messenger = null;
}
getServer().getPluginManager().registerEvents(new PlayerJoinListener(this), this);
try {
Class.forName("io.papermc.paper.event.connection.PlayerConnectionValidateLoginEvent");
getServer().getPluginManager().registerEvents(new PlayerConnectionValidateLoginListener(this), this);
logDebug("Using Paper connection validate login event");
} catch (ClassNotFoundException e) {
getServer().getPluginManager().registerEvents(new PlayerLoginListener(this), this);
logDebug("Using legacy login event");
}
getServer().getPluginManager().registerEvents(new PlayerQuitListener(this), this);
getServer().getPluginManager().registerEvents(new PlayerFreezeListener(this), this);
getServer().getPluginManager().registerEvents(new MapCreationListener(this), this);
getServer().getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
getCommand("syncinv").setExecutor(this);
if (openInv != null) {
// ensure minimum OpenInv version is present.
if (storeUnknownPlayers && new ComparableVersion(openInv.getPluginMeta().getVersion()).compareTo(new ComparableVersion("5.1.7")) < 0) {
getLogger().severe(
"Warning: You are using a not supported Version of OpenInv! " +
"Please update to Version 5.1.7 or higher! " +
"With the wrong version version present storing unknown players will fail!");
}
OpenInvCommand openInvCommand = (OpenInvCommand) openInv.getCommand("openinv").getExecutor();
CommandExecutor forwarding = (sender, command, label, args) -> {
if (sender instanceof Player && args.length > 0 && (!getMessenger().isAllowedToBeAlone() || !getMessenger().isAlone())) {
if ("?".equalsIgnoreCase(args[0])) {
return openInvCommand.onCommand(sender, command, label, args);
}
Player player = getServer().getPlayer(args[0]);
if (player == null || !player.isOnline()) {
getServer().getScheduler().runTaskAsynchronously(this, () -> {
OfflinePlayer offlinePlayer = openInv.matchPlayer(args[0]);
if (offlinePlayer != null && (offlinePlayer.hasPlayedBefore() || offlinePlayer.isOnline())) {
PlayerDataQuery q = getMessenger().queryData(offlinePlayer.getUniqueId(), (query) -> {
if (getServer().getPlayer(query.getPlayerId()) != null) {
openInvCommand.onCommand(sender, command, label, args);
return;
}
getMessenger().removeQuery(query.getPlayerId());
if (!((Player) sender).isOnline()) {
return;
}
if (query.getYoungestServer() == null) {
openInvCommand.onCommand(sender, command, label, args);
} else {
sender.sendMessage(ChatColor.RED + "Current server does not have newest player data! "
+ ChatColor.GRAY + "Connecting to server " + query.getYoungestServer() + " which has the newest data...");
connectToServer(((Player) sender).getUniqueId(), query.getYoungestServer());
}
});
if (q == null) {
sender.sendMessage(ChatColor.RED + "Could not query information from other servers! Take a look at the log for more details.");
}
} else {
sender.sendMessage(ChatColor.RED + "Player not found!");
}
});
return true;
}
}
return openInvCommand.onCommand(sender, command, label, args);
};
getCommand("openinv").setExecutor(forwarding);
getCommand("openender").setExecutor(forwarding);
}
}
/**
* Check if the plugin should sync a certain type
* @param syncType The type to check
* @return Whether or not it should be synced
*/
public boolean shouldSync(SyncType syncType) {
return enabledSyncTypes.contains(syncType);
}
/**
* Check if the plugin should sync any of the provided types
* @param syncTypes The types to check
* @return Whether or not it should be synced
*/
public boolean shouldSyncAny(SyncType... syncTypes) {
for (SyncType syncType : syncTypes) {
if (shouldSync(syncType)) {
return true;
}
}
return false;
}
private boolean disableSync(SyncType syncType) {
return enabledSyncTypes.remove(syncType);
}
@Override
public void onDisable() {
disabling = true;
if (getMessenger() != null) {
for (Player player : getServer().getOnlinePlayers()) {
getMessenger().sendGroupMessage(new Message(getMessenger().getServerName(), System.currentTimeMillis(), MessageType.DATA, getData(player)), true);
}
getMessenger().goodbye();
}
}
public void loadConfig() {
saveDefaultConfig();
reloadConfig();
debug = getConfig().getBoolean("debug");
queryInventories = getConfig().getBoolean("query-inventories");
syncWithGroupOnLogout = getConfig().getBoolean("sync-with-group-on-logout");
storeUnknownPlayers = getConfig().getBoolean("store-unknown-players");
queryTimeout = getConfig().getInt("query-timeout");
applyTimedOutQueries = getConfig().getBoolean("apply-timed-out-queries");
enabledSyncTypes = EnumSet.noneOf(SyncType.class);
for (SyncType syncType : SyncType.values()) {
String key = "sync." + syncType.getKey();
if (!getConfig().contains(key, true)
&& getConfig().contains("sync-" + syncType.getKey(), true)) {
key = "sync-" + syncType.getKey();
}
if (getConfig().getBoolean(key)) {
enabledSyncTypes.add(syncType);
}
}
try {
statisticsFilterMode = FilterMode.valueOf(getConfig().getString("statistics-filter.mode", FilterMode.DENY.name()).toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
getLogger().log(Level.WARNING, "Invalid statistics filter mode in config! Using default DENY");
statisticsFilterMode = FilterMode.DENY;
}
Set<Statistic> statisticsFilter = EnumSet.noneOf(Statistic.class);
for (String statisticName : getConfig().getStringList("statistics-filter.list")) {
try {
statisticsFilter.add(Statistic.valueOf(statisticName.toUpperCase(Locale.ROOT)));
} catch (IllegalArgumentException e) {
getLogger().log(Level.WARNING, "Invalid statistic in statistics filter list: " + statisticName);
}
}
this.statisticsFilter = statisticsFilter;
if (getServer().getPluginManager().isPluginEnabled("OpenInv")) {
openInv = (OpenInv) getServer().getPluginManager().getPlugin("OpenInv");
getLogger().log(Level.INFO, "Hooked into " + openInv.getName() + " " + openInv.getDescription().getVersion());
}
if (shouldSync(SyncType.PERSISTENT_DATA)) {
try {
PersistentDataContainer.class.getMethod("readFromBytes", byte[].class, boolean.class);
PersistentDataContainer.class.getMethod("serializeToBytes");
} catch (NoSuchMethodException e) {
if (shouldSync(SyncType.PERSISTENT_DATA)) {
getLogger().log(Level.WARNING, "Could not load static method required for persistent data syncing. Disabling it!", e);
disableSync(SyncType.PERSISTENT_DATA);
}
}
}
if (getServer().getMap((short) 0) == null) {
getServer().createMap(getServer().getWorlds().getFirst());
}
try {
MapView map = null;
for (short i = 0; i < Short.MAX_VALUE && map == null; i++) {
try {
map = getServer().getMap(i);
} catch (IllegalArgumentException ignored) {
}
}
if (map != null) {
fieldWorldMap = map.getClass().getDeclaredField("worldMap");
fieldWorldMap.setAccessible(true);
Object worldMap = fieldWorldMap.get(map);
try {
fieldMapColor = worldMap.getClass().getField("colors");
} catch (NoSuchFieldException e1) {
for (Field field : worldMap.getClass().getFields()) {
if (field.getType() == byte[].class) {
fieldMapColor = field;
}
}
}
fieldMapWorldId = worldMap.getClass().getDeclaredField("uniqueId");
fieldMapWorldId.setAccessible(true);
} else if (shouldSync(SyncType.MAPS)) {
getLogger().log(Level.WARNING, "Could not get a map to load the field required for map syncing. Disabling it!");
disableSync(SyncType.MAPS);
}
} catch (NoSuchFieldException | IllegalAccessException e) {
if (shouldSync(SyncType.MAPS)) {
getLogger().log(Level.WARNING, "Could not load field required for map syncing. Disabling it!", e);
disableSync(SyncType.MAPS);
}
}
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (args.length > 0) {
if ("reload".equalsIgnoreCase(args[0]) && sender.hasPermission("syncing.command.reload")) {
loadConfig();
sender.sendMessage(ChatColor.YELLOW + "Config reloaded!");
return true;
}
}
return false;
}
/**
* Get a language message from the config and replace variables in it
* @param key The key of the message (lang.<key>)
* @param replacements An array of variables to be replaced with certain strings in the format [var,repl,var,repl,...]
* @return The message string with colorcodes and variables replaced
*/
public String getLang(String key, String... replacements) {
String msg = ChatColor.translateAlternateColorCodes('&', getConfig().getString("lang." + key, getName() + ": &cMissing language key &6" + key));
for (int i = 0; i + 1 < replacements.length; i += 2) {
msg = msg.replace("%" + replacements[i] + "%", replacements[i + 1]);
}
return msg;
}
/**
* Check whether or not the inventory etc. of a player is locked
* @param playerId The UUID of the player
* @return true if it is locked; false if not
*/
public boolean isLocked(UUID playerId) {
return getMessenger() == null || getMessenger().hasQuery(playerId);
}
/**
* Get the date when a player last logged out
* @param playerId The UUID of the player
* @param online Whether or not it should return the current time if the player is online
* @return The timestamp of his last known data on the server in milliseconds;
* 0 if the file doesn't exist or an error occurs. (Take a look at {File#lastModified})
*/
public long getLastSeen(UUID playerId, boolean online) {
if (online) {
Player player = getServer().getPlayer(playerId);
if (player != null && player.isOnline()) {
return System.currentTimeMillis();
}
}
// Check if lastseen file exists, if so use it
File lastSeen = getPlayerLastSeenFile(playerId);
if (lastSeen.exists()) {
try {
String lastSeenString = Files.readString(lastSeen.toPath());
logDebug("Lastseen file existed for " + playerId + "! (" + lastSeenString + ")");
return Long.parseLong(lastSeenString);
} catch (IOException e) {
getLogger().log(Level.SEVERE, "Error while reading last seen file for " + playerId + "!", e);
return 0;
}
}
File playerDat = getPlayerDataFile(playerId);
return playerDat.lastModified();
}
/**
* Set the date when a player last logged out (by setting the file modify time)
* @param playerId The UUID of the player
* @param timeStamp The timestamp to set as the last modify time of the file in
* milliseconds.
* @return true if the time was successfully set
*/
public boolean setLastSeen(UUID playerId, long timeStamp) {
File playerDat = getPlayerDataFile(playerId);
if (playerDat.exists()) {
File lastSeen = getPlayerLastSeenFile(playerId);
if (playerDat.setLastModified(timeStamp)) {
if (playerDat.lastModified() == timeStamp) {
// Delete old last seen file if it existed
if (!lastSeen.exists() || lastSeen.delete()) {
return true;
}
logDebug("Unable to remove old last seen file for " + playerId + "?");
}
logDebug("Set last seen of " + playerId + " to " + timeStamp + " but it didn't work? Using workaround...");
} else {
logDebug("Unable to set last seen of " + playerId + " to " + timeStamp + "! Using workaround...");
}
// Workaround for systems that don't allow modifying the dat directly
try {
Files.writeString(lastSeen.toPath(), String.valueOf(timeStamp));
return true;
} catch (IOException e) {
getLogger().log(Level.SEVERE, "Unable to store lastseen file for " + playerId, e);
}
} else {
logDebug("Tried to set last seen of " + playerId + " to " + timeStamp + " but they had no player file stored?");
}
return false;
}
/**
* Whether or not we should query inventories from other servers
*/
public boolean shouldQueryInventories() {
return queryInventories;
}
/**
* Sync data with all servers in a group when a player logs out
*/
public boolean shouldSyncWithGroupOnLogout() {
return syncWithGroupOnLogout;
}
/**
* Whether or not we should apply data of queries that weren't answered by every server
*/
public boolean applyTimedOutQueries() {
return applyTimedOutQueries;
}
/**
* Connect a player to a bungee server
* @param playerId The UUID of the player
* @param server The name of the server
*/
public void connectToServer(UUID playerId, String server) {
Player player = getServer().getPlayer(playerId);
if (player != null && player.isOnline()) {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
out.writeUTF("Connect");
out.writeUTF(server);
player.sendPluginMessage(this, "BungeeCord", out.toByteArray());
}
}
/**
* Apply a PlayerData object to its player
* @param data The data to apply
*/
public void applyData(PlayerData data, Runnable finished) {
if (data == null)
return;
if (data.dataVersion() != getServer().getUnsafe().getDataVersion()) {
getLogger().log(Level.WARNING, "Received data with "
+ (data.dataVersion() < getServer().getUnsafe().getDataVersion() ? "older" : "newer")
+ " Minecraft data version (" + data.dataVersion() + ") than this server (" + getServer().getUnsafe().getDataVersion() + "). Trying to apply anyways but there will most likely be errors! Please try running the same Server version on all synced servers.");
}
runSync(() -> {
Player player = getServer().getPlayer(data.playerId());
boolean createdNewFile = false;
if ((player == null || !player.isOnline()) && getMessenger().hasQuery(data.playerId())) {
long localLastSeen = getLastSeen(data.playerId(), true);
if (localLastSeen < data.lastSeen()) {
cacheData(data, finished);
logDebug("Player " + data.playerId() + " has query but was not fully online yet! Caching data " + data.lastSeen() + "...");
} else {
logDebug("Not caching data for player " + data.playerId() + " as our local player data is not older (" + localLastSeen + ") than the one provided! (" + data.lastSeen() + ")");
}
return;
}
if (getOpenInv() != null) {
if (player == null) {
OfflinePlayer offlinePlayer = getServer().getOfflinePlayer(data.playerId());
if (storeUnknownPlayers && !offlinePlayer.hasPlayedBefore()) {
if (offlinePlayer.getName() == null) {
OfflinePlayer internalOfflinePlayer = getOfflinePlayer.apply(new GameProfile(data.playerId(), data.playerName()));
if (internalOfflinePlayer != null) {
offlinePlayer = internalOfflinePlayer;
}
}
createdNewFile = createNewEmptyData(offlinePlayer.getUniqueId());
}
player = getOpenInv().loadPlayer(offlinePlayer);
if (player == null) {
logDebug("Unable to load player " + offlinePlayer.getName() + "/" + offlinePlayer.getUniqueId() + " data with OpenInv");
}
} else if (!getOpenInv().disableSaving() && getOpenInv().isPlayerLoaded(player.getUniqueId())) {
Player openInvLoadedPlayer = getOpenInv().loadPlayer(player);
if (openInvLoadedPlayer != null && openInvLoadedPlayer != player) {
// The copy loaded by OpenInv is not the same as our loaded copy. Use theirs to stay in sync
player = openInvLoadedPlayer;
}
}
}
if (player == null) {
logDebug("Could not apply data for player " + data.playerId() + " as he isn't online and "
+ (getOpenInv() == null ? "this server doesn't have OpenInv installed!" : "never was online on this server before!"));
if (createdNewFile) {
getPlayerDataFile(data.playerId()).delete();
}
return;
}
try {
if (shouldSync(SyncType.EXPERIENCE)) {
player.setTotalExperience(0);
player.setLevel(0);
player.setExp(0);
}
if (shouldSync(SyncType.INVENTORY))
player.getInventory().clear();
if (shouldSync(SyncType.ENDERCHEST))
player.getEnderChest().clear();
if (player.isOnline() && shouldSync(SyncType.EFFECTS)) {
for (PotionEffect effect : player.getActivePotionEffects()) {
player.removePotionEffect(effect.getType());
}
}
if (shouldSync(SyncType.HEALTH))
player.resetMaxHealth();
if (shouldSync(SyncType.EXPERIENCE)) {
player.setTotalExperience(data.totalExperience());
player.setLevel(data.level());
player.setExp(data.exp());
}
// Try to fix the maps if we should do it
if (shouldSync(SyncType.MAPS)) {
for (MapData mapData : data.maps()) {
logDebug("Found map " + mapData.id() + " in inventory");
checkMap(mapData.id());
try {
logDebug("Writing data of map " + mapData.id());
MapView map = getServer().getMap(mapData.id());
if (map != null) {
Object worldMap = fieldWorldMap.get(map);
map.setCenterX(mapData.centerX());
map.setCenterZ(mapData.centerZ());
map.setScale(mapData.scale());
fieldMapColor.set(worldMap, mapData.colors());
try {
// Newer map info
map.setLocked(mapData.locked());
map.setTrackingPosition(mapData.trackingPosition());
map.setUnlimitedTracking(mapData.unlimitedTracking());
} catch (NoSuchMethodError ignored) {
}
World world = getServer().getWorld(mapData.worldId());
if (world != null) {
map.setWorld(world);
}
fieldMapWorldId.set(worldMap, mapData.worldId()); // plugin API doesn't change UUID on world set so set it always
// Workaround for map not showing directly after creating it
forceRender(map);
player.sendMap(map);
}
} catch (IllegalAccessException e) {
getLogger().log(Level.SEVERE, "Could not access field in WorldMap class for " + mapData.id() + "! ", e);
} catch (Exception e) {
getLogger().log(Level.SEVERE, "Error while trying to store map " + mapData.id() + "! ", e);
}
}
}
logDebug("Applying data for " + player.getName() + " (" + data.lastSeen() + ")");
if (shouldSync(SyncType.INVENTORY))
player.getInventory().setContents(data.getInventoryContents());
if (shouldSync(SyncType.ENDERCHEST))
player.getEnderChest().setContents(data.getEnderchestContents());
if (shouldSync(SyncType.GAMEMODE)) {
if (data.gamemode() != null) {
player.setGameMode(data.gamemode());
} else {
getLogger().log(Level.WARNING, "Data of " + player.getName() + " did not contain gamemode! Setting it to server default " + getServer().getDefaultGameMode());
player.setGameMode(getServer().getDefaultGameMode());
}
}
if (shouldSync(SyncType.HEALTH)) {
player.setMaxHealth(data.maxHealth());
}
if (shouldSync(SyncType.HUNGER))
player.setFoodLevel(data.foodLevel());
if (shouldSync(SyncType.SATURATION))
player.setSaturation(data.saturation());
if (shouldSync(SyncType.EXHAUSTION))
player.setExhaustion(data.exhaustion());
if (shouldSync(SyncType.AIR)) {
player.setMaximumAir(data.maxAir());
player.setRemainingAir(data.remainingAir());
}
if (shouldSync(SyncType.FIRE))
player.setFireTicks(data.fireTicks());
if (shouldSync(SyncType.NO_DAMAGE_TICKS)) {
player.setMaximumNoDamageTicks(data.maxNoDamageTicks());
player.setNoDamageTicks(data.noDamageTicks());
}
if (shouldSync(SyncType.VELOCITY))
player.setVelocity(data.velocity());
if (shouldSync(SyncType.FALL_DISTANCE))
player.setFallDistance(data.fallDistance());
if (shouldSync(SyncType.PERSISTENT_DATA) && data.persistentData() != null) {
try {
PersistentDataContainer pdc = player.getPersistentDataContainer();
pdc.readFromBytes(data.persistentData(), true);
} catch (IOException e) {
getLogger().log(Level.WARNING, "Error while trying to write PersistentDataContainer data. Disabling persistent data syncing!", e);
disableSync(SyncType.PERSISTENT_DATA);
}
}
if (shouldSync(SyncType.ADVANCEMENTS)) {
Boolean oldGamerule = null;
try {
oldGamerule = player.getWorld().getGameRuleValue(GameRule.ANNOUNCE_ADVANCEMENTS);
if ((oldGamerule != null && oldGamerule) || (oldGamerule == null && player.getWorld().getGameRuleDefault(GameRule.ANNOUNCE_ADVANCEMENTS))) {
player.getWorld().setGameRule(GameRule.ANNOUNCE_ADVANCEMENTS, false);
}
} catch (NullPointerException ignored) {
// world is not known
}
for (Iterator<Advancement> it = getServer().advancementIterator(); it.hasNext(); ) {
Advancement advancement = it.next();
Map<String, Long> awarded = data.advancementProgress().get(advancement.getKey().toString());
if (awarded != null) {
AdvancementProgress progress = player.getAdvancementProgress(advancement);
for (String criterion : progress.getAwardedCriteria()) {
if (!awarded.containsKey(criterion)) {
progress.revokeCriteria(criterion);
}
}
for (Map.Entry<String, Long> entry : awarded.entrySet()) {
Date date = progress.getDateAwarded(entry.getKey());
if (date == null && progress.awardCriteria(entry.getKey())) {
date = progress.getDateAwarded(entry.getKey());
}
if (date != null && date.getTime() != entry.getValue()) {
date.setTime(entry.getValue());
}
}
}
}
if (oldGamerule == null || oldGamerule) {
try {
player.getWorld().setGameRule(GameRule.ANNOUNCE_ADVANCEMENTS, true);
} catch (NullPointerException ignored) {
// world is not known
}
}
}
if (shouldSyncAny(SyncType.GENERAL_STATISTICS, SyncType.ENTITY_STATISTICS, SyncType.ITEM_STATISTICS, SyncType.BLOCK_STATISTICS)) {
for (Map.Entry<Statistic, Map<String, Integer>> entry : data.statistics().rowMap().entrySet()) {
Statistic statistic = entry.getKey();
if (!shouldBeSynced(statistic)) {
continue;
}
for (Map.Entry<String, Integer> valueEntry : entry.getValue().entrySet()) {
if (valueEntry.getValue() <= 0) {
continue;
}
switch (statistic.getType()) {
case UNTYPED:
if (shouldSync(SyncType.GENERAL_STATISTICS)) {
player.setStatistic(statistic, valueEntry.getValue());
}
break;
case ENTITY:
if (shouldSync(SyncType.ENTITY_STATISTICS)) {
try {
EntityType entityType = EntityType.valueOf(valueEntry.getKey());
player.setStatistic(statistic, entityType, valueEntry.getValue());
} catch (IllegalArgumentException ignored) {
// unknown entity type
}
}
break;
case BLOCK:
if (shouldSync(SyncType.BLOCK_STATISTICS)) {
Material blockType = Material.getMaterial(valueEntry.getKey());
if (blockType != null) {
player.setStatistic(statistic, blockType, valueEntry.getValue());
}
}
break;
case ITEM:
if (shouldSync(SyncType.ITEM_STATISTICS)) {
Material itemType = Material.getMaterial(valueEntry.getKey());
if (itemType != null) {
player.setStatistic(statistic, itemType, valueEntry.getValue());
}
}
break;
}
}
}
}
if (player.isOnline()) {
if (shouldSync(SyncType.EFFECTS)) {
player.addPotionEffects(data.potionEffects());
}
if (shouldSync(SyncType.HEALTH)) {
player.setHealthScale(data.healthScale());
player.setHealthScaled(data.isHealthScaled());
player.setHealth(Math.min(data.health(), player.getMaxHealth()));
}
if (shouldSync(SyncType.INVENTORY)) {
player.getInventory().setHeldItemSlot(data.heldItemSlot());
player.updateInventory();
}
} else {
if (shouldSync(SyncType.HEALTH)) {
double health = Math.min(data.health(), player.getMaxHealth());
try {
if (methodGetHandle == null) {
methodGetHandle = player.getClass().getMethod("getHandle");
}
Object handle = methodGetHandle.invoke(player);
if (handle != null) {
if (methodSetHealth == null) {
methodSetHealth = handle.getClass().getMethod("setHealth", float.class);
}
methodSetHealth.invoke(handle, (float) health);
}
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
player.setHealth(health > 0 ? health : 1);
}
}
}
finished.run();
if (getOpenInv() != null && !player.isOnline()) {
File playerDat = getPlayerDataFile(data.playerId());
// Store original player file modification date to compare after save to catch error while saving as that's not thrown
long lastModification = playerDat.lastModified();
// Try to save data
player.saveData();
// Check for temporary file
if (new File(playerDataFolder, data.playerId() + "-.dat").exists()) {
throw new RuntimeException("Error while trying to save new player data file after creating temp file!");
}
// If the file was not modified while saving then an error occurred which didn't throw an uncaught exception
if (playerDat.lastModified() == lastModification) {
throw new RuntimeException("Internal error while trying to save new player data file!");
}
}
setLastSeen(data.playerId(), data.lastSeen());
} catch (Exception e) {
getLogger().log(Level.SEVERE, "Error while applying player data of " + player.getName() + "!", e);
File playerDat = getPlayerDataFile(data.playerId());
if (playerDat.exists()) {
if (createdNewFile) {
playerDat.delete();
} else if (playerDat.lastModified() >= data.lastSeen()) {
// Failed to apply data, make sure our locally stored data is older than the newest
setLastSeen(data.playerId(), data.lastSeen() - 1);
}
}
} finally {
if (getOpenInv() != null) {
getOpenInv().unload(player);
}
}
});
}
/**
* Check if a statistic should get synced
* @param statistic The statistic to check
* @return Whether it should be synced
*/
private boolean shouldBeSynced(Statistic statistic) {
if (statisticsFilter.contains(statistic)) {
return statisticsFilterMode == FilterMode.ALLOW;
}
return statisticsFilterMode == FilterMode.DENY;
}
/**
* Force a rerender of the map. This is done by adding an empty custom renderer above the vanilla one.
* @param map The MapView
*/
private void forceRender(MapView map) {
map.addRenderer(new EmptyRenderer());
}
/**
* @return Reference to the OpenInv plugin to load data for the query option
*/
public OpenInv getOpenInv() {
return openInv;
}
/**
* @return The messenger for communications between the servers
*/
public ServerMessenger getMessenger() {
return messenger;
}
/**
* @return The amount of seconds we should wait for a query to stopTimeout
*/
public int getQueryTimeout() {
return queryTimeout;
}
/**
* @return The id of the newest map that was seen on this server
*/
public int getNewestMap() {
return newestMap;
}
private void cacheData(PlayerData data, Runnable finished) {
playerDataCache.put(data.playerId(), new AbstractMap.SimpleEntry<>(data, finished));
}
/**
* Get data that was cached which should be applied on a player's login
* @param player The player to get the data for
* @return A cache entry containing the PlayerData and the notification Runnable when applied successfully
*/
public Map.Entry<PlayerData, Runnable> getCachedData(Player player) {
return playerDataCache.getIfPresent(player.getUniqueId());
}
/**
* Remove the cached data of a player
* @param player The player to remove the data for
*/
public void removeCachedData(Player player) {
playerDataCache.invalidate(player.getUniqueId());
}
private File getPlayerDataFile(UUID playerId) {
return new File(playerDataFolder, playerId + ".dat");
}
private File getPlayerLastSeenFile(UUID playerId) {
return new File(playerDataFolder, playerId + ".lastseen");
}
private boolean createNewEmptyData(UUID playerId) {
File playerDat = getPlayerDataFile(playerId);
if (playerDat.exists()) {
return false;
}
try {
playerDat.getParentFile().mkdirs();
Files.copy(getResource("empty.dat"), playerDat.toPath());
return true;
} catch (IOException e) {
logDebug("Error while trying to create file for unknown player " + playerId + ": " + e.getMessage());
}