Files
src
COMMANDS.md
Code
6 530
src/main/java/com/kodari/recoinshop/ReCoinShop.java
package com.kodari.recoinshop;
import com.cryptomorin.xseries.XMaterial;
import com.cryptomorin.xseries.XEnchantment;
import com.cryptomorin.xseries.XItemFlag;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
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.InventoryDragEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
public final class ReCoinShop extends JavaPlugin implements Listener, CommandExecutor, TabCompleter {
private YamlConfiguration messages, currencies, balances;
private final Map<String, YamlConfiguration> menus = new TreeMap<>();
private File menuDir, dataFile;
@Override public void onEnable() {
saveDefaultConfig();
if (!new File(getDataFolder(), "messages.yml").exists()) saveResource("messages.yml", false);
if (!new File(getDataFolder(), "currencies.yml").exists()) saveResource("currencies.yml", false);
menuDir = new File(getDataFolder(), "menus");
menuDir.mkdirs();
File dataDir = new File(getDataFolder(), "data");
dataDir.mkdirs();
dataFile = new File(dataDir, "balances.yml");
loadFiles();
Bukkit.getPluginManager().registerEvents(this, this);
for (String name : Arrays.asList("rcshop", "coin", "coins", "rcreload")) {
Objects.requireNonNull(getCommand(name)).setExecutor(this);
Objects.requireNonNull(getCommand(name)).setTabCompleter(this);
}
}
private void loadFiles() {
reloadConfig();
messages = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "messages.yml"));
currencies = YamlConfiguration.loadConfiguration(new File(getDataFolder(), "currencies.yml"));
balances = YamlConfiguration.loadConfiguration(dataFile);
menus.clear();
File[] files = menuDir.listFiles((dir, name) -> name.endsWith(".yml"));
if (files != null) for (File file : files) menus.put(file.getName().substring(0, file.getName().length() - 4), YamlConfiguration.loadConfiguration(file));
}
private void save(YamlConfiguration yaml, File file) {
try { yaml.save(file); } catch (IOException ex) { throw new IllegalStateException("Could not save " + file, ex); }
}
private void saveMenu(String id) { save(menus.get(id), new File(menuDir, id + ".yml")); }
private void saveCurrencies() { save(currencies, new File(getDataFolder(), "currencies.yml")); }
private void saveBalances() { save(balances, dataFile); }
private String color(String s) { return ChatColor.translateAlternateColorCodes('&', s == null ? "" : s); }
private void msg(CommandSender sender, String text) { sender.sendMessage(color(messages.getString("prefix", "&6[ReCoinShop] &r") + text)); }
private boolean allowed(CommandSender s, String permission) {
if (s.hasPermission(permission) || s.hasPermission("recoinshop.admin")) return true;
msg(s, messages.getString("no-permission", "&cNo permission.")); return false;
}
private boolean idValid(String id) { return id.matches("[a-z0-9_-]{1,64}"); }
private String normalize(String s) { return s.toLowerCase(Locale.ROOT); }
private Set<String> keys(ConfigurationSection section) { return section == null ? Collections.emptySet() : section.getKeys(false); }
private Set<String> currencyIds() { return keys(currencies.getConfigurationSection("currencies")); }
private String defaultCurrency() { return normalize(getConfig().getString("default-currency", "coins")); }
private String currencyName(String id) { return currencies.getString("currencies." + id + ".name", id); }
private long balance(UUID uuid, String id) { return balances.getLong(uuid + "." + id, 0); }
private void balance(UUID uuid, String id, long value) { balances.set(uuid + "." + id, value); }
private long number(String s, boolean zero) {
long n = Long.parseLong(s);
if (n < 0 || (!zero && n == 0)) throw new IllegalArgumentException("Amount must be " + (zero ? "non-negative" : "positive") + ".");
return n;
}
private int slot(String s) {
int n = Integer.parseInt(s);
if (n < 1 || n > 1000000) throw new IllegalArgumentException("Slot must be between 1 and 1000000.");
return n;
}
private ItemStack material(String name) {
ItemStack item = XMaterial.matchXMaterial(name.toUpperCase(Locale.ROOT)).map(XMaterial::parseItem).orElse(null);
if (item == null || item.getType().isAir()) throw new IllegalArgumentException("Invalid item material: " + name);
return item;
}
private OfflinePlayer player(String name) {
Player online = Bukkit.getPlayerExact(name);
if (online != null) return online;
OfflinePlayer offline = Bukkit.getOfflinePlayer(name);
if (!offline.hasPlayedBefore()) throw new IllegalArgumentException("Player has never joined: " + name);
return offline;
}
@Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
try {
switch (command.getName().toLowerCase(Locale.ROOT)) {
case "rcreload":
if (allowed(sender, "recoinshop.reload")) { saveBalances(); loadFiles(); msg(sender, "&aConfiguration and data reloaded."); }
break;
case "coins":
if (!(sender instanceof Player)) throw new IllegalArgumentException("Only players can open the shop.");
openMain((Player) sender, 0); break;
case "coin": coin(sender, args); break;
case "rcshop": admin(sender, args); break;
default: return false;
}
} catch (IllegalArgumentException | ArithmeticException ex) { msg(sender, "&c" + (ex.getMessage() == null ? "Invalid number." : ex.getMessage())); }
catch (IllegalStateException ex) { getLogger().severe(ex.getMessage()); msg(sender, "&cCould not save data; contact an administrator."); }
return true;
}
private void coin(CommandSender s, String[] a) {
String action = a.length == 0 ? "balance" : normalize(a[0]);
if (action.equals("balance")) {
if (!allowed(s, "recoinshop.balance")) return;
if (a.length > 3) throw new IllegalArgumentException("Usage: /coin balance [player] [currency]");
OfflinePlayer target = a.length > 1 ? player(a[1]) : (s instanceof Player ? (Player)s : null);
if (target == null) throw new IllegalArgumentException("Specify a player.");
String currency = a.length > 2 ? normalize(a[2]) : defaultCurrency();
requireCurrency(currency);
msg(s, "&e" + target.getName() + ": " + currencies.getString("currencies." + currency + ".symbol", "") + balance(target.getUniqueId(), currency) + " " + currencyName(currency));
return;
}
if (!Arrays.asList("give", "take", "set", "pay").contains(action) || a.length < 3 || a.length > 4)
throw new IllegalArgumentException("Usage: /coin <balance|give|take|set|pay> [player] [amount] [currency]");
if (!allowed(s, action.equals("pay") ? "recoinshop.pay" : "recoinshop.admin")) return;
OfflinePlayer target = player(a[1]);
long amount = number(a[2], action.equals("set"));
String currency = a.length == 4 ? normalize(a[3]) : defaultCurrency();
requireCurrency(currency);
long old = balance(target.getUniqueId(), currency), value;
if (action.equals("pay")) {
if (!(s instanceof Player)) throw new IllegalArgumentException("Only players can pay.");
UUID from = ((Player)s).getUniqueId();
if (from.equals(target.getUniqueId())) throw new IllegalArgumentException("You cannot pay yourself.");
long source = balance(from, currency);
if (source < amount) throw new IllegalArgumentException("Insufficient balance.");
value = Math.addExact(old, amount);
balance(from, currency, source - amount);
} else if (action.equals("give")) value = Math.addExact(old, amount);
else if (action.equals("take")) {
if (old < amount) throw new IllegalArgumentException("That player has insufficient balance.");
value = old - amount;
} else value = amount;
balance(target.getUniqueId(), currency, value); saveBalances();
msg(s, "&a" + action + " completed: " + amount + " " + currencyName(currency) + " for " + target.getName() + ".");
if (action.equals("pay") && target.isOnline()) msg(target.getPlayer(), "&aReceived " + amount + " " + currencyName(currency) + " from " + s.getName() + ".");
}
private void requireCurrency(String id) { if (!currencyIds().contains(id)) throw new IllegalArgumentException("Unknown currency: " + id); }
private YamlConfiguration requireMenu(String id) {
YamlConfiguration menu = menus.get(id);
if (menu == null) throw new IllegalArgumentException("Unknown menu: " + id);
return menu;
}
private void admin(CommandSender s, String[] a) {
if (a.length < 2) throw new IllegalArgumentException("Usage: /rcshop <menu|item|currency> <action>");
String type = normalize(a[0]), action = normalize(a[1]);
if (type.equals("menu")) menuCommand(s, action, a);
else if (type.equals("currency")) currencyCommand(s, action, a);
else if (type.equals("item")) itemCommand(s, action, a);
else throw new IllegalArgumentException("Unknown management category.");
}
private void menuCommand(CommandSender s, String action, String[] a) {
if (action.equals("list")) { msg(s, "&eMenus: " + String.join(", ", menus.keySet())); return; }
if (action.equals("create")) {
if (!allowed(s, "recoinshop.menu.create")) return;
if (a.length != 5 || !a[3].equalsIgnoreCase("slot") || !a[2].matches("[1-6][a-zA-Z0-9_-]{1,64}")) throw new IllegalArgumentException("Usage: /rcshop menu create <rows><menu_name> slot <slot>");
int rows = a[2].charAt(0) - '0'; String id = normalize(a[2].substring(1)); int position = slot(a[4]);
if (menus.containsKey(id)) throw new IllegalArgumentException("Menu already exists.");
ensureMenuSlot(position, null);
YamlConfiguration menu = new YamlConfiguration();
menu.set("title", "&6" + id); menu.set("rows", rows); menu.set("slot", position); menu.set("icon", "CHEST");
menus.put(id, menu); saveMenu(id); msg(s, "&aCreated menu " + id + "."); return;
}
if (a.length < 3) throw new IllegalArgumentException("Specify a menu name.");
String id = normalize(a[2]); YamlConfiguration menu = requireMenu(id);
if (action.equals("open")) {
if (!(s instanceof Player)) throw new IllegalArgumentException("Only players can open menus.");
openMenu((Player)s, id, 0); return;
}
if (action.equals("delete")) {
if (!allowed(s, "recoinshop.menu.delete")) return;
if (a.length != 3) throw new IllegalArgumentException("Usage: /rcshop menu delete <menu>");
if (!new File(menuDir, id + ".yml").delete()) throw new IllegalStateException("Could not delete menu " + id);
menus.remove(id); msg(s, "&aDeleted menu " + id + "."); return;
}