From 6e738b8de220ec68d865f05efed5d8363a9039d1 Mon Sep 17 00:00:00 2001 From: Efe Kurban Date: Sat, 13 Jan 2024 22:15:36 +0300 Subject: [PATCH] Make some actions run async using the new RequestUtil --- .../plugin/configuration/Language.java | 2 + .../modules/auth/commands/AuthCommand.java | 10 ++ .../modules/bazaar/gui/BazaarAddItemGui.java | 148 +++++++++--------- .../plugin/modules/bazaar/gui/BazaarGui.java | 131 +++++++++------- .../credit/commands/CreditCommand.java | 98 +++++++----- .../modules/discord/commands/SyncCommand.java | 32 ++-- .../voucher/listeners/VoucherListener.java | 42 ++--- .../webstore/helpers/WebStoreHelper.java | 89 ++++++----- shared/pom.xml | 5 + .../leaderos/shared/helpers/RequestUtil.java | 25 +++ 10 files changed, 344 insertions(+), 238 deletions(-) create mode 100644 shared/src/main/java/net/leaderos/shared/helpers/RequestUtil.java diff --git a/bukkit/src/main/java/net/leaderos/plugin/configuration/Language.java b/bukkit/src/main/java/net/leaderos/plugin/configuration/Language.java index 62750e8f9..2afb83d4b 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/configuration/Language.java +++ b/bukkit/src/main/java/net/leaderos/plugin/configuration/Language.java @@ -52,6 +52,8 @@ public static class Messages extends OkaeriConfig { private String cannotCreateFull = "{prefix} &cPlease create some space in your inventory and try again."; + private String haveRequestOngoing = "&cPlease wait for your current request to be done!"; + /** * Help commands message */ diff --git a/bukkit/src/main/java/net/leaderos/plugin/modules/auth/commands/AuthCommand.java b/bukkit/src/main/java/net/leaderos/plugin/modules/auth/commands/AuthCommand.java index 89b218a3a..cd1095cf9 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/modules/auth/commands/AuthCommand.java +++ b/bukkit/src/main/java/net/leaderos/plugin/modules/auth/commands/AuthCommand.java @@ -8,6 +8,7 @@ import net.leaderos.plugin.Bukkit; import net.leaderos.plugin.helpers.ChatUtil; import net.leaderos.plugin.helpers.MDChat.MDChatAPI; +import net.leaderos.shared.helpers.RequestUtil; import net.leaderos.shared.modules.auth.AuthHelper; import org.bukkit.entity.Player; @@ -27,6 +28,13 @@ public class AuthCommand extends BaseCommand { @Default @Permission("leaderos.auth") public void defaultCommand(Player player) { + if (!RequestUtil.canRequest(player.getUniqueId())) { + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getHaveRequestOngoing()); + return; + } + + RequestUtil.addRequest(player.getUniqueId()); + String link = AuthHelper.getAuthLink(player.getName(), player.getUniqueId()); if (link != null) player.spigot().sendMessage( @@ -37,5 +45,7 @@ public void defaultCommand(Player player) { .replace("{prefix}", Bukkit.getInstance().getLangFile().getMessages().getPrefix())))); else ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getAuth().getNoLink()); + + RequestUtil.invalidate(player.getUniqueId()); } } \ No newline at end of file diff --git a/bukkit/src/main/java/net/leaderos/plugin/modules/bazaar/gui/BazaarAddItemGui.java b/bukkit/src/main/java/net/leaderos/plugin/modules/bazaar/gui/BazaarAddItemGui.java index f30113368..21dbb68e7 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/modules/bazaar/gui/BazaarAddItemGui.java +++ b/bukkit/src/main/java/net/leaderos/plugin/modules/bazaar/gui/BazaarAddItemGui.java @@ -62,86 +62,86 @@ public static void showGui(Player player, int itemAmount) { gui.addElement(new GuiStorageElement('i', inv)); // Close action area (event) gui.setCloseAction(close -> { - // Calculating storage amounts - int maxStorageAmount = GameUtil.getAmountFromPerm(player, - "bazaar.maxstorage.", - Bukkit.getInstance().getModulesFile().getBazaar().getDefaultStorageSize()); + // Calculating storage amounts + int maxStorageAmount = GameUtil.getAmountFromPerm(player, + "bazaar.maxstorage.", + Bukkit.getInstance().getModulesFile().getBazaar().getDefaultStorageSize()); - int canStoreAmount = maxStorageAmount - itemAmount; - // Items which stored (airs included) - List items = Arrays.stream(inv.getContents()).collect(Collectors.toList()); - String userId = User.getUser(player.getName()).getId(); - int serverId = BazaarModule.getServerId(); + int canStoreAmount = maxStorageAmount - itemAmount; + // Items which stored (airs included) + List items = Arrays.stream(inv.getContents()).collect(Collectors.toList()); + String userId = User.getUser(player.getName()).getId(); + int serverId = BazaarModule.getServerId(); - // If player maxed out storage limit items will be added to - // this list then gives back to player. - List returnItems = new ArrayList<>(); + // If player maxed out storage limit items will be added to + // this list then gives back to player. + List returnItems = new ArrayList<>(); - // item loop - for (ItemStack item : items) { - // Checks if item is empty or null (can be AIR etc.) - if (item == null) - continue; - if (item.getType() == null) - continue; - if (item.getType().equals(Material.AIR)) - continue; - // Checks if area is filler item - if (item.equals(fillerItem)) - continue; + // item loop + for (ItemStack item : items) { + // Checks if item is empty or null (can be AIR etc.) + if (item == null) + continue; + if (item.getType() == null) + continue; + if (item.getType().equals(Material.AIR)) + continue; + // Checks if area is filler item + if (item.equals(fillerItem)) + continue; - // Calculates storage amount - if (canStoreAmount > 0) - canStoreAmount--; - // If maxed out then add items to temp array - else { - returnItems.add(item); - continue; - } - // Item info - XMaterial material = XMaterial.matchXMaterial(item); - String name = ItemUtil.getName(item); - String lore = (item.hasItemMeta() && item.getItemMeta().hasLore()) ? - String.join("\n", item.getItemMeta().getLore()) : null; - int amount = item.getAmount(); - int maxDurability = item.getType().getMaxDurability(); - int durability = ItemUtil.getDurability(item, maxDurability); - String base64 = ItemUtil.toBase64(item); - double price = 0.0; - String creationDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); - String modelId = ItemUtil.getModelId(item); - String enchantment = ItemUtil.getEnchantments(item); + // Calculates storage amount + if (canStoreAmount > 0) + canStoreAmount--; + // If maxed out then add items to temp array + else { + returnItems.add(item); + continue; + } + // Item info + XMaterial material = XMaterial.matchXMaterial(item); + String name = ItemUtil.getName(item); + String lore = (item.hasItemMeta() && item.getItemMeta().hasLore()) ? + String.join("\n", item.getItemMeta().getLore()) : null; + int amount = item.getAmount(); + int maxDurability = item.getType().getMaxDurability(); + int durability = ItemUtil.getDurability(item, maxDurability); + String base64 = ItemUtil.toBase64(item); + double price = 0.0; + String creationDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()); + String modelId = ItemUtil.getModelId(item); + String enchantment = ItemUtil.getEnchantments(item); - // Sends response - try { - Response postBazaarItem = new AddBazaarItemRequest(userId, name, lore, amount, maxDurability, durability, base64, price, creationDate, modelId, enchantment, serverId, material.name()).getResponse(); - if (postBazaarItem.getResponseCode() == HttpURLConnection.HTTP_OK - && postBazaarItem.getResponseMessage().getBoolean("status")) { - ChatUtil.sendMessage(player, ChatUtil.replacePlaceholders( - Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getAddItemMessage(), - new Placeholder("%item_name%", name) - )); - } - else throw new Exception(); - } catch (Exception e) { - // TODO error msg - e.printStackTrace(); - // If something occur when adding item it will pop item back to player inventory - returnItems.add(item); - } - } + org.bukkit.Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getInstance(), () -> { + // Sends response + try { + Response postBazaarItem = new AddBazaarItemRequest(userId, name, lore, amount, maxDurability, durability, base64, price, creationDate, modelId, enchantment, serverId, material.name()).getResponse(); + if (postBazaarItem.getResponseCode() == HttpURLConnection.HTTP_OK + && postBazaarItem.getResponseMessage().getBoolean("status")) { + ChatUtil.sendMessage(player, ChatUtil.replacePlaceholders( + Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getAddItemMessage(), + new Placeholder("%item_name%", name) + )); + } else throw new Exception(); + } catch (Exception e) { + // TODO error msg + e.printStackTrace(); + // If something occur when adding item it will pop item back to player inventory + returnItems.add(item); + } + if (!returnItems.isEmpty()) { + PlayerInventory playerInventory = player.getInventory(); - // Gives items back to player - if (!returnItems.isEmpty()) { - PlayerInventory playerInventory = player.getInventory(); - returnItems.forEach(playerInventory::addItem); - String returnMessage = Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getReturnItemMessage(); - returnMessage = returnMessage.replace("%max_amount%", String.valueOf(maxStorageAmount)) - .replace("%amount%", String.valueOf(returnItems.size())); - ChatUtil.sendMessage(player, returnMessage); - } - return false; // Don't go back to the previous GUI (true would automatically go back to the previously opened one) - }); + returnItems.forEach(playerInventory::addItem); + String returnMessage = Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getReturnItemMessage(); + returnMessage = returnMessage.replace("%max_amount%", String.valueOf(maxStorageAmount)) + .replace("%amount%", String.valueOf(returnItems.size())); + ChatUtil.sendMessage(player, returnMessage); + } + }); + } + return false; // Don't go back to the previous GUI (true would automatically go back to the previously opened one) + }); gui.show(player); } } diff --git a/bukkit/src/main/java/net/leaderos/plugin/modules/bazaar/gui/BazaarGui.java b/bukkit/src/main/java/net/leaderos/plugin/modules/bazaar/gui/BazaarGui.java index 4c4321b7c..b3dad923e 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/modules/bazaar/gui/BazaarGui.java +++ b/bukkit/src/main/java/net/leaderos/plugin/modules/bazaar/gui/BazaarGui.java @@ -5,12 +5,12 @@ import de.themoep.inventorygui.InventoryGui; import de.themoep.inventorygui.StaticGuiElement; import lombok.SneakyThrows; +import net.leaderos.plugin.Bukkit; import net.leaderos.plugin.helpers.ChatUtil; +import net.leaderos.plugin.helpers.GuiHelper; import net.leaderos.plugin.modules.bazaar.model.PlayerBazaar; import net.leaderos.plugin.modules.cache.model.User; -import net.leaderos.plugin.Bukkit; -import net.leaderos.shared.exceptions.CacheNotFoundException; -import net.leaderos.plugin.helpers.GuiHelper; +import net.leaderos.shared.helpers.RequestUtil; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -34,65 +34,78 @@ public BazaarGui() {} */ @SneakyThrows public static void showGui(Player player) { - // Gui template as array - String[] layout = Bukkit.getInstance().getModulesFile().getBazaar().getGui().getLayout().toArray(new String[0]); - // Inventory object - String guiName = ChatUtil.replacePlaceholders(Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getGuiName()); - InventoryGui gui = new InventoryGui(Bukkit.getInstance(), null, guiName, layout); - // Filler item for empty slots - gui.setFiller(GuiHelper.getFiller(Bukkit.getInstance().getModulesFile().getBazaar().getGui().getFillerItem().isUseFiller(), Bukkit.getInstance().getModulesFile().getBazaar().getGui().getFillerItem().getMaterial())); - - // List creator - List playerBazaarList; - try { - playerBazaarList = PlayerBazaar.getBazaarStorage(User.getUser(player.getName()).getId()); - } catch (Exception e){ - throw new CacheNotFoundException("cache not found"); + if (!RequestUtil.canRequest(player.getUniqueId())) { + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getHaveRequestOngoing()); + return; } - // Add item icon - gui.addElement(new StaticGuiElement('a', GuiHelper.addItemIcon(), 1, click -> { - gui.close(); - click.getEvent().setCancelled(true); - BazaarAddItemGui.showGui(player, playerBazaarList.size()); - return false; - })); + org.bukkit.Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getInstance(), () -> { + RequestUtil.addRequest(player.getUniqueId()); + + // Gui template as array + String[] layout = Bukkit.getInstance().getModulesFile().getBazaar().getGui().getLayout().toArray(new String[0]); + // Inventory object + String guiName = ChatUtil.replacePlaceholders(Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getGuiName()); + InventoryGui gui = new InventoryGui(Bukkit.getInstance(), null, guiName, layout); + // Filler item for empty slots + gui.setFiller(GuiHelper.getFiller(Bukkit.getInstance().getModulesFile().getBazaar().getGui().getFillerItem().isUseFiller(), Bukkit.getInstance().getModulesFile().getBazaar().getGui().getFillerItem().getMaterial())); + + // List creator + // why throw a cache not found exception here? its not related to cache at all. I will let @SneakyThrows do its job here + List playerBazaarList = PlayerBazaar.getBazaarStorage(User.getUser(player.getName()).getId()); + + // Add item icon + gui.addElement(new StaticGuiElement('a', GuiHelper.addItemIcon(), 1, click -> { + gui.close(); + click.getEvent().setCancelled(true); + BazaarAddItemGui.showGui(player, playerBazaarList.size()); + return false; + })); + + // Bazaar group creator + GuiElementGroup bazaarGui = new GuiElementGroup('i'); + if (!playerBazaarList.isEmpty()) + playerBazaarList.forEach(playerBazaarItem -> { + ItemStack bazaarItem = playerBazaarItem.getItem(); + bazaarGui.addElement(new DynamicGuiElement('s', (viewer) + -> new StaticGuiElement('s', + bazaarItem, + bazaarItem.getAmount(), + click -> { + click.getEvent().setCancelled(true); + gui.close(); + if (player.getInventory().firstEmpty() == -1) { + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCannotCreateFull()); + return false; + } + String title = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getWithdrawTitle()); + String subtitleError = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getWithdrawErrorSubtitle()); + String subtitleSuccess = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getWithdrawSuccessSubtitle()); + String subtitleProgress = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getWithdrawProgressSubtitle()); + player.sendTitle(title, subtitleProgress); + + org.bukkit.Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getInstance(), () -> { + boolean withdrawStatus = playerBazaarItem.withdrawItem(player); + if (withdrawStatus) + player.sendTitle(title, subtitleSuccess); + else + player.sendTitle(title, subtitleError); + }); + + return false; + }))); + } + ); + gui.addElement(bazaarGui); - // Bazaar group creator - GuiElementGroup bazaarGui = new GuiElementGroup('i'); - if (!playerBazaarList.isEmpty()) - playerBazaarList.forEach(playerBazaarItem -> { - ItemStack bazaarItem = playerBazaarItem.getItem(); - bazaarGui.addElement(new DynamicGuiElement('s', (viewer) - -> new StaticGuiElement('s', - bazaarItem, - bazaarItem.getAmount(), - click -> { - click.getEvent().setCancelled(true); - gui.close(); - if (player.getInventory().firstEmpty() == -1) { - ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCannotCreateFull()); - return false; - } - String title = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getWithdrawTitle()); - String subtitleError = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getWithdrawErrorSubtitle()); - String subtitleSuccess = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getWithdrawSuccessSubtitle()); - String subtitleProgress = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getWithdrawProgressSubtitle()); - player.sendTitle(title, subtitleProgress); - boolean withdrawStatus = playerBazaarItem.withdrawItem(player); - if (withdrawStatus) - player.sendTitle(title, subtitleSuccess); - else - player.sendTitle(title, subtitleError); - return false; - }))); - } - ); - gui.addElement(bazaarGui); + // Next and previous page icons + gui.addElement(GuiHelper.createNextPage(Bukkit.getInstance().getModulesFile().getBazaar().getGui().getNextPage().getItem())); + gui.addElement(GuiHelper.createPreviousPage(Bukkit.getInstance().getModulesFile().getBazaar().getGui().getPreviousPage().getItem())); - // Next and previous page icons - gui.addElement(GuiHelper.createNextPage(Bukkit.getInstance().getModulesFile().getBazaar().getGui().getNextPage().getItem())); - gui.addElement(GuiHelper.createPreviousPage(Bukkit.getInstance().getModulesFile().getBazaar().getGui().getPreviousPage().getItem())); - gui.show(player); + org.bukkit.Bukkit.getScheduler().runTask(Bukkit.getInstance(), () -> { + gui.show(player); + RequestUtil.invalidate(player.getUniqueId()); + }); + }); } } diff --git a/bukkit/src/main/java/net/leaderos/plugin/modules/credit/commands/CreditCommand.java b/bukkit/src/main/java/net/leaderos/plugin/modules/credit/commands/CreditCommand.java index 5dd0ae8b8..208c15edd 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/modules/credit/commands/CreditCommand.java +++ b/bukkit/src/main/java/net/leaderos/plugin/modules/credit/commands/CreditCommand.java @@ -12,13 +12,11 @@ import net.leaderos.plugin.helpers.ChatUtil; import net.leaderos.shared.helpers.MoneyUtil; import net.leaderos.shared.helpers.Placeholder; -import net.leaderos.shared.model.Response; -import net.leaderos.shared.modules.credit.CreditHelper; +import net.leaderos.shared.helpers.RequestUtil; import net.leaderos.shared.modules.credit.enums.UpdateType; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.net.HttpURLConnection; import java.util.Objects; /** @@ -36,14 +34,25 @@ public class CreditCommand extends BaseCommand { @Default @Permission("leaderos.credit.see") public void defaultCommand(Player player) { - Double amount = LeaderOSAPI.getCreditManager().get(player.getName()); - if (amount == null) - amount = 0.00; - - ChatUtil.sendMessage(player, ChatUtil.replacePlaceholders( - Bukkit.getInstance().getLangFile().getMessages().getCredit().getCreditInfo(), - new Placeholder("{amount}", MoneyUtil.format(amount) - ))); + if (!RequestUtil.canRequest(player.getUniqueId())) { + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getHaveRequestOngoing()); + return; + } + + RequestUtil.addRequest(player.getUniqueId()); + + org.bukkit.Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getInstance(), () -> { + Double amount = LeaderOSAPI.getCreditManager().get(player.getName()); + if (amount == null) + amount = 0.00; + + ChatUtil.sendMessage(player, ChatUtil.replacePlaceholders( + Bukkit.getInstance().getLangFile().getMessages().getCredit().getCreditInfo(), + new Placeholder("{amount}", MoneyUtil.format(amount)) + )); + + RequestUtil.invalidate(player.getUniqueId()); + }); } /** @@ -54,43 +63,54 @@ public void defaultCommand(Player player) { */ @SubCommand(value = "send", alias = {"gönder", "gonder"}) @Permission("leaderos.credit.send") - public void sendCommand(Player player, String target, Double amount) { - amount = MoneyUtil.parseDouble(amount); - Player targetPlayer = org.bukkit.Bukkit.getPlayerExact(target); - - if (player.getName().equalsIgnoreCase(target)) { - ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditYourself()); + public void sendCommand(Player player, String target, Double a) { + if (!RequestUtil.canRequest(player.getUniqueId())) { + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getHaveRequestOngoing()); return; } - if (amount <= 0) { - ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNegative()); - return; - } + RequestUtil.addRequest(player.getUniqueId()); - boolean sendCredit = LeaderOSAPI.getCreditManager().send(player.getName(), target, amount); + org.bukkit.Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getInstance(), () -> { - if (sendCredit) { - // Calls UpdateCache event for update player's cache - org.bukkit.Bukkit.getPluginManager().callEvent(new UpdateCacheEvent(player.getName(), amount, UpdateType.REMOVE)); - ChatUtil.sendMessage(player, ChatUtil.replacePlaceholders( - Bukkit.getInstance().getLangFile().getMessages().getCredit().getSuccessfullySentCredit(), - new Placeholder("{amount}", MoneyUtil.format(amount)), - new Placeholder("{target}", target) - )); + double amount = MoneyUtil.parseDouble(a); + Player targetPlayer = org.bukkit.Bukkit.getPlayerExact(target); + + if (player.getName().equalsIgnoreCase(target)) { + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditYourself()); + return; + } + + if (amount <= 0) { + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNegative()); + return; + } - if (targetPlayer != null) { + boolean sendCredit = LeaderOSAPI.getCreditManager().send(player.getName(), target, amount); + + if (sendCredit) { // Calls UpdateCache event for update player's cache - org.bukkit.Bukkit.getPluginManager().callEvent(new UpdateCacheEvent(target, amount, UpdateType.ADD)); - ChatUtil.sendMessage(Objects.requireNonNull(targetPlayer), ChatUtil.replacePlaceholders( - Bukkit.getInstance().getLangFile().getMessages().getCredit().getReceivedCredit(), + org.bukkit.Bukkit.getPluginManager().callEvent(new UpdateCacheEvent(player.getName(), amount, UpdateType.REMOVE)); + ChatUtil.sendMessage(player, ChatUtil.replacePlaceholders( + Bukkit.getInstance().getLangFile().getMessages().getCredit().getSuccessfullySentCredit(), new Placeholder("{amount}", MoneyUtil.format(amount)), - new Placeholder("{player}", player.getName()) + new Placeholder("{target}", target) )); - } - } - else - ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNotEnough()); + + if (targetPlayer != null) { + // Calls UpdateCache event for update player's cache + org.bukkit.Bukkit.getPluginManager().callEvent(new UpdateCacheEvent(target, amount, UpdateType.ADD)); + ChatUtil.sendMessage(Objects.requireNonNull(targetPlayer), ChatUtil.replacePlaceholders( + Bukkit.getInstance().getLangFile().getMessages().getCredit().getReceivedCredit(), + new Placeholder("{amount}", MoneyUtil.format(amount)), + new Placeholder("{player}", player.getName()) + )); + } + } else + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNotEnough()); + + RequestUtil.invalidate(player.getUniqueId()); + }); } /** diff --git a/bukkit/src/main/java/net/leaderos/plugin/modules/discord/commands/SyncCommand.java b/bukkit/src/main/java/net/leaderos/plugin/modules/discord/commands/SyncCommand.java index ff78d268a..3ff02f306 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/modules/discord/commands/SyncCommand.java +++ b/bukkit/src/main/java/net/leaderos/plugin/modules/discord/commands/SyncCommand.java @@ -8,6 +8,7 @@ import net.leaderos.plugin.Bukkit; import net.leaderos.plugin.helpers.ChatUtil; import net.leaderos.plugin.helpers.MDChat.MDChatAPI; +import net.leaderos.shared.helpers.RequestUtil; import net.leaderos.shared.modules.discord.DiscordHelper; import org.bukkit.entity.Player; @@ -27,15 +28,26 @@ public class SyncCommand extends BaseCommand { @Default @Permission("leaderos.discord.sync") public void defaultCommand(Player player) { - String link = DiscordHelper.getSyncLink(player.getName()); - if (link != null) - player.spigot().sendMessage( - MDChatAPI.getFormattedMessage(ChatUtil.color(Bukkit.getInstance() - .getLangFile().getMessages() - .getDiscord().getCommandMessage() - .replace("%link%", link) - .replace("{prefix}", Bukkit.getInstance().getLangFile().getMessages().getPrefix())))); - else - ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getDiscord().getNoLink()); + if (!RequestUtil.canRequest(player.getUniqueId())) { + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getHaveRequestOngoing()); + return; + } + + RequestUtil.addRequest(player.getUniqueId()); + + org.bukkit.Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getInstance(), () -> { + String link = DiscordHelper.getSyncLink(player.getName()); + if (link != null) + player.spigot().sendMessage( + MDChatAPI.getFormattedMessage(ChatUtil.color(Bukkit.getInstance() + .getLangFile().getMessages() + .getDiscord().getCommandMessage() + .replace("%link%", link) + .replace("{prefix}", Bukkit.getInstance().getLangFile().getMessages().getPrefix())))); + else + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getDiscord().getNoLink()); + + RequestUtil.invalidate(player.getUniqueId()); + }); } } \ No newline at end of file diff --git a/bukkit/src/main/java/net/leaderos/plugin/modules/voucher/listeners/VoucherListener.java b/bukkit/src/main/java/net/leaderos/plugin/modules/voucher/listeners/VoucherListener.java index b1d55edc5..023867c29 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/modules/voucher/listeners/VoucherListener.java +++ b/bukkit/src/main/java/net/leaderos/plugin/modules/voucher/listeners/VoucherListener.java @@ -74,26 +74,30 @@ public void onRightClick(PlayerInteractEvent event) { return; } - Response depositResponse = CreditHelper.addCreditRequest(player.getName(), amount); - if (Objects.requireNonNull(depositResponse).getResponseCode() == HttpURLConnection.HTTP_OK - && depositResponse.getResponseMessage().getBoolean("status")) { - remove(player, id); - list.add(id); - VoucherModule.getVoucherData().set("used", list); - VoucherModule.getVoucherData().save(); - awaitingVouchers.remove(String.valueOf(id)); + remove(player, id); + list.add(id); + VoucherModule.getVoucherData().set("used", list); + VoucherModule.getVoucherData().save(); - // Calls UpdateCache event for update player's cache - org.bukkit.Bukkit.getPluginManager().callEvent(new UpdateCacheEvent(player.getName(), amount, UpdateType.ADD)); - ChatUtil.sendMessage(player, ChatUtil.replacePlaceholders( - Bukkit.getInstance().getLangFile().getMessages().getVouchers() - .getSuccessfullyUsed(), new Placeholder("{amount}", MoneyUtil.format(amount)) - )); - } - else { - ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getPlayerNotAvailable()); - awaitingVouchers.remove(String.valueOf(id)); - } + org.bukkit.Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getInstance(), () -> { + Response depositResponse = CreditHelper.addCreditRequest(player.getName(), amount); + if (Objects.requireNonNull(depositResponse).getResponseCode() == HttpURLConnection.HTTP_OK + && depositResponse.getResponseMessage().getBoolean("status")) { + + awaitingVouchers.remove(String.valueOf(id)); + + // Calls UpdateCache event for update player's cache + org.bukkit.Bukkit.getScheduler().runTask(Bukkit.getInstance(), () -> org.bukkit.Bukkit.getPluginManager().callEvent(new UpdateCacheEvent(player.getName(), amount, UpdateType.ADD))); + ChatUtil.sendMessage(player, ChatUtil.replacePlaceholders( + Bukkit.getInstance().getLangFile().getMessages().getVouchers() + .getSuccessfullyUsed(), new Placeholder("{amount}", MoneyUtil.format(amount)) + )); + } + else { + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getPlayerNotAvailable()); + awaitingVouchers.remove(String.valueOf(id)); + } + }); } /** diff --git a/bukkit/src/main/java/net/leaderos/plugin/modules/webstore/helpers/WebStoreHelper.java b/bukkit/src/main/java/net/leaderos/plugin/modules/webstore/helpers/WebStoreHelper.java index 5ce8f1113..997302d19 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/modules/webstore/helpers/WebStoreHelper.java +++ b/bukkit/src/main/java/net/leaderos/plugin/modules/webstore/helpers/WebStoreHelper.java @@ -6,6 +6,7 @@ import net.leaderos.plugin.helpers.ChatUtil; import net.leaderos.plugin.helpers.MDChat.MDChatAPI; import net.leaderos.plugin.modules.cache.model.User; +import net.leaderos.shared.helpers.RequestUtil; import net.leaderos.shared.model.Response; import net.leaderos.shared.model.request.impl.store.BuyRequest; import net.leaderos.shared.modules.auth.AuthHelper; @@ -17,45 +18,59 @@ public class WebStoreHelper { public static void buyItem(Player player, String productId) { - if (User.isPlayerAuthed(player)) { - User user = User.getUser(player.getName()); - // Titles - String title = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getWebStoreGui().getBuyWebStoreTitle()); - String subtitleError = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getWebStoreGui().getBuyWebStoreError()); - String subtitleProgress = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getWebStoreGui().getBuyWebStoreProgress()); - String subtitleSuccess = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getWebStoreGui().getBuyWebStoreSuccess()); - String subtitleNotEnoughCredit = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getWebStoreGui().getBuyWebStoreNotEnoughCredit()); - player.sendTitle(title, subtitleProgress); - // Buy progress - try { - Response buyRequest = new BuyRequest(user.getId(), productId).getResponse(); - if (buyRequest.getResponseCode() == HttpURLConnection.HTTP_OK) { - // Calls UpdateCache event for update player's cache - double credits = buyRequest.getResponseMessage().getJSONObject("data").getDouble("credits"); - org.bukkit.Bukkit.getPluginManager().callEvent(new UpdateCacheEvent(player.getName(), credits, UpdateType.SET)); - player.sendTitle(title, subtitleSuccess); - } - else if (buyRequest.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST) - player.sendTitle(title, subtitleNotEnoughCredit); - else throw new IOException(); - } catch (IOException e) { - player.sendTitle(title, subtitleError); + if (RequestUtil.canRequest(player.getUniqueId())) { + + RequestUtil.addRequest(player.getUniqueId()); + + if (User.isPlayerAuthed(player)) { + User user = User.getUser(player.getName()); + // Titles + String title = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getWebStoreGui().getBuyWebStoreTitle()); + String subtitleError = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getWebStoreGui().getBuyWebStoreError()); + String subtitleProgress = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getWebStoreGui().getBuyWebStoreProgress()); + String subtitleSuccess = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getWebStoreGui().getBuyWebStoreSuccess()); + String subtitleNotEnoughCredit = ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getWebStoreGui().getBuyWebStoreNotEnoughCredit()); + player.sendTitle(title, subtitleProgress); + org.bukkit.Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getInstance(), () -> { + // Buy progress + try { + Response buyRequest = new BuyRequest(user.getId(), productId).getResponse(); + if (buyRequest.getResponseCode() == HttpURLConnection.HTTP_OK) { + // Calls UpdateCache event for update player's cache + double credits = buyRequest.getResponseMessage().getJSONObject("data").getDouble("credits"); + org.bukkit.Bukkit.getPluginManager().callEvent(new UpdateCacheEvent(player.getName(), credits, UpdateType.SET)); + player.sendTitle(title, subtitleSuccess); + } + else if (buyRequest.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST) + player.sendTitle(title, subtitleNotEnoughCredit); + else throw new IOException(); + } catch (IOException e) { + player.sendTitle(title, subtitleError); + } + RequestUtil.invalidate(player.getUniqueId()); + }); } - } - else { - // If auth login is enabled - if (ModuleManager.getModuleStatus("Auth")) { - String authLink = AuthHelper.getAuthLink(player.getName(), player.getUniqueId()); - if (authLink != null) - player.spigot().sendMessage( - MDChatAPI.getFormattedMessage( - ChatUtil.color(Bukkit.getInstance().getLangFile().getMessages().getAuth().getModuleError() - .replace("%link%", authLink) - .replace("{prefix}", Bukkit.getInstance().getLangFile().getMessages().getPrefix())))); + else { + org.bukkit.Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getInstance(), () -> { + // If auth login is enabled + if (ModuleManager.getModuleStatus("Auth")) { + String authLink = AuthHelper.getAuthLink(player.getName(), player.getUniqueId()); + if (authLink != null) + player.spigot().sendMessage( + MDChatAPI.getFormattedMessage( + ChatUtil.color(Bukkit.getInstance().getLangFile().getMessages().getAuth().getModuleError() + .replace("%link%", authLink) + .replace("{prefix}", Bukkit.getInstance().getLangFile().getMessages().getPrefix())))); + } + // If cache not found and Auth is disabled situation + else + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getGui().getWebStoreGui().getBuyWebStoreNoAuthLinkError()); + + RequestUtil.invalidate(player.getUniqueId()); + }); } - // If cache not found and Auth is disabled situation - else - ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getGui().getWebStoreGui().getBuyWebStoreNoAuthLinkError()); + } else { + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getHaveRequestOngoing()); } } } diff --git a/shared/pom.xml b/shared/pom.xml index 25f944d8c..045ab9cd3 100644 --- a/shared/pom.xml +++ b/shared/pom.xml @@ -35,6 +35,11 @@ gson 2.10.1 + + com.google.guava + guava + 33.0.0-jre + com.github.simplix-softworks simplixstorage diff --git a/shared/src/main/java/net/leaderos/shared/helpers/RequestUtil.java b/shared/src/main/java/net/leaderos/shared/helpers/RequestUtil.java new file mode 100644 index 000000000..b9ab8a6ad --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/helpers/RequestUtil.java @@ -0,0 +1,25 @@ +package net.leaderos.shared.helpers; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; + +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +public class RequestUtil { + + private static final Cache CACHE = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).build(); + + public static void addRequest(UUID uuid) { + CACHE.put(uuid, (byte) 1); + } + + public static boolean canRequest(UUID uuid) { + return CACHE.getIfPresent(uuid) == null; + } + + public static void invalidate(UUID uuid) { + CACHE.invalidate(uuid); + } + +}