From d2701efa60e3fc95e888ce496e847a39c4d0b485 Mon Sep 17 00:00:00 2001 From: Efe Kurban Date: Sat, 6 Jan 2024 20:59:00 +0300 Subject: [PATCH 1/5] Some code refactoring done by adding classes dedicated to requests --- .../modules/bazaar/gui/BazaarAddItemGui.java | 35 ++++++------------- .../modules/bazaar/model/PlayerBazaar.java | 9 ++--- .../plugin/modules/cache/model/User.java | 5 +-- .../donations/managers/DonationManager.java | 6 ++-- .../webstore/helpers/WebStoreHelper.java | 11 ++---- .../modules/webstore/model/Category.java | 3 +- .../model/request/impl/auth/AuthRequest.java | 17 +++++++++ .../impl/bazaar/AddBazaarItemRequest.java | 31 ++++++++++++++++ .../impl/bazaar/GetBazaarItemsRequest.java | 13 +++++++ .../impl/bazaar/RemoveBazaarItemRequest.java | 14 ++++++++ .../impl/credit/AddCreditsRequest.java | 16 +++++++++ .../impl/credit/GetCreditsRequest.java | 13 +++++++ .../impl/credit/RemoveCreditsRequest.java | 14 ++++++++ .../impl/credit/SendCreditsRequest.java | 15 ++++++++ .../impl/credit/SetCreditsRequest.java | 14 ++++++++ .../impl/discord/DiscordSyncRequest.java | 14 ++++++++ .../impl/donations/GetDonationsRequest.java | 17 +++++++++ .../model/request/impl/store/BuyRequest.java | 18 ++++++++++ .../request/impl/store/ListingRequest.java | 17 +++++++++ .../request/impl/user/GetUserRequest.java | 13 +++++++ .../shared/modules/auth/AuthHelper.java | 11 ++---- .../shared/modules/credit/CreditHelper.java | 23 ++++-------- .../shared/modules/discord/DiscordHelper.java | 7 ++-- 23 files changed, 262 insertions(+), 74 deletions(-) create mode 100644 shared/src/main/java/net/leaderos/shared/model/request/impl/auth/AuthRequest.java create mode 100644 shared/src/main/java/net/leaderos/shared/model/request/impl/bazaar/AddBazaarItemRequest.java create mode 100644 shared/src/main/java/net/leaderos/shared/model/request/impl/bazaar/GetBazaarItemsRequest.java create mode 100644 shared/src/main/java/net/leaderos/shared/model/request/impl/bazaar/RemoveBazaarItemRequest.java create mode 100644 shared/src/main/java/net/leaderos/shared/model/request/impl/credit/AddCreditsRequest.java create mode 100644 shared/src/main/java/net/leaderos/shared/model/request/impl/credit/GetCreditsRequest.java create mode 100644 shared/src/main/java/net/leaderos/shared/model/request/impl/credit/RemoveCreditsRequest.java create mode 100644 shared/src/main/java/net/leaderos/shared/model/request/impl/credit/SendCreditsRequest.java create mode 100644 shared/src/main/java/net/leaderos/shared/model/request/impl/credit/SetCreditsRequest.java create mode 100644 shared/src/main/java/net/leaderos/shared/model/request/impl/discord/DiscordSyncRequest.java create mode 100644 shared/src/main/java/net/leaderos/shared/model/request/impl/donations/GetDonationsRequest.java create mode 100644 shared/src/main/java/net/leaderos/shared/model/request/impl/store/BuyRequest.java create mode 100644 shared/src/main/java/net/leaderos/shared/model/request/impl/store/ListingRequest.java create mode 100644 shared/src/main/java/net/leaderos/shared/model/request/impl/user/GetUserRequest.java 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..f30113368 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,19 @@ 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.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 +23,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; /** @@ -108,28 +112,9 @@ public static void showGui(Player player, int itemAmount) { String modelId = ItemUtil.getModelId(item); String enchantment = ItemUtil.getEnchantments(item); - 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)); - - 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()); - // Sends response try { - Response postBazaarItem = new PostRequest("bazaar/storages/" + userId + "/items", body).getResponse(); + 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( 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..aca4c6a74 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,12 @@ 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.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; @@ -77,7 +78,7 @@ public ItemStack getItem() { */ @SneakyThrows public boolean withdrawItem(Player player) { - Response deleteRequest = new DeleteRequest("bazaar/storages/" + getUserId() + "/items/" + getId()).getResponse(); + Response deleteRequest = new RemoveBazaarItemRequest(getUserId(), getUserId()).getResponse(); if (deleteRequest.getResponseCode() == HttpURLConnection.HTTP_OK && deleteRequest.getResponseMessage().getBoolean("status")) { ItemStack item = ItemUtil.fromBase64(getBase64()); @@ -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/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/webstore/helpers/WebStoreHelper.java b/bukkit/src/main/java/net/leaderos/plugin/modules/webstore/helpers/WebStoreHelper.java index 0f1b1805e..5ce8f1113 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,26 +6,19 @@ 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.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()); @@ -35,7 +28,7 @@ public static void buyItem(Player player, String productId) { player.sendTitle(title, subtitleProgress); // Buy progress try { - Response buyRequest = new PostRequest("store/buy", body).getResponse(); + 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"); 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/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..4bc51609e 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("credits/" + target + "/set", 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"); } From 6e738b8de220ec68d865f05efed5d8363a9039d1 Mon Sep 17 00:00:00 2001 From: Efe Kurban Date: Sat, 13 Jan 2024 22:15:36 +0300 Subject: [PATCH 2/5] 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); + } + +} From 44df4a8e1f08a6aacd3afe88b341f1249a0eb31f Mon Sep 17 00:00:00 2001 From: Efe Kurban Date: Mon, 15 Jan 2024 22:49:44 +0300 Subject: [PATCH 3/5] refactor DonationType to something sane, i guess --- .../modules/donations/model/DonationType.java | 77 ++++--------------- 1 file changed, 14 insertions(+), 63 deletions(-) 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'; - } } From 3c62524d42891e4d9c2d705fcb3adfa7526c8746 Mon Sep 17 00:00:00 2001 From: Efe Kurban Date: Mon, 15 Jan 2024 22:51:24 +0300 Subject: [PATCH 4/5] Bulk Update includes async, custom error codes and more. --- .../api/modules/credit/CreditManager.java | 9 ++++-- .../plugin/configuration/Language.java | 8 +++++ .../plugin/configuration/lang/en.java | 3 +- .../plugin/configuration/lang/tr.java | 3 +- .../modules/bazaar/gui/BazaarAddItemGui.java | 3 ++ .../plugin/modules/bazaar/gui/BazaarGui.java | 14 ++++---- .../modules/bazaar/model/PlayerBazaar.java | 10 +++--- .../credit/commands/CreditCommand.java | 20 +++++++++--- .../voucher/listeners/VoucherListener.java | 23 +++++++++---- .../webstore/helpers/WebStoreHelper.java | 11 +++++-- .../bungee/configuration/Language.java | 2 ++ .../credit/commands/CreditCommand.java | 13 ++++++-- .../java/net/leaderos/shared/error/Error.java | 32 +++++++++++++++++++ .../net/leaderos/shared/model/Request.java | 6 ++-- .../net/leaderos/shared/model/Response.java | 6 ++++ 15 files changed, 131 insertions(+), 32 deletions(-) create mode 100644 shared/src/main/java/net/leaderos/shared/error/Error.java 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..6c155a0df 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; @@ -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 2afb83d4b..87e16ddf1 100644 --- a/bukkit/src/main/java/net/leaderos/plugin/configuration/Language.java +++ b/bukkit/src/main/java/net/leaderos/plugin/configuration/Language.java @@ -261,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."; @@ -425,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/bazaar/gui/BazaarAddItemGui.java b/bukkit/src/main/java/net/leaderos/plugin/modules/bazaar/gui/BazaarAddItemGui.java index 21dbb68e7..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 @@ -11,6 +11,7 @@ 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.impl.bazaar.AddBazaarItemRequest; @@ -122,6 +123,8 @@ public static void showGui(Player player, int itemAmount) { 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 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 b3dad923e..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 @@ -10,6 +10,7 @@ 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.shared.error.Error; import net.leaderos.shared.helpers.RequestUtil; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; @@ -39,9 +40,9 @@ public static void showGui(Player player) { return; } - org.bukkit.Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getInstance(), () -> { - RequestUtil.addRequest(player.getUniqueId()); + 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 @@ -85,11 +86,13 @@ public static void showGui(Player player) { player.sendTitle(title, subtitleProgress); org.bukkit.Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getInstance(), () -> { - boolean withdrawStatus = playerBazaarItem.withdrawItem(player); - if (withdrawStatus) + Error error = playerBazaarItem.withdrawItem(player); + if (error == null) player.sendTitle(title, subtitleSuccess); - else + else if (error == Error.DELETE_ERROR) player.sendTitle(title, subtitleError); + + RequestUtil.invalidate(player.getUniqueId()); }); return false; @@ -104,7 +107,6 @@ public static void showGui(Player 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/bazaar/model/PlayerBazaar.java b/bukkit/src/main/java/net/leaderos/plugin/modules/bazaar/model/PlayerBazaar.java index aca4c6a74..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 @@ -7,6 +7,7 @@ import net.leaderos.plugin.helpers.ChatUtil; 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.GetRequest; import net.leaderos.shared.model.request.impl.bazaar.GetBazaarItemsRequest; @@ -77,17 +78,16 @@ public ItemStack getItem() { * @return status of withdraw */ @SneakyThrows - public boolean withdrawItem(Player player) { + 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(); } /** 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 208c15edd..8ad5ade31 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,6 +10,7 @@ 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.helpers.RequestUtil; @@ -59,7 +60,7 @@ public void defaultCommand(Player player) { * 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") @@ -72,23 +73,24 @@ public void sendCommand(Player player, String target, Double a) { RequestUtil.addRequest(player.getUniqueId()); org.bukkit.Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getInstance(), () -> { - double amount = MoneyUtil.parseDouble(a); Player targetPlayer = org.bukkit.Bukkit.getPlayerExact(target); if (player.getName().equalsIgnoreCase(target)) { + RequestUtil.invalidate(player.getUniqueId()); ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditYourself()); return; } if (amount <= 0) { + RequestUtil.invalidate(player.getUniqueId()); ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNegative()); return; } - boolean sendCredit = LeaderOSAPI.getCreditManager().send(player.getName(), target, amount); + Error error = LeaderOSAPI.getCreditManager().send(player.getName(), target, amount); - if (sendCredit) { + if (error == null) { // 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( @@ -106,8 +108,16 @@ public void sendCommand(Player player, String target, Double a) { new Placeholder("{player}", player.getName()) )); } - } else + } else if (error == Error.NOT_ENOUGH_CREDITS || error == Error.USER_NOT_FOUND) { ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNotEnough()); + } 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, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNotEnough()); + } RequestUtil.invalidate(player.getUniqueId()); }); 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 023867c29..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,7 +76,12 @@ public void onRightClick(PlayerInteractEvent event) { return; } - remove(player, 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(); @@ -84,19 +91,23 @@ public void onRightClick(PlayerInteractEvent event) { 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))); + 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 { + } 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 997302d19..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,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.error.Error; import net.leaderos.shared.helpers.RequestUtil; import net.leaderos.shared.model.Response; import net.leaderos.shared.model.request.impl.store.BuyRequest; @@ -41,9 +42,15 @@ public static void buyItem(Player player, String productId) { org.bukkit.Bukkit.getPluginManager().callEvent(new UpdateCacheEvent(player.getName(), credits, UpdateType.SET)); player.sendTitle(title, subtitleSuccess); } - else if (buyRequest.getResponseCode() == HttpURLConnection.HTTP_BAD_REQUEST) + else if (buyRequest.getError() == Error.INVALID_QUANTITY + || buyRequest.getError() == Error.INSUFFICIENT_BALANCE) player.sendTitle(title, subtitleNotEnoughCredit); - else throw new IOException(); + 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); } 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/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/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 From 487e59970f06e3b309a40ed962b2e20264349e42 Mon Sep 17 00:00:00 2001 From: Efe Kurban Date: Sat, 20 Jan 2024 15:53:53 +0300 Subject: [PATCH 5/5] Some fixes --- .../plugin/api/modules/credit/CreditManager.java | 2 +- .../modules/credit/commands/CreditCommand.java | 13 ++++++++++--- .../net/leaderos/shared/helpers/RequestUtil.java | 2 +- .../shared/modules/credit/CreditHelper.java | 2 +- 4 files changed, 13 insertions(+), 6 deletions(-) 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 6c155a0df..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 @@ -27,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"); } 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 8ad5ade31..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 @@ -92,7 +92,8 @@ public void sendCommand(Player player, String target, Double a) { if (error == null) { // Calls UpdateCache event for update player's cache - org.bukkit.Bukkit.getPluginManager().callEvent(new UpdateCacheEvent(player.getName(), amount, UpdateType.REMOVE)); + 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)), @@ -109,14 +110,20 @@ public void sendCommand(Player player, String target, Double a) { )); } } else if (error == Error.NOT_ENOUGH_CREDITS || error == Error.USER_NOT_FOUND) { - ChatUtil.sendMessage(player, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNotEnough()); + 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, Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNotEnough()); + ChatUtil.sendMessage(player, ChatUtil.replacePlaceholders( + Bukkit.getInstance().getLangFile().getMessages().getCredit().getCannotSendCreditNotEnough(), + new Placeholder("{amount}", MoneyUtil.format(amount)) + )); } RequestUtil.invalidate(player.getUniqueId()); diff --git a/shared/src/main/java/net/leaderos/shared/helpers/RequestUtil.java b/shared/src/main/java/net/leaderos/shared/helpers/RequestUtil.java index b9ab8a6ad..35dd4f041 100644 --- a/shared/src/main/java/net/leaderos/shared/helpers/RequestUtil.java +++ b/shared/src/main/java/net/leaderos/shared/helpers/RequestUtil.java @@ -8,7 +8,7 @@ public class RequestUtil { - private static final Cache CACHE = CacheBuilder.newBuilder().expireAfterWrite(5, TimeUnit.SECONDS).build(); + private static final Cache CACHE = CacheBuilder.newBuilder().expireAfterWrite(20, TimeUnit.SECONDS).build(); public static void addRequest(UUID uuid) { CACHE.put(uuid, (byte) 1); 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 4bc51609e..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 @@ -86,7 +86,7 @@ public class CreditHelper { */ public static @Nullable Response setCreditRequest(String target, double amount) { try { - PostRequest postSetCredit = new SetCreditsRequest("credits/" + target + "/set", amount); + PostRequest postSetCredit = new SetCreditsRequest(target, amount); return postSetCredit.getResponse(); } catch (Exception e) {