Skip to content

Commit

Permalink
Merge pull request #49 from OpenMinetopia/bugfix/incorrect-player-data
Browse files Browse the repository at this point in the history
First and foremost removed bloated getMinetopiaAsync, also fixed bug loading player data incorrectly due to me being stupid™️
  • Loading branch information
duranaaron authored Jan 4, 2025
2 parents 2863e8b + d4c32d5 commit 3814506
Show file tree
Hide file tree
Showing 62 changed files with 272 additions and 328 deletions.
1 change: 0 additions & 1 deletion src/main/java/nl/openminetopia/OpenMinetopia.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import com.jazzkuh.inventorylib.objects.Menu;
import com.jeff_media.customblockdata.CustomBlockData;
import com.sk89q.worldguard.WorldGuard;
import com.sk89q.worldguard.protection.flags.BooleanFlag;
import com.sk89q.worldguard.protection.flags.StateFlag;
import com.sk89q.worldguard.protection.flags.StringFlag;
import com.sk89q.worldguard.protection.flags.registry.FlagConflictException;
Expand Down
96 changes: 14 additions & 82 deletions src/main/java/nl/openminetopia/api/player/PlayerManager.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,100 +36,32 @@ public MinetopiaPlayer getOnlineMinetopiaPlayer(Player player) {

public CompletableFuture<MinetopiaPlayer> getMinetopiaPlayer(OfflinePlayer player) {
CompletableFuture<MinetopiaPlayer> future = new CompletableFuture<>();
getMinetopiaPlayerAsync(player, future::complete, future::completeExceptionally);
return future;
}

/**
* Fetches a MinetopiaPlayer asynchronously. If the player is online, retrieve it from the map.
* Otherwise, query the database.
*
* @param player The OfflinePlayer to retrieve the MinetopiaPlayer for.
* @param callback The action to perform if the MinetopiaPlayer is retrieved successfully.
* @param errorCallback The action to perform if there is an error during retrieval.
*
* @deprecated Use {@link #getMinetopiaPlayer(OfflinePlayer)} instead.
*/
@Deprecated
public void getMinetopiaPlayerAsync(OfflinePlayer player,
Consumer<MinetopiaPlayer> callback,
Consumer<Throwable> errorCallback) {
UUID playerId = player.getUniqueId();

// Check if player is online and already loaded
if (onlinePlayers.containsKey(playerId)) {
callback.accept(onlinePlayers.get(playerId));
return;
if (onlinePlayers.containsKey(player.getUniqueId())) {
future.complete(onlinePlayers.get(player.getUniqueId()));
return future;
}

// Load player if offline or not in the map
loadPlayerModel(player).whenComplete((playerModel, throwable) -> {
this.playerModule.getPlayerModel(player.getUniqueId()).whenComplete((playerModel, throwable) -> {
if (throwable != null) {
errorCallback.accept(throwable);
return;
}
if (playerModel == null) {
callback.accept(null);
future.completeExceptionally(throwable);
return;
}

// Create a new MinetopiaPlayer
MinetopiaPlayer newMinetopiaPlayer = new MinetopiaPlayer(playerId, playerModel);
loadMinetopiaPlayer(newMinetopiaPlayer).whenComplete((loadedMinetopiaPlayer, loadThrowable) -> {
if (loadThrowable != null) {
errorCallback.accept(loadThrowable);
return;
}
MinetopiaPlayer minetopiaPlayer = new MinetopiaPlayer(player.getUniqueId(), playerModel);

minetopiaPlayer.load().thenAccept(unused -> {
if (player.isOnline()) {
onlinePlayers.put(playerId, loadedMinetopiaPlayer);
} else {
loadedMinetopiaPlayer.load();
onlinePlayers.put(player.getUniqueId(), minetopiaPlayer);
}
callback.accept(loadedMinetopiaPlayer);
});
});
}

/**
* Synchronously gets a MinetopiaPlayer if there's an ongoing async operation or if the player is online.
*
* @param player The player to retrieve.
* @return The MinetopiaPlayer object.
*/
public MinetopiaPlayer getMinetopiaPlayerSync(OfflinePlayer player) {
UUID playerId = player.getUniqueId();
if (onlinePlayers.containsKey(playerId)) {
return onlinePlayers.get(playerId);
}

// Perform synchronous retrieval if needed (not recommended if complex)
CompletableFuture<MinetopiaPlayer> future = new CompletableFuture<>();
getMinetopiaPlayerAsync(player, future::complete, future::completeExceptionally);
return future.join();
}

private CompletableFuture<PlayerModel> loadPlayerModel(OfflinePlayer player) {
UUID playerId = player.getUniqueId();
CompletableFuture<PlayerModel> future = new CompletableFuture<>();
this.playerModule.loadPlayer(playerId).whenComplete((playerModel, throwable) -> {
if (throwable != null) {
future.completeExceptionally(throwable);
return;
}
future.complete(playerModel);
future.complete(minetopiaPlayer);
}).exceptionally(throwable2 -> {
future.completeExceptionally(throwable2);
return null;
});
});
return future;
}

private CompletableFuture<MinetopiaPlayer> loadMinetopiaPlayer(MinetopiaPlayer minetopiaPlayer) {
CompletableFuture<MinetopiaPlayer> future = new CompletableFuture<>();
minetopiaPlayer.load().whenComplete((unused, throwable) -> {
if (throwable != null) {
future.completeExceptionally(throwable);
return;
}
future.complete(minetopiaPlayer);
});
return future;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -111,15 +111,17 @@ public void addBooster(int amount, long expiresAtMillis) {
boosterModel.setPlayerId(this.playerModel.getId());
boosterModel.setAmount(amount);
boosterModel.setExpiresAt(expiresAtMillis);
playerModel.getBoosters().add(boosterModel);
this.playerModel.getBoosters().add(boosterModel);
StormDatabase.getInstance().saveStormModel(boosterModel);

System.out.println(playerModel.getUniqueId());

runnable.run();
}

@SneakyThrows
public void removeBooster(FitnessBoosterModel booster) {
playerModel.getBoosters().remove(booster);
this.playerModel.getBoosters().remove(booster);
StormDatabase.getInstance().getStorm().delete(booster);

runnable.run();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,52 +82,44 @@ public MinetopiaPlayer(UUID uuid, PlayerModel playerModel) {
public CompletableFuture<Void> load() {
CompletableFuture<Void> loadFuture = new CompletableFuture<>();

playerModule.getPlayerLoadFuture().whenComplete((unused, throwable) -> {
if (throwable != null) {
OpenMinetopia.getInstance().getLogger().severe("Failed to load player: " + throwable.getMessage());
return;
}

DefaultConfiguration configuration = OpenMinetopia.getDefaultConfiguration();

if (this.getBukkit().getPlayer() != null && this.getBukkit().isOnline())
this.getBukkit().getPlayer().sendMessage(ChatUtils.color("<red>Je data wordt geladen..."));
DefaultConfiguration configuration = OpenMinetopia.getDefaultConfiguration();

this.fitness = new Fitness(this);
if (this.getBukkit().getPlayer() != null && this.getBukkit().isOnline())
this.getBukkit().getPlayer().sendMessage(ChatUtils.color("<red>Je data wordt geladen..."));

this.playtime = this.playerModel.getPlaytime();
this.level = this.playerModel.getLevel();
this.calculatedLevel = configuration.getDefaultLevel();
this.staffchatEnabled = this.playerModel.getStaffchatEnabled();
this.commandSpyEnabled = this.playerModel.getCommandSpyEnabled();
this.chatSpyEnabled = this.playerModel.getChatSpyEnabled();
this.fitness = new Fitness(this);

this.colors = colorModule.getColorsFromPlayer(this.playerModel);
this.activeChatColor = (ChatColor) colorModule.getActiveColorFromPlayer(this.playerModel, OwnableColorType.CHAT)
.orElse(OwnableColorType.CHAT.defaultColor());
this.playtime = this.playerModel.getPlaytime();
this.level = this.playerModel.getLevel();
this.calculatedLevel = configuration.getDefaultLevel();
this.staffchatEnabled = this.playerModel.getStaffchatEnabled();
this.commandSpyEnabled = this.playerModel.getCommandSpyEnabled();
this.chatSpyEnabled = this.playerModel.getChatSpyEnabled();

this.activeNameColor = (NameColor) colorModule.getActiveColorFromPlayer(this.playerModel, OwnableColorType.NAME)
.orElse(OwnableColorType.NAME.defaultColor());
this.colors = colorModule.getColorsFromPlayer(this.playerModel);
this.activeChatColor = (ChatColor) colorModule.getActiveColorFromPlayer(this.playerModel, OwnableColorType.CHAT)
.orElse(OwnableColorType.CHAT.defaultColor());

this.activePrefixColor = (PrefixColor) colorModule.getActiveColorFromPlayer(this.playerModel, OwnableColorType.PREFIX)
.orElse(OwnableColorType.PREFIX.defaultColor());
this.activeNameColor = (NameColor) colorModule.getActiveColorFromPlayer(this.playerModel, OwnableColorType.NAME)
.orElse(OwnableColorType.NAME.defaultColor());

this.activeLevelColor = (LevelColor) colorModule.getActiveColorFromPlayer(this.playerModel, OwnableColorType.LEVEL)
.orElse(OwnableColorType.LEVEL.defaultColor());
this.activePrefixColor = (PrefixColor) colorModule.getActiveColorFromPlayer(this.playerModel, OwnableColorType.PREFIX)
.orElse(OwnableColorType.PREFIX.defaultColor());

this.prefixes = prefixModule.getPrefixesFromPlayer(this.playerModel);
this.activePrefix = prefixModule.getActivePrefixFromPlayer(playerModel)
.orElse(new Prefix(-1, configuration.getDefaultPrefix(), -1));
this.activeLevelColor = (LevelColor) colorModule.getActiveColorFromPlayer(this.playerModel, OwnableColorType.LEVEL)
.orElse(OwnableColorType.LEVEL.defaultColor());

this.playtimeRunnable = new PlaytimeRunnable(this);
playtimeRunnable.runTaskTimerAsynchronously(OpenMinetopia.getInstance(), 0, 20L);
this.prefixes = prefixModule.getPrefixesFromPlayer(this.playerModel);
this.activePrefix = prefixModule.getActivePrefixFromPlayer(playerModel)
.orElse(new Prefix(-1, configuration.getDefaultPrefix(), -1));

this.levelcheckRunnable = new LevelCheckRunnable(this);
levelcheckRunnable.runTaskTimerAsynchronously(OpenMinetopia.getInstance(), 0, 20L * 30);
this.playtimeRunnable = new PlaytimeRunnable(this);
playtimeRunnable.runTaskTimerAsynchronously(OpenMinetopia.getInstance(), 20L, 20L);

loadFuture.complete(null);
});
this.levelcheckRunnable = new LevelCheckRunnable(this);
levelcheckRunnable.runTaskTimerAsynchronously(OpenMinetopia.getInstance(), 20L, 20L * 30);

loadFuture.complete(null);
return loadFuture;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class BankingCreateCommand extends BaseCommand {
public void createAccount(Player player, AccountType type, String name) {
BankingModule bankingModule = OpenMinetopia.getModuleManager().getModule(BankingModule.class);

PlayerManager.getInstance().getMinetopiaPlayerAsync(player, minetopiaPlayer -> {
PlayerManager.getInstance().getMinetopiaPlayer(player).whenComplete((minetopiaPlayer, throwable) -> {
if (type == AccountType.PRIVATE) {
ChatUtils.sendFormattedMessage(minetopiaPlayer, MessageConfiguration.message("banking_unique_private_account"));
return;
Expand Down Expand Up @@ -65,6 +65,6 @@ public void createAccount(Player player, AccountType type, String name) {
bankingModule.getBankAccountModels().add(accountModel);
accountModel.initSavingTask();
}));
}, Throwable::printStackTrace);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public void deleteAccount(CommandSender sender, String accountName) {
BankingModule bankingModule = OpenMinetopia.getModuleManager().getModule(BankingModule.class);
BankAccountModel accountModel = bankingModule.getAccountByName(accountName);

PlayerManager.getInstance().getMinetopiaPlayerAsync((OfflinePlayer) sender, minetopiaPlayer -> {
PlayerManager.getInstance().getMinetopiaPlayer((OfflinePlayer) sender).whenComplete((minetopiaPlayer, throwable1) -> {
if (accountModel == null) {
ChatUtils.sendFormattedMessage(minetopiaPlayer, MessageConfiguration.message("banking_account_not_found"));
return;
Expand All @@ -42,6 +42,6 @@ public void deleteAccount(CommandSender sender, String accountName) {
.replace("<account_name>", accountModel.getName()));
bankingModule.getBankAccountModels().remove(accountModel);
});
}, Throwable::printStackTrace);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public void infoAccount(CommandSender sender, String accountName) {
BankingModule bankingModule = OpenMinetopia.getModuleManager().getModule(BankingModule.class);
BankAccountModel accountModel = bankingModule.getAccountByName(accountName);

PlayerManager.getInstance().getMinetopiaPlayerAsync((OfflinePlayer) sender, minetopiaPlayer -> {
PlayerManager.getInstance().getMinetopiaPlayer((OfflinePlayer) sender).whenComplete((minetopiaPlayer, throwable1 ) -> {
if (accountModel == null) {
ChatUtils.sendFormattedMessage(minetopiaPlayer, MessageConfiguration.message("banking_account_not_found"));
return;
Expand All @@ -35,7 +35,7 @@ public void infoAccount(CommandSender sender, String accountName) {
ChatUtils.sendFormattedMessage(minetopiaPlayer, replacePlaceholders(MessageConfiguration.message("banking_account_info_line3"), accountModel));
ChatUtils.sendFormattedMessage(minetopiaPlayer, replacePlaceholders(MessageConfiguration.message("banking_account_info_line4"), accountModel));

}, Throwable::printStackTrace);
});
}

private String replacePlaceholders(String message, BankAccountModel accountModel) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class BankingUsersCommand extends BaseCommand {
public void addUser(CommandSender sender, OfflinePlayer target, String accountName, AccountPermission permission) {
BankingModule bankingModule = OpenMinetopia.getModuleManager().getModule(BankingModule.class);
BankAccountModel accountModel = bankingModule.getAccountByName(accountName);
PlayerManager.getInstance().getMinetopiaPlayerAsync((Player) sender, minetopiaPlayer -> {
PlayerManager.getInstance().getMinetopiaPlayer((Player) sender).whenComplete((minetopiaPlayer, throwable1) -> {
if (accountModel == null) {
ChatUtils.sendFormattedMessage(minetopiaPlayer, MessageConfiguration.message("banking_account_not_found"));
return;
Expand All @@ -51,7 +51,7 @@ public void addUser(CommandSender sender, OfflinePlayer target, String accountNa
.replace("<account_name>", accountModel.getName())
.replace("<permission>", permission.name()));
}));
}, Throwable::printStackTrace);
});
}

@Subcommand("removeuser")
Expand All @@ -62,7 +62,7 @@ public void removeUser(CommandSender sender, OfflinePlayer target, String accoun
BankingModule bankingModule = OpenMinetopia.getModuleManager().getModule(BankingModule.class);
BankAccountModel accountModel = bankingModule.getAccountByName(accountName);

PlayerManager.getInstance().getMinetopiaPlayerAsync((Player) sender, minetopiaPlayer -> {
PlayerManager.getInstance().getMinetopiaPlayer((Player) sender).whenComplete((minetopiaPlayer, throwable1) -> {
if (accountModel == null) {
ChatUtils.sendFormattedMessage(minetopiaPlayer, MessageConfiguration.message("banking_account_not_found"));
return;
Expand All @@ -79,6 +79,6 @@ public void removeUser(CommandSender sender, OfflinePlayer target, String accoun
.replace("<player>", (target.getName() == null ? "null" : target.getName()))
.replace("<account_name>", accountModel.getName()));
});
}, Throwable::printStackTrace);
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public void onClick(InventoryClickEvent event) {
if (!PersistentDataUtil.contains(item, "bank_note_value")) return;
if (PersistentDataUtil.getDouble(item, "bank_note_value") == null) return;

PlayerManager.getInstance().getMinetopiaPlayerAsync(player, minetopiaPlayer -> {
PlayerManager.getInstance().getMinetopiaPlayer(player).whenComplete((minetopiaPlayer, throwable) -> {
if(!isAsAdmin() && !accountModel.hasPermission(player.getUniqueId(), AccountPermission.DEPOSIT)) {
ChatUtils.sendFormattedMessage(minetopiaPlayer, MessageConfiguration.message("banking_no_deposit_permission"));
return;
Expand All @@ -113,14 +113,14 @@ public void onClick(InventoryClickEvent event) {
ChatUtils.sendFormattedMessage(minetopiaPlayer, MessageConfiguration.message("banking_deposit_message")
.replace("<deposit_value>", bankingModule.format(totalValue)));
new BankContentsMenu(player, accountModel, isAsAdmin()).open(player);
}, Throwable::printStackTrace);
});
}

private void withdrawMoney(BankNote note, int amount) {
double balance = accountModel.getBalance();
double totalValue = note.getValue() * amount;

PlayerManager.getInstance().getMinetopiaPlayerAsync(player, minetopiaPlayer -> {
PlayerManager.getInstance().getMinetopiaPlayer(player).whenComplete((minetopiaPlayer, throwable) -> {
if (balance < totalValue) {
ChatUtils.sendFormattedMessage(minetopiaPlayer, MessageConfiguration.message("banking_not_enough_money"));
return;
Expand All @@ -137,7 +137,7 @@ private void withdrawMoney(BankNote note, int amount) {
ChatUtils.sendFormattedMessage(minetopiaPlayer, MessageConfiguration.message("banking_withdraw_message")
.replace("<withdraw_value>", bankingModule.format(totalValue)));
new BankContentsMenu(player, accountModel, isAsAdmin()).open(player);
}, Throwable::printStackTrace);
});
}

@Getter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class PlayerChatListener implements Listener {
@EventHandler
public void playerChat(AsyncChatEvent event) {
Player source = event.getPlayer();
PlayerManager.getInstance().getMinetopiaPlayerAsync(source, minetopiaPlayer -> {
PlayerManager.getInstance().getMinetopiaPlayer(source).whenComplete((minetopiaPlayer, throwable1) -> {
if (minetopiaPlayer == null) return;

if (!minetopiaPlayer.isInPlace()) return;
Expand Down Expand Up @@ -87,6 +87,6 @@ public void playerChat(AsyncChatEvent event) {
// Send the formatted message to the target
target.sendMessage(ChatUtils.format(minetopiaPlayer, finalMessage));
}
}, Throwable::printStackTrace);
});
}
}
Loading

0 comments on commit 3814506

Please sign in to comment.