Files
src
pom.xml
Code
6 412
src/main/java/ua/minesmp/sell/SellPlugin.java
package ua.minesmp.sell;
import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.XSound;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.title.Title;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.Damageable;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardOpenOption;
import java.text.NumberFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public final class SellPlugin extends JavaPlugin implements Listener, TabExecutor {
private final MiniMessage mm = MiniMessage.miniMessage();
private final ExecutorService io = Executors.newSingleThreadExecutor();
private final Map<UUID, Long> cooldowns = new HashMap<>();
private YamlConfiguration prices, messages, data;
private Economy economy;
private int frame;
@Override public void onEnable() {
RegisteredServiceProvider<Economy> provider = getServer().getServicesManager().getRegistration(Economy.class);
if (provider == null || provider.getProvider() == null) {
getLogger().severe("Vault не має провайдера економіки.");
getServer().getPluginManager().disablePlugin(this);
return;
}
economy = provider.getProvider();
saveDefaultConfig();
if (!new File(getDataFolder(), "prices.yml").exists()) saveResource("prices.yml", false);
if (!new File(getDataFolder(), "messages.yml").exists()) saveResource("messages.yml", false);
prices = load("prices.yml"); messages = load("messages.yml"); data = load("data.yml");
for (Material material : Material.values()) {
if (material.isItem() && !prices.contains("prices." + material.name())) prices.set("prices." + material.name(), defaultPrice(material.name()));
}
savePrices();
getServer().getPluginManager().registerEvents(this, this);
getCommand("sell").setExecutor(this);
getCommand("sell").setTabCompleter(this);
Bukkit.getScheduler().runTaskTimer(this, () -> {
frame++;
for (Player p : Bukkit.getOnlinePlayers()) {
Inventory inv = p.getOpenInventory().getTopInventory();
if (inv.getHolder() instanceof Menu menu && menu.kind.equals("sell")) decorate(inv);
if (inv.getHolder() instanceof Menu menu && menu.kind.startsWith("top") && frame % 30 == 0) fillTop(inv, menu.kind);
}
}, 20L, 20L);
Bukkit.getScheduler().runTaskTimer(this, this::recalculate, 12000L, 12000L);
Bukkit.getScheduler().runTaskTimer(this, this::saveData, 1200L, 1200L);
}
@Override public void onDisable() {
for (Player p : Bukkit.getOnlinePlayers()) if (p.getOpenInventory().getTopInventory().getHolder() instanceof Menu) p.closeInventory();
if (data != null) saveData();
io.shutdown();
try { if (!io.awaitTermination(10, TimeUnit.SECONDS)) getLogger().warning("Не всі файли встигли зберегтися."); }
catch (InterruptedException ex) { Thread.currentThread().interrupt(); }
}
private YamlConfiguration load(String name) { return YamlConfiguration.loadConfiguration(new File(getDataFolder(), name)); }
private void writeAsync(String name, String text, boolean append) {
File file = new File(getDataFolder(), name);
io.execute(() -> {
try {
if (append) Files.writeString(file.toPath(), text, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
else Files.writeString(file.toPath(), text, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
} catch (IOException ex) { getLogger().severe("Помилка запису " + name + ": " + ex.getMessage()); }
});
}
private void saveData() { writeAsync("data.yml", data.saveToString(), false); }
private void savePrices() { writeAsync("prices.yml", prices.saveToString(), false); }
private double defaultPrice(String n) {
if (n.equals("NETHERITE_INGOT") || n.equals("ELYTRA") || n.equals("DRAGON_EGG")) return 15000;
if (n.contains("SHULKER_BOX") || n.endsWith("_HEAD") || n.endsWith("_SKULL") || n.equals("TOTEM_OF_UNDYING") || n.equals("ENCHANTED_GOLDEN_APPLE")) return 12000;
if (n.contains("NETHERITE")) return 2000;
if (n.contains("DIAMOND")) return 500;
if (n.contains("EMERALD")) return 300;
if (n.contains("GOLD")) return 55;
if (n.contains("IRON")) return 30;
if (n.contains("COPPER") || n.contains("LAPIS") || n.contains("REDSTONE")) return 12;
if (n.contains("LOG") || n.contains("PLANK") || n.contains("FOOD")) return 4;
return 1;
}
private Component text(String s) { return mm.deserialize(s); }
private void msg(CommandSender sender, String key) { sender.sendMessage(text(messages.getString("prefix", "") + messages.getString(key, key))); }
private String money(double value) {
NumberFormat f = NumberFormat.getNumberInstance(Locale.US); f.setMaximumFractionDigits(2);
return f.format(value).replace(',', ' ');
}
private double base(Material m) { return Math.max(0, prices.getDouble("prices." + m.name(), 1)); }
private double multiplier(Material m) { return data.getDouble("market." + m.name() + ".multiplier", 1); }
private double current(Material m) { return base(m) * multiplier(m) * Math.max(0, getConfig().getDouble("economy-multiplier", 1)); }
private boolean allowed(ItemStack item) {
if (item == null || item.getType().isAir() || getConfig().getStringList("blacklist").contains(item.getType().name())) return false;
ItemMeta meta = item.getItemMeta();
if (meta == null) return true;
return meta.getPersistentDataContainer().getKeys().stream().noneMatch(key -> key.getKey().equalsIgnoreCase("nosell"));
}
private double itemPrice(ItemStack item) {
double value = current(item.getType());
ItemMeta meta = item.getItemMeta();
if (meta != null) {
value *= 1 + Math.min(2, meta.getEnchants().values().stream().mapToInt(Integer::intValue).sum() * 0.1);
if (meta instanceof Damageable d && item.getType().getMaxDurability() > 0) value *= Math.max(0.05, 1.0 - (double) d.getDamage() / item.getType().getMaxDurability());
}
return value;
}
private int limit(Material type) {
return Math.max(0, getConfig().getInt(base(type) >= getConfig().getDouble("hourly-limit.rare-price", 10000) ? "hourly-limit.rare" : "hourly-limit.cheap", 5));
}
private int used(UUID id, Material type) {
String path = "limits." + id + "." + type.name();
if (System.currentTimeMillis() - data.getLong(path + ".time") >= 3600000L) return 0;
return data.getInt(path + ".count");
}
private record Line(int slot, ItemStack item, int amount, double value) {}
private List<Line> quote(Player player, Inventory inv, int from, int to) {
List<Line> result = new ArrayList<>(); Map<Material, Integer> pending = new HashMap<>();
double decay = Math.max(0, getConfig().getDouble("market.stack-decay", 0.001));
for (int slot = from; slot <= to; slot++) {
ItemStack item = inv.getItem(slot); if (!allowed(item)) continue;
Material type = item.getType(); int already = pending.getOrDefault(type, 0);
int amount = Math.min(item.getAmount(), Math.max(0, limit(type) - used(player.getUniqueId(), type) - already));
if (amount == 0) continue;
double value = 0; for (int i = 0; i < amount; i++) value += itemPrice(item) / (1 + decay * (already + i));
pending.put(type, already + amount); result.add(new Line(slot, item.clone(), amount, value));
}
return result;
}
private double sum(List<Line> lines) { return Math.round(lines.stream().mapToDouble(Line::value).sum() * 100.0) / 100.0; }
private void sell(Player player, Inventory inv, int from, int to) {
if (System.currentTimeMillis() - cooldowns.getOrDefault(player.getUniqueId(), 0L) < getConfig().getLong("cooldown-seconds", 2) * 1000L) { msg(player, "cooldown"); return; }
List<Line> lines = quote(player, inv, from, to); double total = sum(lines);
if (lines.isEmpty() || total <= 0 || !Double.isFinite(total)) { msg(player, "empty"); return; }
if (!economy.depositPlayer(player, total).transactionSuccess()) { msg(player, "failed"); return; }
long now = System.currentTimeMillis(); cooldowns.put(player.getUniqueId(), now);
String stats = "players." + player.getUniqueId();
int count = 0;
for (Line line : lines) {
ItemStack original = inv.getItem(line.slot());
if (original.getAmount() == line.amount()) inv.setItem(line.slot(), null); else original.setAmount(original.getAmount() - line.amount());
Material type = line.item().getType(); count += line.amount();
String lp = "limits." + player.getUniqueId() + "." + type.name();
if (now - data.getLong(lp + ".time") >= 3600000L) { data.set(lp + ".time", now); data.set(lp + ".count", 0); }
data.set(lp + ".count", data.getInt(lp + ".count") + line.amount());
String sp = stats + ".items." + type.name(); data.set(sp, data.getInt(sp) + line.amount());
String mp = "market." + type.name();
double floor = getConfig().getDouble("market.minimum", 0.3);
data.set(mp + ".multiplier", Math.max(floor, multiplier(type) * Math.pow(1 - Math.min(0.1, Math.max(0, getConfig().getDouble("market.instant-drop-per-item", 0.0002))), line.amount())));
String bucket = mp + ".history." + (now / 600000L); data.set(bucket, data.getInt(bucket) + line.amount());
writeAsync("sales.log", now + " " + player.getUniqueId() + " " + player.getName() + " " + type.name() + " x" + line.amount() + " " + money(line.value()) + "\n", true);
}
data.set(stats + ".count", data.getLong(stats + ".count") + count);
data.set(stats + ".earned", data.getDouble(stats + ".earned") + total);
data.set(stats + ".record", Math.max(total, data.getDouble(stats + ".record")));
player.sendMessage(text(messages.getString("prefix", "") + messages.getString("sold", "<green>Продано: <amount> грн</green>").replace("<amount>", money(total))));
player.showTitle(Title.title(text("<green>Продано!</green>"), Component.empty(), Title.Times.times(Duration.ofMillis(200), Duration.ofSeconds(2), Duration.ofMillis(400))));
player.sendActionBar(text("<yellow>+" + money(total) + " грн</yellow>"));
XSound.matchXSound(total > getConfig().getDouble("expensive-threshold", 5000) ? "UI_TOAST_CHALLENGE_COMPLETE" : "ENTITY_EXPERIENCE_ORB_PICKUP").ifPresent(s -> s.play(player));
saveData();
}
private void recalculate() {
long cutoff = System.currentTimeMillis() / 600000L - 30;
ConfigurationSection market = data.getConfigurationSection("market"); if (market == null) return;