diff --git a/bukkit/src/main/java/net/leaderos/plugin/api/modules/credit/CreditManager.java b/bukkit/src/main/java/net/leaderos/plugin/api/modules/credit/CreditManager.java index 707ab6795..ffd0e8563 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/api/modules/credit/CreditManager.java +++ b/bukkit/src/main/java/net/leaderos/plugin/api/modules/credit/CreditManager.java @@ -1,5 +1,6 @@ package net.leaderos.plugin.api.modules.credit; +import net.leaderos.shared.error.Error; import net.leaderos.shared.model.Response; import net.leaderos.shared.modules.credit.CreditHelper; @@ -26,7 +27,7 @@ public CreditManager() {} */ public Double get(String player) { Response amount = CreditHelper.getRequest(player); - if (amount == null) return null; + if (amount == null || amount.getResponseMessage() == null) return null; return amount.getResponseMessage().getDouble("raw_credits"); } @@ -70,10 +71,14 @@ public boolean remove(String target, Double amount) { * @param target receiver of credit * @param amount to send */ - public boolean send(String sender, String target, Double amount) { + public Error send(String sender, String target, Double amount) { Response sendCreditResponse = CreditHelper.sendCreditRequest(sender, target, amount); - return (Objects.requireNonNull(sendCreditResponse).getResponseCode() == HttpURLConnection.HTTP_OK && sendCreditResponse.getResponseMessage().getBoolean("status")); + if ((Objects.requireNonNull(sendCreditResponse).getResponseCode() == HttpURLConnection.HTTP_OK && sendCreditResponse.getResponseMessage().getBoolean("status"))) { + return null; + } + + return sendCreditResponse.getError(); } } 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..87e16ddf1 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 */ @@ -259,6 +261,8 @@ public static class Credit extends OkaeriConfig { private String creditInfoOther = "{prefix} &b{target} &ahas &e{amount} &acredit(s)"; + private String cannotSendCreditsThisUser = "{prefix} &cCould not send credits to this user."; + private String cannotSendCreditYourself = "{prefix} &cYou can not send credit(s) to yourself."; private String cannotSendCreditNegative = "{prefix} &cPlease enter a valid amount. The amount must be higher than 0."; @@ -423,6 +427,12 @@ public static class WebStoreGui extends OkaeriConfig { */ private String buyWebStoreNotEnoughCredit = "&cNot enough credits."; + private String buyWebStoreOutOfStock = "&cOut of stock."; + + private String buyWebStoreProductNotFound = "&cProduct not found."; + + private String buyWebStoreUserNotFound = "&cUser not found."; + /** * withdraw item subtitle error */ diff --git a/bukkit/src/main/java/net/leaderos/plugin/configuration/lang/en.java b/bukkit/src/main/java/net/leaderos/plugin/configuration/lang/en.java index efbc92871..d8ec9de47 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/configuration/lang/en.java +++ b/bukkit/src/main/java/net/leaderos/plugin/configuration/lang/en.java @@ -1,6 +1,5 @@ package net.leaderos.plugin.configuration.lang; -import eu.okaeri.configs.OkaeriConfig; import eu.okaeri.configs.annotation.Comment; import eu.okaeri.configs.annotation.NameModifier; import eu.okaeri.configs.annotation.NameStrategy; @@ -260,6 +259,8 @@ public static class Credit extends Language.Messages.Credit { private String creditInfoOther = "{prefix} &b{target} &ahas &e{amount} &acredit(s)"; + private String cannotSendCreditsThisUser = "{prefix} &cCould not send credits to this user."; + private String cannotSendCreditYourself = "{prefix} &cYou can not send credit(s) to yourself."; private String cannotSendCreditNegative = "{prefix} &cPlease enter a valid amount. The amount must be higher than 0."; diff --git a/bukkit/src/main/java/net/leaderos/plugin/configuration/lang/tr.java b/bukkit/src/main/java/net/leaderos/plugin/configuration/lang/tr.java index 35d357fab..26ef7db3a 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/configuration/lang/tr.java +++ b/bukkit/src/main/java/net/leaderos/plugin/configuration/lang/tr.java @@ -1,6 +1,5 @@ package net.leaderos.plugin.configuration.lang; -import eu.okaeri.configs.OkaeriConfig; import eu.okaeri.configs.annotation.Comment; import eu.okaeri.configs.annotation.NameModifier; import eu.okaeri.configs.annotation.NameStrategy; @@ -260,6 +259,8 @@ public static class Credit extends Language.Messages.Credit { private String creditInfoOther = "{prefix} &b{target} &aadlı oyuncunun &e{amount} &akredisi bulunuyor."; + private String cannotSendCreditsThisUser = "{prefix} &cBu kullanıcıya kredi gönderemezsin."; + private String cannotSendCreditYourself = "{prefix} &cKendine kredi gönderemezsin."; private String cannotSendCreditNegative = "{prefix} &cLütfen geçerli bir miktar giriniz."; 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 e6a2969c6..57ad17acc 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 @@ -1,18 +1,20 @@ package net.leaderos.plugin.modules.bazaar.gui; import com.cryptomorin.xseries.XMaterial; -import de.themoep.inventorygui.*; +import de.themoep.inventorygui.GuiStorageElement; +import de.themoep.inventorygui.InventoryGui; import lombok.SneakyThrows; import net.leaderos.plugin.Bukkit; import net.leaderos.plugin.helpers.ChatUtil; import net.leaderos.plugin.helpers.GameUtil; import net.leaderos.plugin.helpers.GuiHelper; -import net.leaderos.plugin.modules.cache.model.User; -import net.leaderos.plugin.modules.bazaar.BazaarModule; import net.leaderos.plugin.helpers.ItemUtil; +import net.leaderos.plugin.modules.bazaar.BazaarModule; +import net.leaderos.plugin.modules.cache.model.User; +import net.leaderos.shared.error.Error; import net.leaderos.shared.helpers.Placeholder; import net.leaderos.shared.model.Response; -import net.leaderos.shared.model.request.PostRequest; +import net.leaderos.shared.model.request.impl.bazaar.AddBazaarItemRequest; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; @@ -22,7 +24,10 @@ import java.net.HttpURLConnection; import java.text.SimpleDateFormat; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.List; import java.util.stream.Collectors; /** @@ -58,105 +63,88 @@ 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()); - - 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(); + // Calculating storage amounts + int maxStorageAmount = GameUtil.getAmountFromPerm(player, + "bazaar.maxstorage.", + Bukkit.getInstance().getModulesFile().getBazaar().getDefaultStorageSize()); - // If player maxed out storage limit items will be added to - // this list then gives back to player. - List returnItems = new ArrayList<>(); + 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(); - // 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; + // If player maxed out storage limit items will be added to + // this list then gives back to player. + List returnItems = new ArrayList<>(); - // 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); + // 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; - Map body = new HashMap<>(); - body.put("owner", userId); - body.put("name", name); - if (lore != null) - body.put("lore", lore); - body.put("amount", String.valueOf(amount)); - body.put("maxDurability", String.valueOf(maxDurability)); - body.put("durability", String.valueOf(durability)); + // 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); - body.put("base64", base64); - body.put("price", String.valueOf(price)); - body.put("creationDate", creationDate); - if (modelId != null) - body.put("modelID", modelId); - if (enchantment != null) - body.put("enchantment", enchantment); - body.put("serverID", String.valueOf(serverId)); - body.put("itemID", material.name()); + 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 if (postBazaarItem.getError() == Error.INSERT_ERROR) { + returnItems.add(item); + } 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(); - // Sends response - try { - Response postBazaarItem = new PostRequest("bazaar/storages/" + userId + "/items", body).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) - )); + 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); + } + }); } - 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); - } - } - - // 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) - }); + 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..9fab26548 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,13 @@ 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.error.Error; +import net.leaderos.shared.helpers.RequestUtil; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -34,65 +35,79 @@ 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; - })); + RequestUtil.addRequest(player.getUniqueId()); + + org.bukkit.Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getInstance(), () -> { + // 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(), () -> { + Error error = playerBazaarItem.withdrawItem(player); + if (error == null) + player.sendTitle(title, subtitleSuccess); + else if (error == Error.DELETE_ERROR) + player.sendTitle(title, subtitleError); + + RequestUtil.invalidate(player.getUniqueId()); + }); + + 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); + }); + }); } } diff --git a/bukkit/src/main/java/net/leaderos/plugin/modules/bazaar/model/PlayerBazaar.java b/bukkit/src/main/java/net/leaderos/plugin/modules/bazaar/model/PlayerBazaar.java index c9bfb19d0..956286113 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/modules/bazaar/model/PlayerBazaar.java +++ b/bukkit/src/main/java/net/leaderos/plugin/modules/bazaar/model/PlayerBazaar.java @@ -5,11 +5,13 @@ import lombok.SneakyThrows; import net.leaderos.plugin.Bukkit; import net.leaderos.plugin.helpers.ChatUtil; -import net.leaderos.plugin.modules.bazaar.BazaarModule; import net.leaderos.plugin.helpers.ItemUtil; +import net.leaderos.plugin.modules.bazaar.BazaarModule; +import net.leaderos.shared.error.Error; import net.leaderos.shared.model.Response; -import net.leaderos.shared.model.request.DeleteRequest; import net.leaderos.shared.model.request.GetRequest; +import net.leaderos.shared.model.request.impl.bazaar.GetBazaarItemsRequest; +import net.leaderos.shared.model.request.impl.bazaar.RemoveBazaarItemRequest; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; @@ -76,17 +78,16 @@ public ItemStack getItem() { * @return status of withdraw */ @SneakyThrows - public boolean withdrawItem(Player player) { - Response deleteRequest = new DeleteRequest("bazaar/storages/" + getUserId() + "/items/" + getId()).getResponse(); + public Error withdrawItem(Player player) { + Response deleteRequest = new RemoveBazaarItemRequest(getUserId(), getUserId()).getResponse(); if (deleteRequest.getResponseCode() == HttpURLConnection.HTTP_OK && deleteRequest.getResponseMessage().getBoolean("status")) { ItemStack item = ItemUtil.fromBase64(getBase64()); player.getInventory().addItem(item); - return true; + return null; } - else - // TODO Throw exception - return false; + + return deleteRequest.getError(); } /** @@ -97,7 +98,7 @@ public boolean withdrawItem(Player player) { public static List getBazaarStorage(String userId) { try { int serverId = BazaarModule.getServerId(); - GetRequest getRequest = new GetRequest("bazaar/storages/" + userId + "/items?serverID=" + serverId); + GetRequest getRequest = new GetBazaarItemsRequest(userId, String.valueOf(serverId)); JSONObject response = getRequest.getResponse().getResponseMessage(); List playerBazaarList = new ArrayList<>(); response.getJSONArray("array").forEach(bazaar -> playerBazaarList.add(new PlayerBazaar((JSONObject) bazaar, userId))); diff --git a/bukkit/src/main/java/net/leaderos/plugin/modules/cache/model/User.java b/bukkit/src/main/java/net/leaderos/plugin/modules/cache/model/User.java index 8b3231298..83aaad425 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/modules/cache/model/User.java +++ b/bukkit/src/main/java/net/leaderos/plugin/modules/cache/model/User.java @@ -5,6 +5,7 @@ import lombok.SneakyThrows; import net.leaderos.plugin.Bukkit; import net.leaderos.shared.model.request.GetRequest; +import net.leaderos.shared.model.request.impl.user.GetUserRequest; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -90,7 +91,7 @@ public User(@NotNull JSONObject user) { this.creationDate = format.parse(user.getString("creationDate")); // Adds data to cache - userList.remove(username); + userList.remove(username); // why remove? instead, can't we just add the new object? afaik, it replaces the old value userList.put(username, this); } @@ -151,7 +152,7 @@ public static void loadAllPlayers() { */ public static void loadPlayerCache(Player player) { try { - GetRequest getRequest = new GetRequest("users/" + player.getName()); + GetRequest getRequest = new GetUserRequest(player.getName()); new User(getRequest.getResponse().getResponseMessage()); } catch (Exception ignored) {} 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..d99e9b770 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 @@ -10,15 +10,14 @@ import net.leaderos.plugin.api.LeaderOSAPI; import net.leaderos.plugin.api.handlers.UpdateCacheEvent; import net.leaderos.plugin.helpers.ChatUtil; +import net.leaderos.shared.error.Error; 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,61 +35,99 @@ 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()); + }); } /** * Send credit command * @param player executor * @param target player - * @param amount of credit + * @param a amount of credit */ @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(), () -> { + double amount = MoneyUtil.parseDouble(a); + Player targetPlayer = org.bukkit.Bukkit.getPlayerExact(target); - 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) - )); + if (player.getName().equalsIgnoreCase(target)) { + RequestUtil.invalidate(player.getUniqueId()); + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditYourself()); + return; + } - if (targetPlayer != null) { + if (amount <= 0) { + RequestUtil.invalidate(player.getUniqueId()); + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNegative()); + return; + } + + Error error = LeaderOSAPI.getCreditManager().send(player.getName(), target, amount); + + if (error == 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(), + org.bukkit.Bukkit.getScheduler().runTask(Bukkit.getInstance(), () -> 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) + )); + + 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 if (error == Error.NOT_ENOUGH_CREDITS || error == Error.USER_NOT_FOUND) { + ChatUtil.sendMessage(player, ChatUtil.replacePlaceholders( + Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNotEnough(), + new Placeholder("{amount}", MoneyUtil.format(amount)) + )); + } else if (error == Error.INVALID_TARGET + || error == Error.TARGET_USER_NOT_FOUND) { + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditsThisUser()); + } else if (error == Error.INVALID_AMOUNT) { + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNegative()); + } else { + ChatUtil.sendMessage(player, ChatUtil.replacePlaceholders( + Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNotEnough(), + new Placeholder("{amount}", MoneyUtil.format(amount)) )); } - } - 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/donations/managers/DonationManager.java b/bukkit/src/main/java/net/leaderos/plugin/modules/donations/managers/DonationManager.java index b29dac8ae..f592af289 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/modules/donations/managers/DonationManager.java +++ b/bukkit/src/main/java/net/leaderos/plugin/modules/donations/managers/DonationManager.java @@ -3,10 +3,10 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; -import net.leaderos.plugin.modules.donations.model.DonationType; import net.leaderos.plugin.modules.donations.model.Donation; +import net.leaderos.plugin.modules.donations.model.DonationType; import net.leaderos.shared.model.Response; -import net.leaderos.shared.model.request.GetRequest; +import net.leaderos.shared.model.request.impl.donations.GetDonationsRequest; import org.json.JSONArray; import org.json.JSONObject; @@ -105,7 +105,7 @@ private void loadDonationsData() { this.donations = new ArrayList<>(); List donations = new ArrayList<>(); try { - Response recentDonationResponse = new GetRequest("store/donations/?type=" + getType().getRequest() + "&limit=10").getResponse(); + Response recentDonationResponse = new GetDonationsRequest(getType().getRequest()).getResponse(); if (recentDonationResponse.getResponseCode() == HttpURLConnection.HTTP_OK) { JSONArray data = recentDonationResponse.getResponseMessage().getJSONArray("array"); for (int i = 0; i < data.length(); i++) { diff --git a/bukkit/src/main/java/net/leaderos/plugin/modules/donations/model/DonationType.java b/bukkit/src/main/java/net/leaderos/plugin/modules/donations/model/DonationType.java index 5cc1af1f9..02584a8ba 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/modules/donations/model/DonationType.java +++ b/bukkit/src/main/java/net/leaderos/plugin/modules/donations/model/DonationType.java @@ -1,73 +1,24 @@ package net.leaderos.plugin.modules.donations.model; +import lombok.AllArgsConstructor; +import lombok.Getter; + /** - * @author poyrazinan + * @author poyrazinan, efekurbann * @since 1.0 */ +@AllArgsConstructor +@Getter public enum DonationType { - LATEST, - TOP_ALLTIME, - TOP_ANNUAL, - TOP_MONTHLY, - TOP_DAILY; - /** - * Gets request type string - * @return String of request - */ - public String getRequest() { - switch (this) { - case LATEST: - return "latest"; - case TOP_ALLTIME: - return "top-alltime"; - case TOP_ANNUAL: - return "top-annual"; - case TOP_MONTHLY: - return "top-monthly"; - case TOP_DAILY: - return "top-daily"; - } - return null; - } + LATEST("latest", 'l', '1'), + TOP_ALLTIME("top-alltime", 'a', '2'), + TOP_ANNUAL("top-annual", 'y', '3'), + TOP_MONTHLY("top-monthly", 'm', '4'), + TOP_DAILY("top-daily", 'd', '5'); - /** - * Gets gui char - * @return char of gui - */ - public char getGuiChar() { - switch (this) { - case LATEST: - return 'l'; - case TOP_ALLTIME: - return 'a'; - case TOP_ANNUAL: - return 'y'; - case TOP_MONTHLY: - return 'm'; - case TOP_DAILY: - return 'd'; - } - return 'l'; - } + private final String request; + private final char guiChar; + private final char guiInfoChar; - /** - * Gets gui info char - * @return char of gui info - */ - public char getGuiInfoChar() { - switch (this) { - case LATEST: - return '1'; - case TOP_ALLTIME: - return '2'; - case TOP_ANNUAL: - return '3'; - case TOP_MONTHLY: - return '4'; - case TOP_DAILY: - return '5'; - } - return '1'; - } } 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..0dfddaa25 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 @@ -6,8 +6,10 @@ import net.leaderos.plugin.api.handlers.UpdateCacheEvent; import net.leaderos.plugin.helpers.ChatUtil; import net.leaderos.plugin.modules.voucher.VoucherModule; +import net.leaderos.shared.error.Error; import net.leaderos.shared.helpers.MoneyUtil; import net.leaderos.shared.helpers.Placeholder; +import net.leaderos.shared.helpers.RequestUtil; import net.leaderos.shared.model.Response; import net.leaderos.shared.modules.credit.CreditHelper; import net.leaderos.shared.modules.credit.enums.UpdateType; @@ -74,26 +76,39 @@ 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)); - - // 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)); + if (!RequestUtil.canRequest(player.getUniqueId())) { + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getHaveRequestOngoing()); + return; } + + RequestUtil.addRequest(player.getUniqueId()); + list.add(id); + VoucherModule.getVoucherData().set("used", list); + VoucherModule.getVoucherData().save(); + + 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")) { + + // 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)); + awaitingVouchers.remove(String.valueOf(id)); + remove(player, id); + }); + + ChatUtil.sendMessage(player, ChatUtil.replacePlaceholders( + Bukkit.getInstance().getLangFile().getMessages().getVouchers() + .getSuccessfullyUsed(), new Placeholder("{amount}", MoneyUtil.format(amount)) + )); + } else if (depositResponse.getError() == Error.USER_NOT_FOUND) { + ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getPlayerNotAvailable()); + awaitingVouchers.remove(String.valueOf(id)); + } + + RequestUtil.invalidate(player.getUniqueId()); + }); } /** 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 0f1b1805e..44ca2080d 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,63 +6,78 @@ import net.leaderos.plugin.helpers.ChatUtil; import net.leaderos.plugin.helpers.MDChat.MDChatAPI; import net.leaderos.plugin.modules.cache.model.User; -import net.leaderos.plugin.modules.webstore.model.Product; +import net.leaderos.shared.error.Error; +import net.leaderos.shared.helpers.RequestUtil; import net.leaderos.shared.model.Response; -import net.leaderos.shared.model.request.PostRequest; +import net.leaderos.shared.model.request.impl.store.BuyRequest; import net.leaderos.shared.modules.auth.AuthHelper; import net.leaderos.shared.modules.credit.enums.UpdateType; import org.bukkit.entity.Player; import java.io.IOException; import java.net.HttpURLConnection; -import java.util.HashMap; -import java.util.Map; public class WebStoreHelper { public static void buyItem(Player player, String productId) { - if (User.isPlayerAuthed(player)) { - User user = User.getUser(player.getName()); - Map body = new HashMap<>(); - body.put("user", user.getId()); - body.put("products[0][id]", productId); - body.put("products[0][quantity]", "1"); - // 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 PostRequest("store/buy", body).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.getError() == Error.INVALID_QUANTITY + || buyRequest.getError() == Error.INSUFFICIENT_BALANCE) + player.sendTitle(title, subtitleNotEnoughCredit); + else if (buyRequest.getError() == Error.OUT_OF_STOCK) + player.sendTitle(title, ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getWebStoreGui().getBuyWebStoreOutOfStock())); + else if (buyRequest.getError() == Error.USER_NOT_FOUND) + player.sendTitle(title, ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getWebStoreGui().getBuyWebStoreUserNotFound())); + else if (buyRequest.getError() == Error.PRODUCT_NOT_FOUND) + player.sendTitle(title, ChatUtil.color(Bukkit.getInstance().getLangFile().getGui().getWebStoreGui().getBuyWebStoreProductNotFound())); + } 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/bukkit/src/main/java/net/leaderos/plugin/modules/webstore/model/Category.java b/bukkit/src/main/java/net/leaderos/plugin/modules/webstore/model/Category.java index 94c83ffba..71f9d0fc1 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/modules/webstore/model/Category.java +++ b/bukkit/src/main/java/net/leaderos/plugin/modules/webstore/model/Category.java @@ -8,6 +8,7 @@ import net.leaderos.plugin.helpers.ItemUtil; import net.leaderos.shared.exceptions.RequestException; import net.leaderos.shared.model.request.GetRequest; +import net.leaderos.shared.model.request.impl.store.ListingRequest; import org.bukkit.inventory.ItemStack; import org.jetbrains.annotations.NotNull; import org.json.JSONArray; @@ -144,7 +145,7 @@ public static void loadAllCategories() throws IOException, RequestException { if (!categories.isEmpty()) categories.clear(); - GetRequest getRequest = new GetRequest("store/listing"); + GetRequest getRequest = new ListingRequest(); JSONObject response = getRequest.getResponse().getResponseMessage(); response.getJSONArray("categories").forEach(jsonObj -> new Category((JSONObject) jsonObj)); } diff --git a/bungee/src/main/java/net/leaderos/bungee/configuration/Language.java b/bungee/src/main/java/net/leaderos/bungee/configuration/Language.java index e64e368d2..676afec75 100644 --- a/bungee/src/main/java/net/leaderos/bungee/configuration/Language.java +++ b/bungee/src/main/java/net/leaderos/bungee/configuration/Language.java @@ -207,6 +207,8 @@ public static class Credit extends OkaeriConfig { private String creditInfoOther = "{prefix} &b{target} &ahas &e{amount} &acredit(s)"; + private String cannotSendCreditsThisUser = "{prefix} &cCould not send credits to this user."; + private String cannotSendCreditYourself = "{prefix} &cYou can not send credit(s) to yourself."; private String cannotSendCreditNegative = "{prefix} &cPlease enter a valid amount. The amount must be higher than 0."; diff --git a/bungee/src/main/java/net/leaderos/bungee/modules/credit/commands/CreditCommand.java b/bungee/src/main/java/net/leaderos/bungee/modules/credit/commands/CreditCommand.java index 841aa36c3..b723db625 100644 --- a/bungee/src/main/java/net/leaderos/bungee/modules/credit/commands/CreditCommand.java +++ b/bungee/src/main/java/net/leaderos/bungee/modules/credit/commands/CreditCommand.java @@ -2,6 +2,7 @@ import net.leaderos.bungee.Bungee; import net.leaderos.bungee.helpers.ChatUtil; +import net.leaderos.shared.error.Error; import net.leaderos.shared.helpers.MoneyUtil; import net.leaderos.shared.helpers.Placeholder; import net.leaderos.shared.model.Response; @@ -183,9 +184,17 @@ public void sendCommand(CommandSender player, String target, Double amount) { new Placeholder("{amount}", MoneyUtil.format(amount)), new Placeholder("{player}", player.getName()) )); + } else { + if (sendCreditResponse.getError() == Error.NOT_ENOUGH_CREDITS) { + ChatUtil.sendMessage(player, Bungee.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNotEnough()); + } else if (sendCreditResponse.getError() == Error.INVALID_TARGET + || sendCreditResponse.getError() == Error.TARGET_USER_NOT_FOUND + || sendCreditResponse.getError() == Error.USER_NOT_FOUND) { + ChatUtil.sendMessage(player, Bungee.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditsThisUser()); + } else if (sendCreditResponse.getError() == Error.INVALID_AMOUNT) { + ChatUtil.sendMessage(player, Bungee.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNegative()); + } } - else - ChatUtil.sendMessage(player, Bungee.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNotEnough()); } 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/error/Error.java b/shared/src/main/java/net/leaderos/shared/error/Error.java new file mode 100644 index 000000000..8d8379560 --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/error/Error.java @@ -0,0 +1,32 @@ +package net.leaderos.shared.error; + +public enum Error { + + // general + USER_NOT_FOUND, + + // store + INVALID_QUANTITY, + INSUFFICIENT_BALANCE, + OUT_OF_STOCK, + PRODUCT_NOT_FOUND, + + // donations + INVALID_LIMIT, + INVALID_TYPE, + + // bazaar + INSERT_ERROR, + DELETE_ERROR, + + // ticket + TICKET_NOT_FOUND, + + // credit + INVALID_AMOUNT, + NOT_ENOUGH_CREDITS, + INVALID_TARGET, + TARGET_USER_NOT_FOUND + ; + +} 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..35dd4f041 --- /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(20, 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); + } + +} diff --git a/shared/src/main/java/net/leaderos/shared/model/Request.java b/shared/src/main/java/net/leaderos/shared/model/Request.java index 56526596b..3454856b6 100644 --- a/shared/src/main/java/net/leaderos/shared/model/Request.java +++ b/shared/src/main/java/net/leaderos/shared/model/Request.java @@ -3,6 +3,7 @@ import lombok.Getter; import lombok.SneakyThrows; import net.leaderos.shared.Shared; +import net.leaderos.shared.error.Error; import net.leaderos.shared.model.request.RequestType; import org.jetbrains.annotations.NotNull; import org.json.JSONArray; @@ -82,9 +83,10 @@ public Request(String api, Map body, @NotNull RequestType type) || responseCode == HttpURLConnection.HTTP_ACCEPTED || responseCode == HttpURLConnection.HTTP_OK); - String responseString = getStream(connection.getInputStream()); + String responseString = status ? getStream(connection.getInputStream()) : getStream(connection.getErrorStream()); try { - this.response = new Response(responseCode, status, getResponseObj(responseString)); + JSONObject obj = getResponseObj(responseString); + this.response = new Response(responseCode, status, obj, obj.has("error") ? obj.getEnum(Error.class, "error") : null); Shared.getDebugAPI().send(this.response.getResponseMessage().toString(), false); } catch (Exception e) { diff --git a/shared/src/main/java/net/leaderos/shared/model/Response.java b/shared/src/main/java/net/leaderos/shared/model/Response.java index cee1c1216..b76b44de9 100644 --- a/shared/src/main/java/net/leaderos/shared/model/Response.java +++ b/shared/src/main/java/net/leaderos/shared/model/Response.java @@ -3,6 +3,7 @@ import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; +import net.leaderos.shared.error.Error; import org.json.JSONObject; /** @@ -31,6 +32,11 @@ public class Response { */ private JSONObject responseMessage; + /** + * Error + */ + private Error error; + /** * Getter of responseMessage * @return JSONObject - message diff --git a/shared/src/main/java/net/leaderos/shared/model/request/impl/auth/AuthRequest.java b/shared/src/main/java/net/leaderos/shared/model/request/impl/auth/AuthRequest.java new file mode 100644 index 000000000..a35ed00c9 --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/model/request/impl/auth/AuthRequest.java @@ -0,0 +1,17 @@ +package net.leaderos.shared.model.request.impl.auth; + +import net.leaderos.shared.model.request.PostRequest; + +import java.io.IOException; +import java.util.HashMap; + +public class AuthRequest extends PostRequest { + + public AuthRequest(String username, String uuid) throws IOException { + super("auth/generate-link", new HashMap() {{ + put("username", username); + put("uuid", uuid); + }}); + } + +} diff --git a/shared/src/main/java/net/leaderos/shared/model/request/impl/bazaar/AddBazaarItemRequest.java b/shared/src/main/java/net/leaderos/shared/model/request/impl/bazaar/AddBazaarItemRequest.java new file mode 100644 index 000000000..70570ef36 --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/model/request/impl/bazaar/AddBazaarItemRequest.java @@ -0,0 +1,31 @@ +package net.leaderos.shared.model.request.impl.bazaar; + +import net.leaderos.shared.model.request.PostRequest; + +import java.io.IOException; +import java.util.HashMap; + +public class AddBazaarItemRequest extends PostRequest { + + public AddBazaarItemRequest(String userId, String name, String lore, int amount, int maxDurability, int durability, String base64, double price, String creationDate, String modelId, String enchantment, int serverId, String item) throws IOException { + super("bazaar/storages/" + userId + "/items", new HashMap() {{ + put("owner", userId); + put("name", name); + if (lore != null) + put("lore", lore); + put("amount", String.valueOf(amount)); + put("maxDurability", String.valueOf(maxDurability)); + put("durability", String.valueOf(durability)); + put("base64", base64); + put("price", String.valueOf(price)); + put("creationDate", String.valueOf(creationDate)); + if (modelId != null) + put("modelID", modelId); + if (enchantment != null) + put("enchantment", enchantment); + put("serverID", String.valueOf(serverId)); + put("itemID", item); + }}); + } + +} diff --git a/shared/src/main/java/net/leaderos/shared/model/request/impl/bazaar/GetBazaarItemsRequest.java b/shared/src/main/java/net/leaderos/shared/model/request/impl/bazaar/GetBazaarItemsRequest.java new file mode 100644 index 000000000..340cc2df4 --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/model/request/impl/bazaar/GetBazaarItemsRequest.java @@ -0,0 +1,13 @@ +package net.leaderos.shared.model.request.impl.bazaar; + +import net.leaderos.shared.model.request.GetRequest; + +import java.io.IOException; + +public class GetBazaarItemsRequest extends GetRequest { + + public GetBazaarItemsRequest(String userId, String serverId) throws IOException { + super("bazaar/storages/" + userId + "/items?serverID=" + serverId); + } + +} diff --git a/shared/src/main/java/net/leaderos/shared/model/request/impl/bazaar/RemoveBazaarItemRequest.java b/shared/src/main/java/net/leaderos/shared/model/request/impl/bazaar/RemoveBazaarItemRequest.java new file mode 100644 index 000000000..d678e979b --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/model/request/impl/bazaar/RemoveBazaarItemRequest.java @@ -0,0 +1,14 @@ +package net.leaderos.shared.model.request.impl.bazaar; + +import net.leaderos.shared.model.request.DeleteRequest; + +import java.io.IOException; +import java.util.HashMap; + +public class RemoveBazaarItemRequest extends DeleteRequest { + + public RemoveBazaarItemRequest(String userId, String id) throws IOException { + super("bazaar/storages/" + userId + "/items/" + id, new HashMap<>()); + } + +} diff --git a/shared/src/main/java/net/leaderos/shared/model/request/impl/credit/AddCreditsRequest.java b/shared/src/main/java/net/leaderos/shared/model/request/impl/credit/AddCreditsRequest.java new file mode 100644 index 000000000..1196b586d --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/model/request/impl/credit/AddCreditsRequest.java @@ -0,0 +1,16 @@ +package net.leaderos.shared.model.request.impl.credit; + +import net.leaderos.shared.model.request.PostRequest; + +import java.io.IOException; +import java.util.HashMap; + +public class AddCreditsRequest extends PostRequest { + + public AddCreditsRequest(String target, double amount) throws IOException { + super("credits/" + target + "/add", new HashMap() {{ + put("amount", String.valueOf(amount)); + }}); + } + +} diff --git a/shared/src/main/java/net/leaderos/shared/model/request/impl/credit/GetCreditsRequest.java b/shared/src/main/java/net/leaderos/shared/model/request/impl/credit/GetCreditsRequest.java new file mode 100644 index 000000000..73cba0b52 --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/model/request/impl/credit/GetCreditsRequest.java @@ -0,0 +1,13 @@ +package net.leaderos.shared.model.request.impl.credit; + +import net.leaderos.shared.model.request.GetRequest; + +import java.io.IOException; + +public class GetCreditsRequest extends GetRequest { + + public GetCreditsRequest(String username) throws IOException { + super("credits/" + username); + } + +} diff --git a/shared/src/main/java/net/leaderos/shared/model/request/impl/credit/RemoveCreditsRequest.java b/shared/src/main/java/net/leaderos/shared/model/request/impl/credit/RemoveCreditsRequest.java new file mode 100644 index 000000000..3a6657034 --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/model/request/impl/credit/RemoveCreditsRequest.java @@ -0,0 +1,14 @@ +package net.leaderos.shared.model.request.impl.credit; + +import net.leaderos.shared.model.request.PostRequest; + +import java.io.IOException; +import java.util.HashMap; + +public class RemoveCreditsRequest extends PostRequest { + public RemoveCreditsRequest(String target, double amount) throws IOException { + super("credits/" + target + "/remove", new HashMap() {{ + put("amount", String.valueOf(amount)); + }}); + } +} diff --git a/shared/src/main/java/net/leaderos/shared/model/request/impl/credit/SendCreditsRequest.java b/shared/src/main/java/net/leaderos/shared/model/request/impl/credit/SendCreditsRequest.java new file mode 100644 index 000000000..224f01cc7 --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/model/request/impl/credit/SendCreditsRequest.java @@ -0,0 +1,15 @@ +package net.leaderos.shared.model.request.impl.credit; + +import net.leaderos.shared.model.request.PostRequest; + +import java.io.IOException; +import java.util.HashMap; + +public class SendCreditsRequest extends PostRequest { + public SendCreditsRequest(String sender, String target, double amount) throws IOException { + super("credits/" + sender + "/send", new HashMap() {{ + put("target", target); + put("amount", String.valueOf(amount)); + }}); + } +} diff --git a/shared/src/main/java/net/leaderos/shared/model/request/impl/credit/SetCreditsRequest.java b/shared/src/main/java/net/leaderos/shared/model/request/impl/credit/SetCreditsRequest.java new file mode 100644 index 000000000..6cb91595a --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/model/request/impl/credit/SetCreditsRequest.java @@ -0,0 +1,14 @@ +package net.leaderos.shared.model.request.impl.credit; + +import net.leaderos.shared.model.request.PostRequest; + +import java.io.IOException; +import java.util.HashMap; + +public class SetCreditsRequest extends PostRequest { + public SetCreditsRequest(String target, double amount) throws IOException { + super("credits/" + target + "/set", new HashMap() {{ + put("amount", String.valueOf(amount)); + }}); + } +} diff --git a/shared/src/main/java/net/leaderos/shared/model/request/impl/discord/DiscordSyncRequest.java b/shared/src/main/java/net/leaderos/shared/model/request/impl/discord/DiscordSyncRequest.java new file mode 100644 index 000000000..cecd0aac0 --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/model/request/impl/discord/DiscordSyncRequest.java @@ -0,0 +1,14 @@ +package net.leaderos.shared.model.request.impl.discord; + +import net.leaderos.shared.model.request.PostRequest; + +import java.io.IOException; +import java.util.HashMap; + +public class DiscordSyncRequest extends PostRequest { + public DiscordSyncRequest(String username) throws IOException { + super("integrations/discord/sync", new HashMap() {{ + put("user", username); + }}); + } +} diff --git a/shared/src/main/java/net/leaderos/shared/model/request/impl/donations/GetDonationsRequest.java b/shared/src/main/java/net/leaderos/shared/model/request/impl/donations/GetDonationsRequest.java new file mode 100644 index 000000000..fb34a241d --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/model/request/impl/donations/GetDonationsRequest.java @@ -0,0 +1,17 @@ +package net.leaderos.shared.model.request.impl.donations; + +import net.leaderos.shared.model.request.GetRequest; + +import java.io.IOException; + +public class GetDonationsRequest extends GetRequest { + /** + * Request constructor + * + * @param api of request + * @throws IOException for HttpUrlConnection + */ + public GetDonationsRequest(String type) throws IOException { + super("store/donations/?type=" + type + "&limit=10"); + } +} diff --git a/shared/src/main/java/net/leaderos/shared/model/request/impl/store/BuyRequest.java b/shared/src/main/java/net/leaderos/shared/model/request/impl/store/BuyRequest.java new file mode 100644 index 000000000..1226c19b2 --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/model/request/impl/store/BuyRequest.java @@ -0,0 +1,18 @@ +package net.leaderos.shared.model.request.impl.store; + +import net.leaderos.shared.model.request.PostRequest; + +import java.io.IOException; +import java.util.HashMap; + +public class BuyRequest extends PostRequest { + + public BuyRequest(String user, String productId) throws IOException { + super("store/buy", new HashMap() {{ + put("user", user); + put("products[0][id]", productId); + put("products[0][quantity]", "1"); + }}); + } + +} diff --git a/shared/src/main/java/net/leaderos/shared/model/request/impl/store/ListingRequest.java b/shared/src/main/java/net/leaderos/shared/model/request/impl/store/ListingRequest.java new file mode 100644 index 000000000..91a1a9c8d --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/model/request/impl/store/ListingRequest.java @@ -0,0 +1,17 @@ +package net.leaderos.shared.model.request.impl.store; + +import net.leaderos.shared.model.request.GetRequest; + +import java.io.IOException; + +public class ListingRequest extends GetRequest { + /** + * Request constructor + * + * @param api of request + * @throws IOException for HttpUrlConnection + */ + public ListingRequest() throws IOException { + super("store/listing"); + } +} diff --git a/shared/src/main/java/net/leaderos/shared/model/request/impl/user/GetUserRequest.java b/shared/src/main/java/net/leaderos/shared/model/request/impl/user/GetUserRequest.java new file mode 100644 index 000000000..cbd3bef25 --- /dev/null +++ b/shared/src/main/java/net/leaderos/shared/model/request/impl/user/GetUserRequest.java @@ -0,0 +1,13 @@ +package net.leaderos.shared.model.request.impl.user; + +import net.leaderos.shared.model.request.GetRequest; + +import java.io.IOException; + +public class GetUserRequest extends GetRequest { + + public GetUserRequest(String name) throws IOException { + super("users/" + name); + } + +} diff --git a/shared/src/main/java/net/leaderos/shared/modules/auth/AuthHelper.java b/shared/src/main/java/net/leaderos/shared/modules/auth/AuthHelper.java index 1542c94d9..90648532f 100644 --- a/shared/src/main/java/net/leaderos/shared/modules/auth/AuthHelper.java +++ b/shared/src/main/java/net/leaderos/shared/modules/auth/AuthHelper.java @@ -1,11 +1,9 @@ package net.leaderos.shared.modules.auth; -import net.leaderos.shared.model.request.PostRequest; +import net.leaderos.shared.model.request.impl.auth.AuthRequest; import org.json.JSONObject; import java.io.IOException; -import java.util.HashMap; -import java.util.Map; import java.util.UUID; /** @@ -24,11 +22,8 @@ public class AuthHelper { * @throws IOException request exception */ private static String generateLink(String username, String uuid) throws IOException { - Map formData = new HashMap<>(); - formData.put("username", username); - formData.put("uuid", uuid); - PostRequest postRequest = new PostRequest("auth/generate-link", formData); - JSONObject response = postRequest.getResponse().getResponseMessage().getJSONObject("data"); + AuthRequest authRequest = new AuthRequest(username, uuid); + JSONObject response = authRequest.getResponse().getResponseMessage().getJSONObject("data"); return response.getString("url"); } diff --git a/shared/src/main/java/net/leaderos/shared/modules/credit/CreditHelper.java b/shared/src/main/java/net/leaderos/shared/modules/credit/CreditHelper.java index 6bea5fa0b..9114100b0 100644 --- a/shared/src/main/java/net/leaderos/shared/modules/credit/CreditHelper.java +++ b/shared/src/main/java/net/leaderos/shared/modules/credit/CreditHelper.java @@ -3,11 +3,9 @@ import net.leaderos.shared.model.Response; import net.leaderos.shared.model.request.GetRequest; import net.leaderos.shared.model.request.PostRequest; +import net.leaderos.shared.model.request.impl.credit.*; import org.jetbrains.annotations.Nullable; -import java.util.HashMap; -import java.util.Map; - /** * Helper Class for auth module * @author poyrazinan @@ -25,10 +23,7 @@ public class CreditHelper { */ public static @Nullable Response sendCreditRequest(String sender, String target, Double amount) { try { - Map list = new HashMap<>(); - list.put("target", target); - list.put("amount", String.valueOf(amount)); - PostRequest postSendCredit = new PostRequest("credits/" + sender + "/send", list); + PostRequest postSendCredit = new SendCreditsRequest(sender, target, amount); return postSendCredit.getResponse(); } catch (Exception e) { @@ -43,7 +38,7 @@ public class CreditHelper { */ public static @Nullable Response getRequest(String sender) { try { - GetRequest getCurrency = new GetRequest("credits/" + sender); + GetRequest getCurrency = new GetCreditsRequest(sender); return getCurrency.getResponse(); } catch (Exception e) { @@ -59,9 +54,7 @@ public class CreditHelper { */ public static @Nullable Response addCreditRequest(String target, double amount) { try { - Map list = new HashMap<>(); - list.put("amount", String.valueOf(amount)); - PostRequest postAddCredit = new PostRequest("credits/" + target + "/add", list); + PostRequest postAddCredit = new AddCreditsRequest(target, amount); return postAddCredit.getResponse(); } catch (Exception e) { @@ -77,9 +70,7 @@ public class CreditHelper { */ public static @Nullable Response removeCreditRequest(String target, double amount) { try { - Map list = new HashMap<>(); - list.put("amount", String.valueOf(amount)); - PostRequest postRemoveCredit = new PostRequest("credits/" + target + "/remove", list); + PostRequest postRemoveCredit = new RemoveCreditsRequest("credits/" + target + "/remove", amount); return postRemoveCredit.getResponse(); } catch (Exception e) { @@ -95,9 +86,7 @@ public class CreditHelper { */ public static @Nullable Response setCreditRequest(String target, double amount) { try { - Map list = new HashMap<>(); - list.put("amount", String.valueOf(amount)); - PostRequest postSetCredit = new PostRequest("credits/" + target + "/set", list); + PostRequest postSetCredit = new SetCreditsRequest(target, amount); return postSetCredit.getResponse(); } catch (Exception e) { diff --git a/shared/src/main/java/net/leaderos/shared/modules/discord/DiscordHelper.java b/shared/src/main/java/net/leaderos/shared/modules/discord/DiscordHelper.java index af33fd499..d0f3c1f56 100644 --- a/shared/src/main/java/net/leaderos/shared/modules/discord/DiscordHelper.java +++ b/shared/src/main/java/net/leaderos/shared/modules/discord/DiscordHelper.java @@ -1,11 +1,10 @@ package net.leaderos.shared.modules.discord; import net.leaderos.shared.model.request.PostRequest; +import net.leaderos.shared.model.request.impl.discord.DiscordSyncRequest; import org.json.JSONObject; import java.io.IOException; -import java.util.HashMap; -import java.util.Map; /** * Auth module helper class, share methods over platforms @@ -22,9 +21,7 @@ public class DiscordHelper { * @throws IOException request exception */ private static String generateLink(String username) throws IOException { - Map formData = new HashMap<>(); - formData.put("user", username); - PostRequest postRequest = new PostRequest("integrations/discord/sync", formData); + PostRequest postRequest = new DiscordSyncRequest(username); JSONObject response = postRequest.getResponse().getResponseMessage().getJSONObject("data"); return response.getString("url"); }