Files
src
build.gradle
settings.gradle
Code
38 2,917
src/main/java/com/kodari/crates/CratesPlugin.java
package com.kodari.crates;
import com.cryptomorin.xseries.XSound;
import com.cryptomorin.xseries.particles.XParticle;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Particle;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;
import java.util.logging.Level;
/** Main entry point and orchestration layer for crate menus and reward delivery. */
public final class CratesPlugin extends JavaPlugin {
private record OpenSession(Crate crate, Crate.Reward reward, Location block, KeyManager.Consumption consumption) { }
private File configFile;
private File langFile;
private YamlConfiguration config;
private YamlConfiguration lang;
private DataStore dataStore;
private CrateManager crateManager;
private KeyManager keyManager;
private final Map<UUID, OpenSession> sessions = new HashMap<>();
private final Map<UUID, Long> cooldowns = new HashMap<>();
private final Map<UUID, Long> previewCooldowns = new HashMap<>();
private final Map<UUID, BukkitTask> rollingTasks = new HashMap<>();
@Override
public void onEnable() {
installDefaultsOnce();
mergeDefaultCrates();
loadSettings();
dataStore = new DataStore(this);
crateManager = new CrateManager(this);
crateManager.load();
keyManager = new KeyManager(this);
CratesCommand command = new CratesCommand(this);
getCommand("dc").setExecutor(command);
getCommand("dc").setTabCompleter(command);
KeysCommand keysCommand = new KeysCommand(this);
getCommand("keys").setExecutor(keysCommand);
getCommand("keys").setTabCompleter(keysCommand);
Bukkit.getPluginManager().registerEvents(new CrateListener(this), this);
getLogger().info("Loaded " + crateManager.all().size() + " crate definition(s).");
}
@Override
public void onDisable() {
for (BukkitTask task : rollingTasks.values()) task.cancel();
rollingTasks.clear();
for (Map.Entry<UUID, OpenSession> entry : new ArrayList<>(sessions.entrySet())) {
OpenSession session = entry.getValue();
if (session.consumption() != null) {
Player player = Bukkit.getPlayer(entry.getKey());
if (player != null) keyManager.refund(player, session.crate().id(), session.consumption());
}
}
sessions.clear();
if (dataStore != null) dataStore.save();
}
private void installDefaultsOnce() {
File folder = getDataFolder();
if (folder.exists()) return;
folder.mkdirs();
try (InputStream indexStream = getResource("defaults/index.txt")) {
if (indexStream == null) throw new IOException("defaults/index.txt is missing from the plugin jar");
List<String> resources = new String(indexStream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8).lines()
.map(String::trim).filter(line -> !line.isEmpty()).toList();
for (String relative : resources) {
File target = new File(folder, relative);
File parent = target.getParentFile();
if (!parent.exists() && !parent.mkdirs()) throw new IOException("Could not create " + parent);
try (InputStream source = getResource("defaults/" + relative)) {
if (source == null) throw new IOException("Missing bundled default defaults/" + relative);
Files.copy(source, target.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
} catch (IOException exception) {
getLogger().log(Level.SEVERE, "Could not install the initial Crates configuration files.", exception);
}
}
private void mergeDefaultCrates() {
try (InputStream indexStream = getResource("defaults/index.txt")) {
if (indexStream == null) return;
for (String relative : new String(indexStream.readAllBytes(), java.nio.charset.StandardCharsets.UTF_8).lines()
.map(String::trim).filter(path -> path.startsWith("crates/") && path.endsWith(".yml")).toList()) {
File target = new File(getDataFolder(), relative);
File parent = target.getParentFile();
if (!parent.exists() && !parent.mkdirs()) continue;
try (InputStream source = getResource("defaults/" + relative)) {
if (source == null) continue;
YamlConfiguration defaults = YamlConfiguration.loadConfiguration(
new java.io.InputStreamReader(source, java.nio.charset.StandardCharsets.UTF_8));
YamlConfiguration current = YamlConfiguration.loadConfiguration(target);
String crateId = defaults.getKeys(false).stream().findFirst().orElse(null);
if (crateId == null) continue;
ConfigurationSection defaultRoot = defaults.getConfigurationSection(crateId);
ConfigurationSection defaultRewards = defaultRoot == null ? null : defaultRoot.getConfigurationSection("rewards");
if (defaultRewards != null) {
YamlConfiguration detachedRewards = new YamlConfiguration();
ConfigurationSection detached = detachedRewards.createSection("rewards");
copySection(defaultRewards, detached);
defaultRewards = detached;
}
defaults.set(crateId + ".rewards", null);
boolean changed = mergeMissing(current, defaults, "");
ConfigurationSection currentRoot = current.getConfigurationSection(crateId);
if (currentRoot != null && defaultRewards != null) {
ConfigurationSection currentRewards = currentRoot.getConfigurationSection("rewards");
if (currentRewards == null) currentRewards = currentRoot.createSection("rewards");
for (String rewardId : defaultRewards.getKeys(false)) {
ConfigurationSection defaultReward = defaultRewards.getConfigurationSection(rewardId);
if (defaultReward == null) continue;
ConfigurationSection matchingReward = currentRewards.getKeys(false).stream()
.map(currentRewards::getConfigurationSection)
.filter(java.util.Objects::nonNull)
.filter(candidate -> sameReward(candidate, defaultReward))
.findFirst().orElse(null);
if (matchingReward != null) {
changed |= mergeMissing(matchingReward, defaultReward, "");
continue;
}
String destinationId = rewardId;
if (currentRewards.contains(destinationId)) {
int nextId = currentRewards.getKeys(false).stream().mapToInt(key -> {
try { return Integer.parseInt(key); } catch (NumberFormatException ignored) { return 0; }
}).max().orElse(0) + 1;
while (currentRewards.contains(String.valueOf(nextId))) nextId++;
destinationId = String.valueOf(nextId);
}
copySection(defaultReward, currentRewards.createSection(destinationId));
changed = true;
}
}
if (changed) current.save(target);
}
}
} catch (IOException exception) {
getLogger().log(Level.WARNING, "Could not merge bundled crate reward defaults.", exception);
}
}
private boolean sameReward(ConfigurationSection first, ConfigurationSection second) {
ConfigurationSection firstIcon = first.getConfigurationSection("icon");
ConfigurationSection secondIcon = second.getConfigurationSection("icon");
String firstMaterial = firstIcon == null ? "" : firstIcon.getString("material", "");
String secondMaterial = secondIcon == null ? "" : secondIcon.getString("material", "");
String firstName = firstIcon == null ? "" : firstIcon.getString("name", firstIcon.getString("displayname", ""));
String secondName = secondIcon == null ? "" : secondIcon.getString("name", secondIcon.getString("displayname", ""));
return firstMaterial.equalsIgnoreCase(secondMaterial) && firstName.equals(secondName);
}
private void copySection(ConfigurationSection source, ConfigurationSection target) {
for (String key : source.getKeys(false)) {
if (source.isConfigurationSection(key)) copySection(source.getConfigurationSection(key), target.createSection(key));
else target.set(key, source.get(key));
}
}
public void reloadPlugin() {
for (UUID id : new ArrayList<>(sessions.keySet())) {
Player player = Bukkit.getPlayer(id);
if (player != null) cancelOpen(player);
}
loadSettings();
dataStore.load();
mergeDefaultCrates();
crateManager.load();
getLogger().info("Reloaded configuration and " + crateManager.all().size() + " crate(s).");
}
private void loadSettings() {
if (!getDataFolder().exists()) getDataFolder().mkdirs();
configFile = new File(getDataFolder(), "config.yml");
langFile = new File(getDataFolder(), "lang.yml");
config = loadAndMerge(configFile, "defaults/config.yml");
lang = loadAndMerge(langFile, "defaults/lang.yml");