Skip to content

Commit

Permalink
Merge pull request #1 from efekurbann/main
Browse files Browse the repository at this point in the history
Some code improvements
  • Loading branch information
benfiratkaya authored Jan 20, 2024
2 parents f91b021 + 487e599 commit 16b13c4
Show file tree
Hide file tree
Showing 40 changed files with 737 additions and 386 deletions.
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -26,7 +27,7 @@ public CreditManager() {}
*/
public Double get(String player) {
Response amount = CreditHelper.getRequest(player);
if (amount == null) return null;
if (amount == null || amount.getResponseMessage() == null) return null;

return amount.getResponseMessage().getDouble("raw_credits");
}
Expand Down Expand Up @@ -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();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -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
*/
Expand Down Expand Up @@ -259,6 +261,8 @@ public static class Credit extends OkaeriConfig {

private String creditInfoOther = "{prefix} &b{target} &ahas &e{amount} &acredit(s)";

private String cannotSendCreditsThisUser = "{prefix} &cCould not send credits to this user.";

private String cannotSendCreditYourself = "{prefix} &cYou can not send credit(s) to yourself.";

private String cannotSendCreditNegative = "{prefix} &cPlease enter a valid amount. The amount must be higher than 0.";
Expand Down Expand Up @@ -423,6 +427,12 @@ public static class WebStoreGui extends OkaeriConfig {
*/
private String buyWebStoreNotEnoughCredit = "&cNot enough credits.";

private String buyWebStoreOutOfStock = "&cOut of stock.";

private String buyWebStoreProductNotFound = "&cProduct not found.";

private String buyWebStoreUserNotFound = "&cUser not found.";

/**
* withdraw item subtitle error
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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.";
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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.";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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(
Expand All @@ -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());
}
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
package net.leaderos.plugin.modules.bazaar.gui;

import com.cryptomorin.xseries.XMaterial;
import de.themoep.inventorygui.*;
import de.themoep.inventorygui.GuiStorageElement;
import de.themoep.inventorygui.InventoryGui;
import lombok.SneakyThrows;
import net.leaderos.plugin.Bukkit;
import net.leaderos.plugin.helpers.ChatUtil;
import net.leaderos.plugin.helpers.GameUtil;
import net.leaderos.plugin.helpers.GuiHelper;
import net.leaderos.plugin.modules.cache.model.User;
import net.leaderos.plugin.modules.bazaar.BazaarModule;
import net.leaderos.plugin.helpers.ItemUtil;
import net.leaderos.plugin.modules.bazaar.BazaarModule;
import net.leaderos.plugin.modules.cache.model.User;
import net.leaderos.shared.error.Error;
import net.leaderos.shared.helpers.Placeholder;
import net.leaderos.shared.model.Response;
import net.leaderos.shared.model.request.PostRequest;
import net.leaderos.shared.model.request.impl.bazaar.AddBazaarItemRequest;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryType;
Expand All @@ -22,7 +24,10 @@

import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
Expand Down Expand Up @@ -58,105 +63,88 @@ public static void showGui(Player player, int itemAmount) {
gui.addElement(new GuiStorageElement('i', inv));
// Close action area (event)
gui.setCloseAction(close -> {
// Calculating storage amounts
int maxStorageAmount = GameUtil.getAmountFromPerm(player,
"bazaar.maxstorage.",
Bukkit.getInstance().getModulesFile().getBazaar().getDefaultStorageSize());

int canStoreAmount = maxStorageAmount - itemAmount;
// Items which stored (airs included)
List<ItemStack> items = Arrays.stream(inv.getContents()).collect(Collectors.toList());
String userId = User.getUser(player.getName()).getId();
int serverId = BazaarModule.getServerId();
// Calculating storage amounts
int maxStorageAmount = GameUtil.getAmountFromPerm(player,
"bazaar.maxstorage.",
Bukkit.getInstance().getModulesFile().getBazaar().getDefaultStorageSize());

// If player maxed out storage limit items will be added to
// this list then gives back to player.
List<ItemStack> returnItems = new ArrayList<>();
int canStoreAmount = maxStorageAmount - itemAmount;
// Items which stored (airs included)
List<ItemStack> items = Arrays.stream(inv.getContents()).collect(Collectors.toList());
String userId = User.getUser(player.getName()).getId();
int serverId = BazaarModule.getServerId();

// item loop
for (ItemStack item : items) {
// Checks if item is empty or null (can be AIR etc.)
if (item == null)
continue;
if (item.getType() == null)
continue;
if (item.getType().equals(Material.AIR))
continue;
// Checks if area is filler item
if (item.equals(fillerItem))
continue;
// If player maxed out storage limit items will be added to
// this list then gives back to player.
List<ItemStack> returnItems = new ArrayList<>();

// Calculates storage amount
if (canStoreAmount > 0)
canStoreAmount--;
// If maxed out then add items to temp array
else {
returnItems.add(item);
continue;
}
// Item info
XMaterial material = XMaterial.matchXMaterial(item);
String name = ItemUtil.getName(item);
String lore = (item.hasItemMeta() && item.getItemMeta().hasLore()) ?
String.join("\n", item.getItemMeta().getLore()) : null;
int amount = item.getAmount();
int maxDurability = item.getType().getMaxDurability();
int durability = ItemUtil.getDurability(item, maxDurability);
String base64 = ItemUtil.toBase64(item);
double price = 0.0;
String creationDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
String modelId = ItemUtil.getModelId(item);
String enchantment = ItemUtil.getEnchantments(item);
// item loop
for (ItemStack item : items) {
// Checks if item is empty or null (can be AIR etc.)
if (item == null)
continue;
if (item.getType() == null)
continue;
if (item.getType().equals(Material.AIR))
continue;
// Checks if area is filler item
if (item.equals(fillerItem))
continue;

Map<String, String> body = new HashMap<>();
body.put("owner", userId);
body.put("name", name);
if (lore != null)
body.put("lore", lore);
body.put("amount", String.valueOf(amount));
body.put("maxDurability", String.valueOf(maxDurability));
body.put("durability", String.valueOf(durability));
// Calculates storage amount
if (canStoreAmount > 0)
canStoreAmount--;
// If maxed out then add items to temp array
else {
returnItems.add(item);
continue;
}
// Item info
XMaterial material = XMaterial.matchXMaterial(item);
String name = ItemUtil.getName(item);
String lore = (item.hasItemMeta() && item.getItemMeta().hasLore()) ?
String.join("\n", item.getItemMeta().getLore()) : null;
int amount = item.getAmount();
int maxDurability = item.getType().getMaxDurability();
int durability = ItemUtil.getDurability(item, maxDurability);
String base64 = ItemUtil.toBase64(item);
double price = 0.0;
String creationDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
String modelId = ItemUtil.getModelId(item);
String enchantment = ItemUtil.getEnchantments(item);

body.put("base64", base64);
body.put("price", String.valueOf(price));
body.put("creationDate", creationDate);
if (modelId != null)
body.put("modelID", modelId);
if (enchantment != null)
body.put("enchantment", enchantment);
body.put("serverID", String.valueOf(serverId));
body.put("itemID", material.name());
org.bukkit.Bukkit.getScheduler().runTaskAsynchronously(Bukkit.getInstance(), () -> {
// Sends response
try {
Response postBazaarItem = new AddBazaarItemRequest(userId, name, lore, amount, maxDurability, durability, base64, price, creationDate, modelId, enchantment, serverId, material.name()).getResponse();
if (postBazaarItem.getResponseCode() == HttpURLConnection.HTTP_OK
&& postBazaarItem.getResponseMessage().getBoolean("status")) {
ChatUtil.sendMessage(player, ChatUtil.replacePlaceholders(
Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getAddItemMessage(),
new Placeholder("%item_name%", name)
));
} else if (postBazaarItem.getError() == Error.INSERT_ERROR) {
returnItems.add(item);
} else throw new Exception();
} catch (Exception e) {
// TODO error msg
e.printStackTrace();
// If something occur when adding item it will pop item back to player inventory
returnItems.add(item);
}
if (!returnItems.isEmpty()) {
PlayerInventory playerInventory = player.getInventory();

// Sends response
try {
Response postBazaarItem = new PostRequest("bazaar/storages/" + userId + "/items", body).getResponse();
if (postBazaarItem.getResponseCode() == HttpURLConnection.HTTP_OK
&& postBazaarItem.getResponseMessage().getBoolean("status")) {
ChatUtil.sendMessage(player, ChatUtil.replacePlaceholders(
Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getAddItemMessage(),
new Placeholder("%item_name%", name)
));
returnItems.forEach(playerInventory::addItem);
String returnMessage = Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getReturnItemMessage();
returnMessage = returnMessage.replace("%max_amount%", String.valueOf(maxStorageAmount))
.replace("%amount%", String.valueOf(returnItems.size()));
ChatUtil.sendMessage(player, returnMessage);
}
});
}
else throw new Exception();
} catch (Exception e) {
// TODO error msg
e.printStackTrace();
// If something occur when adding item it will pop item back to player inventory
returnItems.add(item);
}
}

// Gives items back to player
if (!returnItems.isEmpty()) {
PlayerInventory playerInventory = player.getInventory();
returnItems.forEach(playerInventory::addItem);
String returnMessage = Bukkit.getInstance().getLangFile().getGui().getBazaarGui().getReturnItemMessage();
returnMessage = returnMessage.replace("%max_amount%", String.valueOf(maxStorageAmount))
.replace("%amount%", String.valueOf(returnItems.size()));
ChatUtil.sendMessage(player, returnMessage);
}
return false; // Don't go back to the previous GUI (true would automatically go back to the previously opened one)
});
return false; // Don't go back to the previous GUI (true would automatically go back to the previously opened one)
});
gui.show(player);
}
}
Loading

0 comments on commit 16b13c4

Please sign in to comment.