diff --git a/build.gradle.kts b/build.gradle.kts index c78b0c6..b71adf7 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,6 +1,6 @@ plugins { java - id("com.gradleup.shadow") version "9.0.0-beta4" + id("com.gradleup.shadow") version "9.2.2" checkstyle } @@ -9,7 +9,7 @@ version = "1.1.0" java { toolchain { - languageVersion.set(JavaLanguageVersion.of(21)) + languageVersion.set(JavaLanguageVersion.of(25)) } } @@ -19,8 +19,10 @@ repositories { } dependencies { - // Paper API для 1.19.4+ - compileOnly("io.papermc.paper:paper-api:1.19.4-R0.1-SNAPSHOT") + // Paper API of the server version the plugin runs on (Paper 26.1.2). + // Compiling against the exact API keeps removed or renamed Bukkit members + // (for example the enchantment constants) from breaking at runtime. + compileOnly("io.papermc.paper:paper-api:26.1.2.build.74-stable") implementation("com.google.code.gson:gson:2.11.0") implementation("com.squareup.okhttp3:okhttp:4.12.0") @@ -31,7 +33,8 @@ dependencies { testImplementation("net.jqwik:jqwik:1.9.2") testImplementation("org.yaml:snakeyaml:2.3") testImplementation("org.xerial:sqlite-jdbc:3.47.2.0") - testCompileOnly("io.papermc.paper:paper-api:1.19.4-R0.1-SNAPSHOT") + testCompileOnly("io.papermc.paper:paper-api:26.1.2.build.74-stable") + testRuntimeOnly("io.papermc.paper:paper-api:26.1.2.build.74-stable") testRuntimeOnly("org.junit.platform:junit-platform-launcher") } @@ -61,12 +64,12 @@ tasks { compileJava { options.encoding = "UTF-8" - options.release.set(21) + options.release.set(25) } compileTestJava { options.encoding = "UTF-8" - options.release.set(21) + options.release.set(25) } } diff --git a/src/main/java/dev/loki/lorep/anticheat/AnticheatService.java b/src/main/java/dev/loki/lorep/anticheat/AnticheatService.java index 1977f77..d28137f 100644 --- a/src/main/java/dev/loki/lorep/anticheat/AnticheatService.java +++ b/src/main/java/dev/loki/lorep/anticheat/AnticheatService.java @@ -109,7 +109,7 @@ public class AnticheatService { } private String renderSummary(String checks, int lookbackHours) { - return config.getMessage("anticheat-summary", "%checks%", checks, "%hours%", String.valueOf(lookbackHours)); + return config.getMessageText("anticheat-summary", "%checks%", checks, "%hours%", String.valueOf(lookbackHours)); } /** diff --git a/src/main/java/dev/loki/lorep/command/ReportStatsCommand.java b/src/main/java/dev/loki/lorep/command/ReportStatsCommand.java index 545cb2a..818babc 100644 --- a/src/main/java/dev/loki/lorep/command/ReportStatsCommand.java +++ b/src/main/java/dev/loki/lorep/command/ReportStatsCommand.java @@ -50,7 +50,7 @@ public class ReportStatsCommand { "%count%", String.valueOf(reportCount))); String lastOnline = target.isOnline() - ? plugin.getConfigManager().getMessage("online-status") + ? plugin.getConfigManager().getMessageText("online-status") : TimeUtil.formatTimeAgo(target.getLastPlayed()); player.sendMessage(plugin.getConfigManager().getMessage("stats-last-online", "%time%", lastOnline)); diff --git a/src/main/java/dev/loki/lorep/config/ConfigManager.java b/src/main/java/dev/loki/lorep/config/ConfigManager.java index 21ae535..a2e1838 100644 --- a/src/main/java/dev/loki/lorep/config/ConfigManager.java +++ b/src/main/java/dev/loki/lorep/config/ConfigManager.java @@ -1,7 +1,8 @@ package dev.loki.lorep.config; import dev.loki.lorep.LorepPlugin; -import org.bukkit.ChatColor; +import dev.loki.lorep.util.TextFormat; +import net.kyori.adventure.text.Component; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; @@ -11,27 +12,33 @@ import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Collections; +import java.util.HashSet; import java.util.List; -import java.util.stream.Collectors; +import java.util.Set; public class ConfigManager { - + + /** Root of the GUI item definitions inside config.yml. */ + private static final String GUI_ITEM_ROOT = "gui.items."; + private final LorepPlugin plugin; + private final Set warned = new HashSet<>(); private FileConfiguration config; private FileConfiguration messages; - + public ConfigManager(LorepPlugin plugin) { this.plugin = plugin; reload(); } - + public void reload() { plugin.saveDefaultConfig(); plugin.reloadConfig(); this.config = plugin.getConfig(); + this.warned.clear(); loadMessages(); } - + private void loadMessages() { File messagesFile = new File(plugin.getDataFolder(), "messages.yml"); if (!messagesFile.exists()) { @@ -39,35 +46,35 @@ public class ConfigManager { } this.messages = YamlConfiguration.loadConfiguration(messagesFile); } - + public String getWebhookUrl() { return config.getString("webhook-url", ""); } - + public String getDatabaseType() { return config.getString("database.type", "sqlite"); } - + public String getSqliteFile() { return config.getString("database.sqlite.file", "reports.db"); } - + public String getPostgresHost() { return config.getString("database.postgresql.host", "localhost"); } - + public int getPostgresPort() { return config.getInt("database.postgresql.port", 5432); } - + public String getPostgresDatabase() { return config.getString("database.postgresql.database", "lorep"); } - + public String getPostgresUsername() { return config.getString("database.postgresql.username", "lorep"); } - + /** PG password: empty {@code password} falls back to one line of {@code password-file} (network convention). */ public String getPostgresPassword() { String direct = config.getString("database.postgresql.password", "password"); @@ -86,32 +93,37 @@ public class ConfigManager { return ""; } } - + public int getPostgresPoolSize() { return config.getInt("database.postgresql.pool-size", 10); } - + public String getServerName() { return config.getString("server-name", "unknown"); } - + public boolean isAnticheatEnabled() { return config.getBoolean("anticheat.enabled", true); } - + public int getAnticheatLookbackHours() { return config.getInt("anticheat.lookback-hours", 72); } - + public int getAnticheatSummaryMaxChecks() { return config.getInt("anticheat.summary-max-checks", 5); } - + public int getAnticheatSummaryMaxFlags() { return config.getInt("anticheat.summary-max-flags", 50); } - - public String getMessage(String key) { + + /** + * Message text of the key, the ampersand colour codes are kept. + * @param key the message key + * @return the raw text + */ + private String rawMessage(String key) { String message = messages.getString(key); if (message == null) { message = config.getString("messages." + key); @@ -119,48 +131,18 @@ public class ConfigManager { if (message == null) { message = "&cMessage not found: " + key; } - return ChatColor.translateAlternateColorCodes('&', message); - } - - public GuiItemConfig getGuiItem(String path) { - ConfigurationSection section = config.getConfigurationSection("gui.items." + path); - if (section == null) { - return null; - } - - Material material = Material.getMaterial(section.getString("material", "STONE").toUpperCase()); - if (material == null) { - material = Material.STONE; - } - - int customModelData = section.contains("custom-model-data") ? section.getInt("custom-model-data") : GuiItemConfig.NO_CUSTOM_MODEL; - - String displayName = section.contains("name") ? ChatColor.translateAlternateColorCodes('&', section.getString("name")) : null; - - List lore = section.contains("lore") - ? section.getStringList("lore").stream() - .map(line -> ChatColor.translateAlternateColorCodes('&', line)) - .collect(Collectors.toList()) - : Collections.emptyList(); - - List slots = section.contains("slots") ? section.getIntegerList("slots") : Collections.emptyList(); - - boolean glowing = section.getBoolean("glowing", false); - - return new GuiItemConfig(material, customModelData, displayName, lore, slots, glowing); + return message; } - public List getItemSlots(String path) { - GuiItemConfig config = getGuiItem(path); - if (config != null && !config.slots().isEmpty()) { - return config.slots(); - } - return Collections.emptyList(); - } - - public String getMessage(String key, String... replacements) { - String message = getMessage(key); - if (replacements == null || replacements.length == 0) { + /** + * Message text with the placeholders applied, still uncoloured. + * @param key the message key + * @param replacements the placeholder pairs + * @return the raw text + */ + public String getMessageText(String key, String... replacements) { + String message = rawMessage(key); + if (replacements == null) { return message; } for (int i = 0; i < replacements.length - 1; i += 2) { @@ -170,4 +152,100 @@ public class ConfigManager { } return message; } -} + + /** + * Coloured message ready to be sent to a player. + * @param key the message key + * @param replacements the placeholder pairs + * @return the component + */ + public Component getMessage(String key, String... replacements) { + return TextFormat.component(getMessageText(key, replacements)); + } + + /** + * Reads a GUI item definition from the config. + * @param path the item path inside {@code gui.items} + * @return the item definition or null when the section is missing + */ + public GuiItemConfig getGuiItem(String path) { + return getGuiItem(path, Material.PAPER); + } + + /** + * Reads a GUI item definition from the config. + * @param path the item path inside {@code gui.items} + * @param defaultMaterial the material used when the config is unusable + * @return the item definition or null when the section is missing + */ + public GuiItemConfig getGuiItem(String path, Material defaultMaterial) { + ConfigurationSection section = config.getConfigurationSection(GUI_ITEM_ROOT + path); + if (section == null) { + warnOnce("missing:" + path, "GUI item '" + GUI_ITEM_ROOT + path + + "' is not configured, the built-in fallback is used"); + return null; + } + + Material material = parseMaterial(path, section.getString("material"), defaultMaterial); + + int customModelData = section.contains("custom-model-data") + ? section.getInt("custom-model-data") : GuiItemConfig.NO_CUSTOM_MODEL; + + String displayName = section.contains("name") ? section.getString("name") : null; + + List lore = section.contains("lore") + ? section.getStringList("lore") + : Collections.emptyList(); + + List slots = section.contains("slots") ? section.getIntegerList("slots") : Collections.emptyList(); + + boolean glowing = section.getBoolean("glowing", false); + + return new GuiItemConfig(material, customModelData, displayName, lore, slots, glowing); + } + + /** + * Resolves the material of a GUI item. + * + *

An unknown material never falls back to a plain stone block silently: + * the problem is logged and the caller supplied material is used + * instead.

+ * @param path the item path inside {@code gui.items} + * @param raw the configured material name + * @param defaultMaterial the material used when the config is unusable + * @return the resolved material + */ + private Material parseMaterial(String path, String raw, Material defaultMaterial) { + Material material = resolveMaterial(raw); + if (material == null) { + warnOnce("bad-material:" + path + ":" + raw, "Unknown material '" + raw + "' for GUI item '" + + GUI_ITEM_ROOT + path + "', " + defaultMaterial + " is used instead"); + return defaultMaterial; + } + return material; + } + + /** + * Resolves a material name of the config. + * + *

Both the plain ({@code PLAYER_HEAD}) and the namespaced + * ({@code minecraft:player_head}) spellings are accepted, the lookup is + * case insensitive. An unknown name never resolves to a plain stone + * block: the caller decides what to use instead.

+ * @param raw the configured material name + * @return the material or null when the name is empty or unknown + */ + static Material resolveMaterial(String raw) { + if (raw == null || raw.isBlank()) { + return null; + } + return Material.matchMaterial(raw.trim()); + } + + /** Logs a configuration problem once per session. */ + private void warnOnce(String key, String message) { + if (warned.add(key)) { + plugin.getLogger().warning(message); + } + } +} \ No newline at end of file diff --git a/src/main/java/dev/loki/lorep/config/GuiItemConfig.java b/src/main/java/dev/loki/lorep/config/GuiItemConfig.java index e92433c..e669e38 100644 --- a/src/main/java/dev/loki/lorep/config/GuiItemConfig.java +++ b/src/main/java/dev/loki/lorep/config/GuiItemConfig.java @@ -1,5 +1,6 @@ package dev.loki.lorep.config; +import dev.loki.lorep.util.TextFormat; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemFlag; @@ -8,6 +9,14 @@ import org.bukkit.inventory.meta.ItemMeta; import java.util.List; +/** + * Configuration driven GUI item: material, custom model data, display name, + * lore, target slots and the glowing flag. + * + *

The display name and the lore are kept as raw config strings (ampersand + * colour codes included) so the GUI code can expand the placeholders before + * the text is turned into Adventure components.

+ */ public record GuiItemConfig( Material material, int customModelData, @@ -18,21 +27,33 @@ public record GuiItemConfig( ) { public static final int NO_CUSTOM_MODEL = -1; + /** Builds the item with the configured name and lore. */ public ItemStack createItem() { + return createItem(displayName, lore); + } + + /** + * Builds the item with the given name and lore. + * + * @param name the display name, may be null + * @param loreLines the lore lines, may be null + * @return the ready to place item + */ + public ItemStack createItem(String name, List loreLines) { ItemStack item = new ItemStack(material); ItemMeta meta = item.getItemMeta(); if (meta != null) { if (customModelData != NO_CUSTOM_MODEL) { meta.setCustomModelData(customModelData); } - if (displayName != null) { - meta.setDisplayName(displayName); + if (name != null) { + meta.displayName(TextFormat.component(name)); } - if (lore != null && !lore.isEmpty()) { - meta.setLore(lore); + if (loreLines != null && !loreLines.isEmpty()) { + meta.lore(TextFormat.lore(loreLines)); } if (glowing) { - meta.addEnchant(Enchantment.DURABILITY, 1, true); + meta.addEnchant(Enchantment.UNBREAKING, 1, true); meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); } item.setItemMeta(meta); diff --git a/src/main/java/dev/loki/lorep/database/PostgreSQLDatabaseManager.java b/src/main/java/dev/loki/lorep/database/PostgreSQLDatabaseManager.java index 4b719cb..33c9ac1 100644 --- a/src/main/java/dev/loki/lorep/database/PostgreSQLDatabaseManager.java +++ b/src/main/java/dev/loki/lorep/database/PostgreSQLDatabaseManager.java @@ -340,7 +340,7 @@ public class PostgreSQLDatabaseManager implements DatabaseManager { try (Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setString(1, playerUuid.toString()); + stmt.setObject(1, playerUuid); stmt.setInt(2, lookbackHours); stmt.setInt(3, limit); try (ResultSet rs = stmt.executeQuery()) { @@ -389,8 +389,12 @@ public class PostgreSQLDatabaseManager implements DatabaseManager { stmt.setInt(3, offset); try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { + UUID playerUuid = parsePlayerUuid(rs.getString("player_uuid")); + if (playerUuid == null) { + continue; + } players.add(new FlaggedPlayer( - UUID.fromString(rs.getString("player_uuid")), + playerUuid, rs.getString("player_name"), rs.getInt("cnt"), toInstant(rs.getTimestamp("last_at")) @@ -413,7 +417,7 @@ public class PostgreSQLDatabaseManager implements DatabaseManager { try (Connection conn = dataSource.getConnection(); PreparedStatement stmt = conn.prepareStatement(sql)) { - stmt.setString(1, playerUuid.toString()); + stmt.setObject(1, playerUuid); stmt.setInt(2, lookbackHours); stmt.setInt(3, limit); try (ResultSet rs = stmt.executeQuery()) { @@ -437,4 +441,25 @@ public class PostgreSQLDatabaseManager implements DatabaseManager { private static Instant toInstant(Timestamp timestamp) { return timestamp != null ? timestamp.toInstant() : Instant.EPOCH; } + + /** + * Parses the uuid of a guard row. + * + *

A malformed value must not break the whole anticheat list, such a row + * is skipped and reported in the log.

+ * + * @param raw the raw uuid + * @return the uuid or null when the value is malformed + */ + private UUID parsePlayerUuid(String raw) { + if (raw == null || raw.isBlank()) { + return null; + } + try { + return UUID.fromString(raw.trim()); + } catch (IllegalArgumentException e) { + logger.warning("Skipping anticheat row with malformed player uuid: " + raw); + return null; + } + } } diff --git a/src/main/java/dev/loki/lorep/database/SQLiteDatabaseManager.java b/src/main/java/dev/loki/lorep/database/SQLiteDatabaseManager.java index 539cb76..2f92495 100644 --- a/src/main/java/dev/loki/lorep/database/SQLiteDatabaseManager.java +++ b/src/main/java/dev/loki/lorep/database/SQLiteDatabaseManager.java @@ -383,8 +383,12 @@ public class SQLiteDatabaseManager implements DatabaseManager { stmt.setInt(3, offset); try (ResultSet rs = stmt.executeQuery()) { while (rs.next()) { + UUID playerUuid = parsePlayerUuid(rs.getString("player_uuid")); + if (playerUuid == null) { + continue; + } players.add(new FlaggedPlayer( - UUID.fromString(rs.getString("player_uuid")), + playerUuid, rs.getString("player_name"), rs.getInt("cnt"), toInstant(rs.getTimestamp("last_at")) @@ -434,4 +438,25 @@ public class SQLiteDatabaseManager implements DatabaseManager { private static Instant toInstant(Timestamp timestamp) { return timestamp != null ? timestamp.toInstant() : Instant.EPOCH; } + + /** + * Parses the uuid of a guard row. + * + *

A malformed value must not break the whole anticheat list, such a row + * is skipped and reported in the log.

+ * + * @param raw the raw uuid + * @return the uuid or null when the value is malformed + */ + private UUID parsePlayerUuid(String raw) { + if (raw == null || raw.isBlank()) { + return null; + } + try { + return UUID.fromString(raw.trim()); + } catch (IllegalArgumentException e) { + logger.warning("Skipping anticheat row with malformed player uuid: " + raw); + return null; + } + } } diff --git a/src/main/java/dev/loki/lorep/gui/AnticheatGui.java b/src/main/java/dev/loki/lorep/gui/AnticheatGui.java index 5c8c127..21e0f30 100644 --- a/src/main/java/dev/loki/lorep/gui/AnticheatGui.java +++ b/src/main/java/dev/loki/lorep/gui/AnticheatGui.java @@ -5,15 +5,17 @@ import dev.loki.lorep.anticheat.AnticheatService; import dev.loki.lorep.config.GuiItemConfig; import dev.loki.lorep.database.DatabaseManager.FlaggedPlayer; import dev.loki.lorep.database.DatabaseManager.ViolationEntry; +import dev.loki.lorep.gui.item.AnticheatItems; +import dev.loki.lorep.gui.item.EntrySlots; import dev.loki.lorep.util.PaginationUtil; -import dev.loki.lorep.util.TimeUtil; +import dev.loki.lorep.util.TextFormat; +import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.SkullMeta; import java.util.ArrayList; import java.util.HashMap; @@ -29,8 +31,17 @@ import java.util.UUID; public class AnticheatGui implements ActionInventory { public static final int INVENTORY_SIZE = 54; + + /** Slot of the single informational item. */ private static final int INFO_SLOT = 22; + /** Navigation slots of the list view. */ + private static final int SLOT_PREV_PAGE = 45; + private static final int SLOT_BACK = 46; + private static final int SLOT_CLOSE = 47; + private static final int SLOT_PAGE_INFO = 49; + private static final int SLOT_NEXT_PAGE = 53; + private final LorepPlugin plugin; private final int page; private boolean detailView; @@ -43,12 +54,13 @@ public class AnticheatGui implements ActionInventory { this.page = page; } + /** Opens the list of flagged players. */ public void open(Player player) { detailView = false; playerNames.clear(); slotActions.clear(); - String title = plugin.getConfigManager().getMessage("anticheat-list-title", + Component title = plugin.getConfigManager().getMessage("anticheat-list-title", "%page%", String.valueOf(page + 1)); this.inventory = Bukkit.createInventory(this, INVENTORY_SIZE, title); @@ -56,22 +68,25 @@ public class AnticheatGui implements ActionInventory { int pageSize = plugin.getConfig().getInt("gui.reports-per-page", 45); List flagged = service.getFlaggedPlayers(page, pageSize); if (flagged == null) { - placeInfoItem(plugin.getConfigManager().getMessage("anticheat-unavailable")); + placeInfoItem(plugin.getConfigManager().getMessageText("anticheat-unavailable")); player.openInventory(inventory); return; } int totalPlayers = service.getFlaggedPlayerCount(); - GuiItemConfig entryConfig = plugin.getConfigManager().getGuiItem("anticheat-entry"); + GuiItemConfig entryConfig = plugin.getConfigManager().getGuiItem("anticheat-entry", Material.PLAYER_HEAD); + List slots = EntrySlots.resolve(entryConfig, INVENTORY_SIZE); + AnticheatItems items = new AnticheatItems(plugin.getConfigManager()); - for (int i = 0; i < flagged.size(); i++) { + for (int i = 0; i < flagged.size() && i < slots.size(); i++) { FlaggedPlayer entry = flagged.get(i); if (entry.playerUuid() != null) { playerNames.put(entry.playerUuid(), entry.playerName()); } - List slots = entryConfig != null ? entryConfig.slots() : List.of(); - int slot = !slots.isEmpty() && i < slots.size() ? slots.get(i) : i; - inventory.setItem(slot, createEntryItem(entry, entryConfig)); + int reportCount = entry.playerUuid() != null + ? plugin.getDatabaseManager().getReportCount(entry.playerUuid()) : 0; + int slot = slots.get(i); + inventory.setItem(slot, items.entry(entryConfig, entry, reportCount)); slotActions.put(slot, "ac_detail:" + entry.playerUuid()); } @@ -79,246 +94,123 @@ public class AnticheatGui implements ActionInventory { player.openInventory(inventory); } + /** + * Opens the detail view of one flagged player. + * + * @param player the viewer + * @param playerUuid the flagged player + * @param playerName the flagged player name + */ public void openDetail(Player player, UUID playerUuid, String playerName) { detailView = true; slotActions.clear(); String name = playerName != null ? playerName : playerUuid.toString(); - String title = plugin.getConfigManager().getMessage("anticheat-detail-title", "%player_name%", name); + Component title = plugin.getConfigManager().getMessage("anticheat-detail-title", "%player_name%", name); this.inventory = Bukkit.createInventory(this, INVENTORY_SIZE, title); AnticheatService service = plugin.getAnticheatService(); if (!service.isAvailable()) { - placeInfoItem(plugin.getConfigManager().getMessage("anticheat-unavailable")); + placeInfoItem(plugin.getConfigManager().getMessageText("anticheat-unavailable")); player.openInventory(inventory); return; } List violations = service.getRecentViolations(playerUuid); if (violations.isEmpty()) { - placeInfoItem(plugin.getConfigManager().getMessage("anticheat-detail-empty")); + placeInfoItem(plugin.getConfigManager().getMessageText("anticheat-detail-empty")); } else { placeDetailItem(playerUuid, name, violations); } - placeConfigItem("anticheat-tab", 45, "back"); - placeConfigItem("close", 47, "close"); - placeConfigItem("anticheat-reports", 49, "open-reports"); + placeConfigItem("anticheat-tab", SLOT_BACK, "back"); + placeConfigItem("close", SLOT_CLOSE, "close"); + placeConfigItem("anticheat-reports", SLOT_PAGE_INFO, "open-reports"); player.openInventory(inventory); } + /** Places the navigation buttons of the list view. */ private void addNavigation(int totalPages, int totalPlayers) { if (page > 0) { - placeConfigItem("prev-page", 45, "prev_page"); + placeConfigItem("prev-page", SLOT_PREV_PAGE, "prev_page"); } - placeConfigItem("anticheat-tab", 46, "back"); - placeConfigItem("close", 47, "close"); + placeConfigItem("anticheat-tab", SLOT_BACK, "back"); + placeConfigItem("close", SLOT_CLOSE, "close"); placePageInfo(totalPages, totalPlayers); if (page < totalPages - 1) { - placeConfigItem("next-page", 53, "next_page"); + placeConfigItem("next-page", SLOT_NEXT_PAGE, "next_page"); } } + /** Places a config driven button, using the config slots when there are any. */ private void placeConfigItem(String configPath, int defaultSlot, String action) { GuiItemConfig config = plugin.getConfigManager().getGuiItem(configPath); if (config == null) { return; } + placeItem(config.slots(), defaultSlot, config.createItem(), action); + } - List slots = config.slots(); - ItemStack item = config.createItem(); - if (slots.isEmpty()) { - inventory.setItem(defaultSlot, item); - slotActions.put(defaultSlot, action); - } else { - for (int slot : slots) { - inventory.setItem(slot, item); + /** Places an item into the configured slots or into the default slot. */ + private void placeItem(List slots, int defaultSlot, ItemStack item, String action) { + List targets = slots.isEmpty() ? List.of(defaultSlot) : slots; + for (int slot : targets) { + inventory.setItem(slot, item); + if (action != null) { slotActions.put(slot, action); } } } + /** Places the page counter of the list view. */ private void placePageInfo(int totalPages, int totalPlayers) { GuiItemConfig config = plugin.getConfigManager().getGuiItem("anticheat-page-info"); if (config == null) { return; } - ItemStack item = config.createItem(); - ItemMeta meta = item.getItemMeta(); - if (meta != null) { - meta.setDisplayName(replacePagePlaceholders(meta.getDisplayName(), totalPages, totalPlayers)); - if (meta.getLore() != null) { - List lore = new ArrayList<>(); - for (String line : meta.getLore()) { - lore.add(replacePagePlaceholders(line, totalPages, totalPlayers)); - } - meta.setLore(lore); - } - item.setItemMeta(meta); - } - - List slots = config.slots(); - if (slots.isEmpty()) { - inventory.setItem(49, item); - } else { - for (int slot : slots) { - inventory.setItem(slot, item); - } + String name = replacePagePlaceholders(config.displayName(), totalPages, totalPlayers); + List lore = new ArrayList<>(); + for (String line : config.lore()) { + lore.add(replacePagePlaceholders(line, totalPages, totalPlayers)); } + placeItem(config.slots(), SLOT_PAGE_INFO, config.createItem(name, lore), null); } + /** Places the detail item of one flagged player. */ private void placeDetailItem(UUID playerUuid, String name, List violations) { - GuiItemConfig config = plugin.getConfigManager().getGuiItem("anticheat-detail"); + GuiItemConfig config = plugin.getConfigManager().getGuiItem("anticheat-detail", Material.PLAYER_HEAD); int reportCount = plugin.getDatabaseManager().getReportCount(playerUuid); - ItemStack item; - if (config == null) { - item = createFallbackHead(playerUuid, name, buildFallbackDetailLore(violations, reportCount)); - } else { - item = config.createItem(); - if (item.getItemMeta() instanceof SkullMeta skullMeta) { - skullMeta.setOwningPlayer(Bukkit.getOfflinePlayer(playerUuid)); - item.setItemMeta(skullMeta); - } - ItemMeta meta = item.getItemMeta(); - if (meta != null) { - meta.setDisplayName(replaceStatic(meta.getDisplayName(), name, reportCount)); - if (meta.getLore() != null) { - meta.setLore(buildDetailLore(meta.getLore(), violations, name, reportCount)); - } - item.setItemMeta(meta); - } - } + AnticheatItems items = new AnticheatItems(plugin.getConfigManager()); + ItemStack item = items.detail(config, playerUuid, name, violations, reportCount); List slots = config != null ? config.slots() : List.of(); inventory.setItem(slots.isEmpty() ? INFO_SLOT : slots.get(0), item); } - /** Expands config lore lines containing %check% into one line per violation. */ - private List buildDetailLore(List configLore, List violations, - String name, int reportCount) { - List lore = new ArrayList<>(); - for (String line : configLore) { - if (line.contains("%check%")) { - for (ViolationEntry violation : violations) { - lore.add(replaceViolation(line, violation, name, reportCount)); - } - } else { - lore.add(replaceStatic(line, name, reportCount)); - } - } - return lore; - } - - private ItemStack createEntryItem(FlaggedPlayer entry, GuiItemConfig config) { - int reportCount = entry.playerUuid() != null ? plugin.getDatabaseManager().getReportCount(entry.playerUuid()) : 0; - if (config == null) { - return createFallbackHead(entry.playerUuid(), entry.playerName(), buildFallbackEntryLore(entry, reportCount)); - } - - ItemStack item = config.createItem(); - if (item.getItemMeta() instanceof SkullMeta skullMeta && entry.playerUuid() != null) { - skullMeta.setOwningPlayer(Bukkit.getOfflinePlayer(entry.playerUuid())); - item.setItemMeta(skullMeta); - } - ItemMeta meta = item.getItemMeta(); - if (meta != null) { - meta.setDisplayName(replaceEntryPlaceholders(meta.getDisplayName(), entry, reportCount)); - if (meta.getLore() != null) { - List lore = new ArrayList<>(); - for (String line : meta.getLore()) { - lore.add(replaceEntryPlaceholders(line, entry, reportCount)); - } - meta.setLore(lore); - } - item.setItemMeta(meta); - } - return item; - } - - private String replaceEntryPlaceholders(String text, FlaggedPlayer entry, int reportCount) { - String lastFlag = entry.lastFlagAt() != null ? TimeUtil.formatTimeAgo(entry.lastFlagAt()) : ""; - return text - .replace("%player_name%", entry.playerName() != null ? entry.playerName() : "") - .replace("%flag_count%", String.valueOf(entry.flagCount())) - .replace("%last_flag%", lastFlag) - .replace("%hours%", String.valueOf(plugin.getAnticheatService().getLookbackHours())) - .replace("%report_count%", String.valueOf(reportCount)); - } - - private String replaceViolation(String line, ViolationEntry violation, String name, int reportCount) { - String time = violation.createdAt() != null ? TimeUtil.formatTimeAgo(violation.createdAt()) : ""; - return replaceStatic(line, name, reportCount) - .replace("%check%", nullSafe(violation.checkKey())) - .replace("%detail%", nullSafe(violation.detail())) - .replace("%server%", nullSafe(violation.server())) - .replace("%time%", time); - } - - private String replaceStatic(String text, String name, int reportCount) { - return text - .replace("%player_name%", name) - .replace("%report_count%", String.valueOf(reportCount)) - .replace("%hours%", String.valueOf(plugin.getAnticheatService().getLookbackHours())); - } - + /** Expands the page placeholders of the page counter. */ private String replacePagePlaceholders(String text, int totalPages, int totalPlayers) { + if (text == null) { + return null; + } return text .replace("%page%", String.valueOf(page + 1)) .replace("%total%", String.valueOf(Math.max(1, totalPages))) .replace("%total_players%", String.valueOf(totalPlayers)); } + /** Places the informational item used when there is nothing to show. */ private void placeInfoItem(String text) { ItemStack item = new ItemStack(Material.PAPER); ItemMeta meta = item.getItemMeta(); if (meta != null) { - meta.setDisplayName(text); + meta.displayName(TextFormat.component(text)); item.setItemMeta(meta); } inventory.setItem(INFO_SLOT, item); } - private ItemStack createFallbackHead(UUID owner, String name, List lore) { - ItemStack head = new ItemStack(Material.PLAYER_HEAD); - SkullMeta meta = (SkullMeta) head.getItemMeta(); - if (meta != null) { - if (owner != null) { - meta.setOwningPlayer(Bukkit.getOfflinePlayer(owner)); - } - meta.setDisplayName("§c" + name); - meta.setLore(lore); - head.setItemMeta(meta); - } - return head; - } - - private List buildFallbackEntryLore(FlaggedPlayer entry, int reportCount) { - String lastFlag = entry.lastFlagAt() != null ? TimeUtil.formatTimeAgo(entry.lastFlagAt()) : ""; - List lore = new ArrayList<>(); - lore.add("§7"); - lore.add("§eFlags: §c" + entry.flagCount()); - lore.add("§eLast flag: §f" + lastFlag); - lore.add("§eReports: §c" + reportCount); - return lore; - } - - private List buildFallbackDetailLore(List violations, int reportCount) { - List lore = new ArrayList<>(); - lore.add("§7"); - lore.add("§eReports: §c" + reportCount); - for (ViolationEntry violation : violations) { - String time = violation.createdAt() != null ? TimeUtil.formatTimeAgo(violation.createdAt()) : ""; - lore.add("§8- §f" + nullSafe(violation.checkKey()) + " §7(" + nullSafe(violation.server()) + ", " + time + ")"); - } - return lore; - } - - private static String nullSafe(String value) { - return value != null ? value : ""; - } - /** @return the name recorded for the player when the list view was rendered. */ public String getPlayerName(UUID playerUuid) { return playerNames.get(playerUuid); diff --git a/src/main/java/dev/loki/lorep/gui/ReportGui.java b/src/main/java/dev/loki/lorep/gui/ReportGui.java index 7917fad..e14760d 100644 --- a/src/main/java/dev/loki/lorep/gui/ReportGui.java +++ b/src/main/java/dev/loki/lorep/gui/ReportGui.java @@ -3,28 +3,42 @@ package dev.loki.lorep.gui; import dev.loki.lorep.LorepPlugin; import dev.loki.lorep.config.GuiItemConfig; import dev.loki.lorep.database.Report; +import dev.loki.lorep.gui.item.EntrySlots; +import dev.loki.lorep.gui.item.ReportItems; import dev.loki.lorep.util.PaginationUtil; -import dev.loki.lorep.util.TimeUtil; +import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.Material; -import org.bukkit.OfflinePlayer; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.SkullMeta; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +/** + * Report list GUI: paginated list of reports, the detail view of a single + * report and the navigation into the anticheat tab. + */ public class ReportGui implements ActionInventory { public static final int INVENTORY_SIZE = 54; + /** Slot of the report item in the detail view. */ + private static final int INFO_SLOT = 22; + + /** Navigation slots of the list view. */ + private static final int SLOT_PREV_PAGE = 45; + private static final int SLOT_ANTICHEAT_TAB = 46; + private static final int SLOT_CLOSE = 47; + private static final int SLOT_PAGE_INFO = 49; + private static final int SLOT_NEXT_PAGE = 53; + final int page; boolean detailView; Report currentReport; @@ -40,12 +54,13 @@ public class ReportGui implements ActionInventory { this.currentReport = null; } + /** Opens the list of reports. */ public void open(Player player) { detailView = false; currentReport = null; slotActions.clear(); - String title = plugin.getConfigManager().getMessage("gui-title", + Component title = plugin.getConfigManager().getMessage("gui-title", "%page%", String.valueOf(page + 1)); this.inventory = Bukkit.createInventory(this, INVENTORY_SIZE, title); @@ -54,287 +69,145 @@ public class ReportGui implements ActionInventory { int totalReports = plugin.getDatabaseManager().getTotalReportCount(); int totalPages = PaginationUtil.calculateTotalPages(totalReports, pageSize); - GuiItemConfig entryConfig = plugin.getConfigManager().getGuiItem("report-entry"); + GuiItemConfig entryConfig = plugin.getConfigManager().getGuiItem("report-entry", Material.PLAYER_HEAD); + List slots = EntrySlots.resolve(entryConfig, INVENTORY_SIZE); + ReportItems items = new ReportItems(plugin.getConfigManager()); - for (int i = 0; i < reports.size(); i++) { + for (int i = 0; i < reports.size() && i < slots.size(); i++) { Report report = reports.get(i); int targetReportCount = plugin.getDatabaseManager().getReportCount(report.targetUuid()); - - ItemStack item; - if (entryConfig != null) { - item = entryConfig.createItem(); - if (item.getItemMeta() instanceof SkullMeta skullMeta) { - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(report.targetUuid()); - skullMeta.setOwningPlayer(offlinePlayer); - item.setItemMeta(skullMeta); - } - ItemMeta meta = item.getItemMeta(); - if (meta != null) { - meta.setDisplayName(replacePlaceholders(meta.getDisplayName(), report, targetReportCount)); - if (meta.getLore() != null) { - List lore = meta.getLore(); - List newLore = new ArrayList<>(); - for (String line : lore) { - newLore.add(replacePlaceholders(line, report, targetReportCount)); - } - meta.setLore(newLore); - } - item.setItemMeta(meta); - } - } else { - item = createFallbackReportItem(report, targetReportCount); - } - - List slots = entryConfig != null ? entryConfig.slots() : List.of(); - if (!slots.isEmpty() && i < slots.size()) { - int slot = slots.get(i); - inventory.setItem(slot, item); - slotActions.put(slot, "report_detail:" + report.id()); - } else { - inventory.setItem(i, item); - slotActions.put(i, "report_detail:" + report.id()); - } + int slot = slots.get(i); + inventory.setItem(slot, items.entry(entryConfig, report, targetReportCount)); + slotActions.put(slot, "report_detail:" + report.id()); } addNavigation(totalReports, totalPages); player.openInventory(inventory); } + /** + * Opens the detail view of one report. + * + * @param player the viewer + * @param report the report to show + */ public void openDetail(Player player, Report report) { detailView = true; currentReport = report; slotActions.clear(); - String title = plugin.getConfigManager().getMessage("gui-title-detail", "%id%", String.valueOf(report.id())); + Component title = plugin.getConfigManager().getMessage("gui-title-detail", "%id%", String.valueOf(report.id())); this.inventory = Bukkit.createInventory(this, INVENTORY_SIZE, title); int targetReportCount = plugin.getDatabaseManager().getReportCount(report.targetUuid()); + GuiItemConfig entryConfig = plugin.getConfigManager().getGuiItem("report-entry", Material.PLAYER_HEAD); + ReportItems items = new ReportItems(plugin.getConfigManager()); + inventory.setItem(INFO_SLOT, items.detail(entryConfig, report, targetReportCount)); - GuiItemConfig entryConfig = plugin.getConfigManager().getGuiItem("report-entry"); - ItemStack item; - if (entryConfig != null) { - item = entryConfig.createItem(); - if (item.getItemMeta() instanceof SkullMeta skullMeta) { - skullMeta.setOwningPlayer(Bukkit.getOfflinePlayer(report.targetUuid())); - item.setItemMeta(skullMeta); - } - ItemMeta meta = item.getItemMeta(); - if (meta != null) { - meta.setDisplayName(replacePlaceholders(meta.getDisplayName(), report, targetReportCount)); - if (meta.getLore() != null) { - List lore = meta.getLore(); - List newLore = new ArrayList<>(); - for (String line : lore) { - newLore.add(replacePlaceholders(line, report, targetReportCount)); - } - meta.setLore(newLore); - } - item.setItemMeta(meta); - } - } else { - item = createFallbackReportItem(report, targetReportCount); - } - inventory.setItem(22, item); - - placeDetailButton("teleport", "teleport"); + placeConfigItem("teleport", "teleport", 20); if (report.imageUrl() != null && !report.imageUrl().isEmpty()) { - placeDetailButton("screenshot", "screenshot"); + placeConfigItem("screenshot", "screenshot", 24); } String currentStatus = report.status() != null ? report.status() : "PENDING"; - placeStatusButton("status-pending", "status_set:PENDING", "PENDING".equals(currentStatus)); - placeStatusButton("status-reviewing", "status_set:REVIEWING", "REVIEWING".equals(currentStatus)); - placeStatusButton("status-resolved", "status_set:RESOLVED", "RESOLVED".equals(currentStatus)); - placeStatusButton("status-dismissed", "status_set:DISMISSED", "DISMISSED".equals(currentStatus)); - - GuiItemConfig closeConfig = plugin.getConfigManager().getGuiItem("close"); - if (closeConfig != null) { - List slots = closeConfig.slots(); - ItemStack closeItem = closeConfig.createItem(); - if (slots.isEmpty()) { - inventory.setItem(49, closeItem); - slotActions.put(49, "close"); - } else { - for (int slot : slots) { - inventory.setItem(slot, closeItem); - slotActions.put(slot, "close"); - } - } - } + placeStatusButton("status-pending", "status_set:PENDING", "PENDING".equals(currentStatus), 29); + placeStatusButton("status-reviewing", "status_set:REVIEWING", "REVIEWING".equals(currentStatus), 30); + placeStatusButton("status-resolved", "status_set:RESOLVED", "RESOLVED".equals(currentStatus), 31); + placeStatusButton("status-dismissed", "status_set:DISMISSED", "DISMISSED".equals(currentStatus), 32); + placeConfigItem("close", "close", SLOT_CLOSE); player.openInventory(inventory); } - private void placeDetailButton(String configPath, String action) { + /** + * Places a config driven button. + * + * @param configPath the item path inside {@code gui.items} + * @param action the click action of the button + * @param defaultSlot the slot used when the config declares none + */ + private void placeConfigItem(String configPath, String action, int defaultSlot) { GuiItemConfig config = plugin.getConfigManager().getGuiItem(configPath); if (config == null) { return; } - - List slots = config.slots(); - ItemStack button = config.createItem(); - if (slots.isEmpty()) { - int slot = switch (action) { - case "teleport" -> 20; - case "screenshot" -> 24; - default -> 22; - }; - inventory.setItem(slot, button); - slotActions.put(slot, action); - } else { - for (int slot : slots) { - inventory.setItem(slot, button); - slotActions.put(slot, action); - } - } + placeItem(config.slots(), defaultSlot, config.createItem(), action); } - private void placeStatusButton(String configPath, String action, boolean active) { + /** + * Places a status button of the detail view. + * + * @param configPath the item path inside {@code gui.items} + * @param action the click action of the button + * @param active whether the status is the current one + * @param defaultSlot the slot used when the config declares none + */ + private void placeStatusButton(String configPath, String action, boolean active, int defaultSlot) { GuiItemConfig config = plugin.getConfigManager().getGuiItem(configPath); if (config == null) { return; } - List slots = config.slots(); - ItemStack button = config.createItem(); + ItemStack item = config.createItem(); if (active) { - button.addUnsafeEnchantment(Enchantment.ARROW_DAMAGE, 1); - ItemMeta meta = button.getItemMeta(); - if (meta != null) { - meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - button.setItemMeta(meta); - } - } - if (slots.isEmpty()) { - int slot = switch (action) { - case "status_set:PENDING" -> 29; - case "status_set:REVIEWING" -> 30; - case "status_set:RESOLVED" -> 31; - case "status_set:DISMISSED" -> 32; - default -> 29; - }; - inventory.setItem(slot, button); - slotActions.put(slot, action); - } else { - for (int slot : slots) { - inventory.setItem(slot, button); - slotActions.put(slot, action); - } - } - } - - private void addNavigation(int totalReports, int totalPages) { - if (page > 0) { - GuiItemConfig prevConfig = plugin.getConfigManager().getGuiItem("prev-page"); - if (prevConfig != null) { - List slots = prevConfig.slots(); - ItemStack item = prevConfig.createItem(); - if (slots.isEmpty()) { - inventory.setItem(45, item); - slotActions.put(45, "prev_page"); - } else { - for (int slot : slots) { - inventory.setItem(slot, item); - slotActions.put(slot, "prev_page"); - } - } - } - } - - GuiItemConfig pageInfoConfig = plugin.getConfigManager().getGuiItem("page-info"); - if (pageInfoConfig != null) { - List slots = pageInfoConfig.slots(); - ItemStack item = pageInfoConfig.createItem(); + item.addUnsafeEnchantment(Enchantment.POWER, 1); ItemMeta meta = item.getItemMeta(); if (meta != null) { - meta.setDisplayName(meta.getDisplayName() - .replace("%page%", String.valueOf(page + 1)) - .replace("%total%", String.valueOf(Math.max(1, totalPages))) - .replace("%total_reports%", String.valueOf(totalReports))); - if (meta.getLore() != null) { - List lore = meta.getLore(); - List newLore = new ArrayList<>(); - for (String line : lore) { - newLore.add(line - .replace("%page%", String.valueOf(page + 1)) - .replace("%total%", String.valueOf(Math.max(1, totalPages))) - .replace("%total_reports%", String.valueOf(totalReports))); - } - meta.setLore(newLore); - } + meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); item.setItemMeta(meta); } - if (slots.isEmpty()) { - inventory.setItem(49, item); - } else { - for (int slot : slots) { - inventory.setItem(slot, item); - } + } + placeItem(config.slots(), defaultSlot, item, action); + } + + /** Places an item into the configured slots or into the default slot. */ + private void placeItem(List slots, int defaultSlot, ItemStack item, String action) { + List targets = slots.isEmpty() ? List.of(defaultSlot) : slots; + for (int slot : targets) { + inventory.setItem(slot, item); + if (action != null) { + slotActions.put(slot, action); } } + } + /** Places the navigation buttons of the list view. */ + private void addNavigation(int totalReports, int totalPages) { + if (page > 0) { + placeConfigItem("prev-page", "prev_page", SLOT_PREV_PAGE); + } + placeConfigItem("anticheat-tab", "anticheat_open", SLOT_ANTICHEAT_TAB); + placeConfigItem("close", "close", SLOT_CLOSE); + placePageInfo(totalReports, totalPages); if (page < totalPages - 1) { - GuiItemConfig nextConfig = plugin.getConfigManager().getGuiItem("next-page"); - if (nextConfig != null) { - List slots = nextConfig.slots(); - ItemStack item = nextConfig.createItem(); - if (slots.isEmpty()) { - inventory.setItem(53, item); - slotActions.put(53, "next_page"); - } else { - for (int slot : slots) { - inventory.setItem(slot, item); - slotActions.put(slot, "next_page"); - } - } - } - } - - GuiItemConfig closeConfig = plugin.getConfigManager().getGuiItem("close"); - if (closeConfig != null) { - List slots = closeConfig.slots(); - ItemStack item = closeConfig.createItem(); - if (slots.isEmpty()) { - inventory.setItem(47, item); - slotActions.put(47, "close"); - } else { - for (int slot : slots) { - inventory.setItem(slot, item); - slotActions.put(slot, "close"); - } - } + placeConfigItem("next-page", "next_page", SLOT_NEXT_PAGE); } } - private String replacePlaceholders(String text, Report report, int reportCount) { - String statusDisplay = plugin.getConfigManager().getMessage("status-" + report.status().toLowerCase()); + /** Places the page counter of the list view. */ + private void placePageInfo(int totalReports, int totalPages) { + GuiItemConfig config = plugin.getConfigManager().getGuiItem("page-info"); + if (config == null) { + return; + } + + String name = replacePagePlaceholders(config.displayName(), totalReports, totalPages); + List lore = new ArrayList<>(); + for (String line : config.lore()) { + lore.add(replacePagePlaceholders(line, totalReports, totalPages)); + } + placeItem(config.slots(), SLOT_PAGE_INFO, config.createItem(name, lore), null); + } + + /** Expands the page placeholders of the page counter. */ + private String replacePagePlaceholders(String text, int totalReports, int totalPages) { + if (text == null) { + return null; + } return text - .replace("%target_name%", report.targetName() != null ? report.targetName() : "") - .replace("%reporter_name%", report.reporterName() != null ? report.reporterName() : "") - .replace("%reason%", report.reason() != null ? report.reason() : "") - .replace("%time%", TimeUtil.formatTimeAgo(report.createdAt())) - .replace("%status%", statusDisplay) - .replace("%server%", report.serverName() != null ? report.serverName() : Report.UNKNOWN_SERVER) - .replace("%report_count%", String.valueOf(reportCount)); - } - - private ItemStack createFallbackReportItem(Report report, int totalReports) { - ItemStack head = new ItemStack(Material.PLAYER_HEAD); - SkullMeta meta = (SkullMeta) head.getItemMeta(); - if (meta != null) { - meta.setOwningPlayer(Bukkit.getOfflinePlayer(report.targetUuid())); - meta.setDisplayName("§c" + report.targetName()); - List lore = new ArrayList<>(); - lore.add("§7"); - lore.add("§eBy: §f" + report.reporterName()); - lore.add("§eReason: §f" + report.reason()); - lore.add("§eTime: §f" + TimeUtil.formatTimeAgo(report.createdAt())); - lore.add("§7"); - lore.add("§eReports: §c" + totalReports); - meta.setLore(lore); - head.setItemMeta(meta); - } - return head; + .replace("%page%", String.valueOf(page + 1)) + .replace("%total%", String.valueOf(Math.max(1, totalPages))) + .replace("%total_reports%", String.valueOf(totalReports)); } public int getPage() { diff --git a/src/main/java/dev/loki/lorep/gui/item/AnticheatItems.java b/src/main/java/dev/loki/lorep/gui/item/AnticheatItems.java new file mode 100644 index 0000000..f940279 --- /dev/null +++ b/src/main/java/dev/loki/lorep/gui/item/AnticheatItems.java @@ -0,0 +1,169 @@ +package dev.loki.lorep.gui.item; + +import dev.loki.lorep.config.ConfigManager; +import dev.loki.lorep.config.GuiItemConfig; +import dev.loki.lorep.database.DatabaseManager.FlaggedPlayer; +import dev.loki.lorep.database.DatabaseManager.ViolationEntry; +import dev.loki.lorep.util.TimeUtil; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +/** + * Builds the items of the anticheat tab: one head per flagged player in the + * list view and the detailed head with the recent flags. + * + *

Every text comes from the config. When the config section is missing the + * built-in fallback template is used, so a half configured server still shows + * a readable head instead of an anonymous block.

+ */ +public final class AnticheatItems { + + private final ConfigManager configManager; + + public AnticheatItems(ConfigManager configManager) { + this.configManager = configManager; + } + + /** + * Builds the list entry of one flagged player. + * + * @param config the item template from the config, may be null + * @param flagged the flagged player + * @param reportCount the number of reports against the player + * @return the head item + */ + public ItemStack entry(GuiItemConfig config, FlaggedPlayer flagged, int reportCount) { + GuiItemConfig template = config != null ? config : fallbackEntryTemplate(); + String name = applyEntryPlaceholders(template.displayName(), flagged, reportCount); + List lore = applyEntryPlaceholders(template.lore(), flagged, reportCount); + + ItemStack item = template.createItem(name, lore); + PlayerHeads.applyProfile(item, flagged.playerUuid(), flagged.playerName()); + return item; + } + + /** + * Builds the detail item of one flagged player. + * + * @param config the item template from the config, may be null + * @param playerUuid the player uuid + * @param playerName the player name + * @param violations the recent flags + * @param reportCount the number of reports against the player + * @return the head item + */ + public ItemStack detail(GuiItemConfig config, UUID playerUuid, String playerName, + List violations, int reportCount) { + GuiItemConfig template = config != null ? config : fallbackDetailTemplate(); + String name = applyDetailPlaceholders(template.displayName(), playerName, reportCount); + List lore = buildDetailLore(template.lore(), violations, playerName, reportCount); + + ItemStack item = template.createItem(name, lore); + PlayerHeads.applyProfile(item, playerUuid, playerName); + return item; + } + + /** Fallback template of the list entry. */ + private GuiItemConfig fallbackEntryTemplate() { + return new GuiItemConfig( + Material.PLAYER_HEAD, + GuiItemConfig.NO_CUSTOM_MODEL, + configManager.getMessageText("anticheat-entry-name"), + List.of( + configManager.getMessageText("anticheat-entry-flags"), + configManager.getMessageText("anticheat-entry-last-flag"), + configManager.getMessageText("anticheat-entry-reports") + ), + List.of(), + false + ); + } + + /** Fallback template of the detail item. */ + private GuiItemConfig fallbackDetailTemplate() { + return new GuiItemConfig( + Material.PLAYER_HEAD, + GuiItemConfig.NO_CUSTOM_MODEL, + configManager.getMessageText("anticheat-detail-name"), + List.of( + configManager.getMessageText("anticheat-detail-reports"), + configManager.getMessageText("anticheat-detail-flag") + ), + List.of(), + false + ); + } + + /** Expands the placeholders of one list entry. */ + private String applyEntryPlaceholders(String text, FlaggedPlayer flagged, int reportCount) { + if (text == null) { + return null; + } + String lastFlag = flagged.lastFlagAt() != null ? TimeUtil.formatTimeAgo(flagged.lastFlagAt()) : ""; + return text + .replace("%player_name%", nullSafe(flagged.playerName())) + .replace("%flag_count%", String.valueOf(flagged.flagCount())) + .replace("%last_flag%", lastFlag) + .replace("%hours%", String.valueOf(configManager.getAnticheatLookbackHours())) + .replace("%report_count%", String.valueOf(reportCount)); + } + + /** Expands the placeholders of the list entry lore. */ + private List applyEntryPlaceholders(List lore, FlaggedPlayer flagged, int reportCount) { + List lines = new ArrayList<>(); + for (String line : lore) { + lines.add(applyEntryPlaceholders(line, flagged, reportCount)); + } + return lines; + } + + /** Expands the placeholders of the detail item. */ + private String applyDetailPlaceholders(String text, String playerName, int reportCount) { + if (text == null) { + return null; + } + return text + .replace("%player_name%", nullSafe(playerName)) + .replace("%report_count%", String.valueOf(reportCount)) + .replace("%hours%", String.valueOf(configManager.getAnticheatLookbackHours())); + } + + /** + * Expands the detail lore: a line with the {@code %check%} placeholder is + * repeated once per flag. + */ + private List buildDetailLore(List configLore, List violations, + String playerName, int reportCount) { + List lore = new ArrayList<>(); + for (String line : configLore) { + if (line.contains("%check%")) { + for (ViolationEntry violation : violations) { + lore.add(applyViolationPlaceholders(line, violation, playerName, reportCount)); + } + } else { + lore.add(applyDetailPlaceholders(line, playerName, reportCount)); + } + } + return lore; + } + + /** Expands the placeholders of a single flag line. */ + private String applyViolationPlaceholders(String line, ViolationEntry violation, + String playerName, int reportCount) { + String time = violation.createdAt() != null ? TimeUtil.formatTimeAgo(violation.createdAt()) : ""; + return applyDetailPlaceholders(line, playerName, reportCount) + .replace("%check%", nullSafe(violation.checkKey())) + .replace("%detail%", nullSafe(violation.detail())) + .replace("%server%", nullSafe(violation.server())) + .replace("%time%", time); + } + + /** Null safe text. */ + private static String nullSafe(String value) { + return value != null ? value : ""; + } +} diff --git a/src/main/java/dev/loki/lorep/gui/item/EntrySlots.java b/src/main/java/dev/loki/lorep/gui/item/EntrySlots.java new file mode 100644 index 0000000..f3b7a70 --- /dev/null +++ b/src/main/java/dev/loki/lorep/gui/item/EntrySlots.java @@ -0,0 +1,56 @@ +package dev.loki.lorep.gui.item; + +import dev.loki.lorep.config.GuiItemConfig; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +/** + * Slot layout of the paginated entry lists. + * + *

The bottom row of the inventory is reserved for the navigation buttons, + * the entries fill the rows above it. When the config declares its own slots + * for an entry item those slots win, the remaining free slots of the grid + * follow. The grid keeps the entries aligned instead of letting them bleed + * into the navigation row.

+ */ +public final class EntrySlots { + + /** Inventory rows reserved for the navigation buttons. */ + public static final int RESERVED_ROWS = 1; + + /** Inventory columns per row. */ + public static final int COLUMNS = 9; + + private EntrySlots() {} + + /** + * Resolves the slots the entries of a page are placed in. + * + * @param config the entry item config, may be null + * @param inventorySize the size of the inventory in slots + * @return the ordered slot list + */ + public static List resolve(GuiItemConfig config, int inventorySize) { + int rows = Math.max(1, inventorySize / COLUMNS); + int firstEntrySlot = (rows - RESERVED_ROWS) * COLUMNS; + Set used = new LinkedHashSet<>(); + List slots = new ArrayList<>(); + + if (config != null) { + for (int slot : config.slots()) { + if (slot >= 0 && slot < firstEntrySlot && used.add(slot)) { + slots.add(slot); + } + } + } + for (int slot = 0; slot < firstEntrySlot; slot++) { + if (used.add(slot)) { + slots.add(slot); + } + } + return slots; + } +} diff --git a/src/main/java/dev/loki/lorep/gui/item/PlayerHeads.java b/src/main/java/dev/loki/lorep/gui/item/PlayerHeads.java new file mode 100644 index 0000000..43a2d97 --- /dev/null +++ b/src/main/java/dev/loki/lorep/gui/item/PlayerHeads.java @@ -0,0 +1,82 @@ +package dev.loki.lorep.gui.item; + +import com.destroystokyo.paper.profile.PlayerProfile; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; + +import java.util.UUID; + +/** + * Player head helpers. + * + *

A head item without a profile is rendered by the client as a plain block, + * so the profile always carries the player name: the client resolves the skin + * by name and shows a real head.

+ */ +public final class PlayerHeads { + + private PlayerHeads() {} + + /** + * Creates a player head that points at the given player. + * + * @param uuid the player uuid, may be null + * @param playerName the player name, may be null + * @return the head item + */ + public static ItemStack create(UUID uuid, String playerName) { + ItemStack head = new ItemStack(Material.PLAYER_HEAD); + applyProfile(head, uuid, playerName); + return head; + } + + /** + * Points a head item at the given player. + * + * @param item the item to update, may be null + * @param uuid the player uuid, may be null + * @param playerName the player name, may be null + */ + public static void applyProfile(ItemStack item, UUID uuid, String playerName) { + if (item == null || uuid == null || !(item.getItemMeta() instanceof SkullMeta skullMeta)) { + return; + } + String name = resolveName(uuid, playerName); + PlayerProfile profile = name.isEmpty() + ? Bukkit.createProfile(uuid) + : Bukkit.createProfile(uuid, name); + skullMeta.setPlayerProfile(profile); + item.setItemMeta(skullMeta); + } + + /** + * Resolves a usable player name for the profile. + * + * @param uuid the player uuid + * @param playerName the known player name, may be null + * @return the name or an empty string when it is unknown + */ + private static String resolveName(UUID uuid, String playerName) { + if (isValidName(playerName)) { + return playerName; + } + String cached = Bukkit.getOfflinePlayer(uuid).getName(); + return isValidName(cached) ? cached : ""; + } + + /** Checks that the name is a valid Minecraft user name. */ + private static boolean isValidName(String name) { + if (name == null || name.isEmpty() || name.length() > 16) { + return false; + } + for (char character : name.toCharArray()) { + boolean allowed = Character.isLetterOrDigit(character) || character == '_'; + if (!allowed) { + return false; + } + } + return true; + } +} diff --git a/src/main/java/dev/loki/lorep/gui/item/ReportItems.java b/src/main/java/dev/loki/lorep/gui/item/ReportItems.java new file mode 100644 index 0000000..f1e5472 --- /dev/null +++ b/src/main/java/dev/loki/lorep/gui/item/ReportItems.java @@ -0,0 +1,112 @@ +package dev.loki.lorep.gui.item; + +import dev.loki.lorep.config.ConfigManager; +import dev.loki.lorep.config.GuiItemConfig; +import dev.loki.lorep.database.Report; +import dev.loki.lorep.util.TimeUtil; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +/** + * Builds the items of the report tab: one head per report in the list view + * and the detailed head of a single report. + * + *

Every text comes from the config. When the config section is missing the + * built-in fallback template is used, so a half configured server still shows + * a readable head instead of an anonymous block.

+ */ +public final class ReportItems { + + private final ConfigManager configManager; + + public ReportItems(ConfigManager configManager) { + this.configManager = configManager; + } + + /** + * Builds the list entry of one report. + * + * @param config the item template from the config, may be null + * @param report the report + * @param reportCount the number of reports against the reported player + * @return the head item + */ + public ItemStack entry(GuiItemConfig config, Report report, int reportCount) { + GuiItemConfig template = config != null ? config : fallbackTemplate(); + String name = applyPlaceholders(template.displayName(), report, reportCount); + List lore = applyPlaceholders(template.lore(), report, reportCount); + + ItemStack item = template.createItem(name, lore); + PlayerHeads.applyProfile(item, report.targetUuid(), report.targetName()); + return item; + } + + /** + * Builds the detail item of one report. + * + * @param config the item template from the config, may be null + * @param report the report + * @param reportCount the number of reports against the reported player + * @return the head item + */ + public ItemStack detail(GuiItemConfig config, Report report, int reportCount) { + return entry(config, report, reportCount); + } + + /** Fallback template of a report entry. */ + private GuiItemConfig fallbackTemplate() { + return new GuiItemConfig( + Material.PLAYER_HEAD, + GuiItemConfig.NO_CUSTOM_MODEL, + configManager.getMessageText("report-entry-name"), + List.of( + configManager.getMessageText("report-entry-reporter"), + configManager.getMessageText("report-entry-reason"), + configManager.getMessageText("report-entry-time"), + configManager.getMessageText("report-entry-status"), + configManager.getMessageText("report-entry-server"), + configManager.getMessageText("report-entry-reports") + ), + List.of(), + false + ); + } + + /** Expands the placeholders of one report entry. */ + private String applyPlaceholders(String text, Report report, int reportCount) { + if (text == null) { + return null; + } + return text + .replace("%target_name%", nullSafe(report.targetName())) + .replace("%reporter_name%", nullSafe(report.reporterName())) + .replace("%reason%", nullSafe(report.reason())) + .replace("%time%", report.createdAt() != null ? TimeUtil.formatTimeAgo(report.createdAt()) : "") + .replace("%status%", statusDisplay(report)) + .replace("%server%", report.serverName() != null ? report.serverName() : Report.UNKNOWN_SERVER) + .replace("%report_count%", String.valueOf(reportCount)); + } + + /** Expands the placeholders of the report entry lore. */ + private List applyPlaceholders(List lore, Report report, int reportCount) { + List lines = new ArrayList<>(); + for (String line : lore) { + lines.add(applyPlaceholders(line, report, reportCount)); + } + return lines; + } + + /** Coloured status label of a report. */ + private String statusDisplay(Report report) { + String status = report.status() != null ? report.status() : "PENDING"; + return configManager.getMessageText("status-" + status.toLowerCase()); + } + + /** Null safe text. */ + private static String nullSafe(String value) { + return value != null ? value : ""; + } +} diff --git a/src/main/java/dev/loki/lorep/util/MessageUtil.java b/src/main/java/dev/loki/lorep/util/MessageUtil.java index 290097f..9efdd05 100644 --- a/src/main/java/dev/loki/lorep/util/MessageUtil.java +++ b/src/main/java/dev/loki/lorep/util/MessageUtil.java @@ -1,32 +1,73 @@ package dev.loki.lorep.util; -import org.bukkit.ChatColor; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; +/** + * Small helper for the chat messages of the plugin. The colouring is done by + * {@link TextFormat}, the deprecated Bukkit colour API is not used. + */ public class MessageUtil { + private static final Component PREFIX = Component.text() + .append(Component.text("[", NamedTextColor.DARK_GRAY)) + .append(Component.text("lorep", NamedTextColor.RED)) + .append(Component.text("]", NamedTextColor.DARK_GRAY)) + .append(Component.space()) + .build(); + private MessageUtil() {} - private static final String PREFIX = "§8[§clorep§8] §r"; - - public static String colorize(String message) { - return ChatColor.translateAlternateColorCodes('&', message); + /** + * Colours a message. + * + * @param message the raw message + * @return the coloured component + */ + public static Component colorize(String message) { + return TextFormat.component(message); } - + + /** + * Sends a prefixed message. + * + * @param sender the receiver + * @param message the raw message + */ public static void send(CommandSender sender, String message) { - sender.sendMessage(PREFIX + colorize(message)); + sender.sendMessage(PREFIX.append(colorize(message))); } - + + /** + * Sends a message without the prefix. + * + * @param sender the receiver + * @param message the raw message + */ public static void sendRaw(CommandSender sender, String message) { sender.sendMessage(colorize(message)); } - + + /** + * Sends a message without the prefix. + * + * @param player the receiver + * @param message the raw message + */ public static void sendNoPrefix(Player player, String message) { player.sendMessage(colorize(message)); } - - public static String format(String message, String... replacements) { + + /** + * Colours a message and expands the placeholders. + * + * @param message the raw message + * @param replacements the placeholder pairs + * @return the coloured component + */ + public static Component format(String message, String... replacements) { String result = message; for (int i = 0; i < replacements.length - 1; i += 2) { result = result.replace(replacements[i], replacements[i + 1]); diff --git a/src/main/java/dev/loki/lorep/util/TextFormat.java b/src/main/java/dev/loki/lorep/util/TextFormat.java new file mode 100644 index 0000000..2a24a9e --- /dev/null +++ b/src/main/java/dev/loki/lorep/util/TextFormat.java @@ -0,0 +1,168 @@ +package dev.loki.lorep.util; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Converts the ampersand colour codes used inside the config files into + * Adventure components. + * + *

The parser is written by hand on purpose: the deprecated Bukkit colour + * API is not used and MiniMessage tags are never interpreted, so player + * provided text (player names, report reasons) cannot smuggle formatting or + * click actions into a GUI item.

+ */ +public final class TextFormat { + + private static final char CODE_PREFIX = '&'; + private static final char LEGACY_CODE_PREFIX = '§'; + + private static final Map COLORS = new HashMap<>(); + private static final Map DECORATIONS = new HashMap<>(); + + static { + COLORS.put('0', NamedTextColor.BLACK); + COLORS.put('1', NamedTextColor.DARK_BLUE); + COLORS.put('2', NamedTextColor.DARK_GREEN); + COLORS.put('3', NamedTextColor.DARK_AQUA); + COLORS.put('4', NamedTextColor.DARK_RED); + COLORS.put('5', NamedTextColor.DARK_PURPLE); + COLORS.put('6', NamedTextColor.GOLD); + COLORS.put('7', NamedTextColor.GRAY); + COLORS.put('8', NamedTextColor.DARK_GRAY); + COLORS.put('9', NamedTextColor.BLUE); + COLORS.put('a', NamedTextColor.GREEN); + COLORS.put('b', NamedTextColor.AQUA); + COLORS.put('c', NamedTextColor.RED); + COLORS.put('d', NamedTextColor.LIGHT_PURPLE); + COLORS.put('e', NamedTextColor.YELLOW); + COLORS.put('f', NamedTextColor.WHITE); + + DECORATIONS.put('k', TextDecoration.OBFUSCATED); + DECORATIONS.put('l', TextDecoration.BOLD); + DECORATIONS.put('m', TextDecoration.STRIKETHROUGH); + DECORATIONS.put('n', TextDecoration.UNDERLINED); + DECORATIONS.put('o', TextDecoration.ITALIC); + } + + private TextFormat() {} + + /** + * Parses a single config line into a component. + * + * @param text the raw line, may be null + * @return the parsed component, empty for null or blank input + */ + public static Component component(String text) { + if (text == null || text.isEmpty()) { + return Component.empty(); + } + List segments = new ArrayList<>(); + StringBuilder buffer = new StringBuilder(); + NamedTextColor color = null; + Map decorations = new HashMap<>(); + + int index = 0; + while (index < text.length()) { + char current = text.charAt(index); + char code = codeAt(text, index); + if (code != 0) { + flush(segments, buffer, color, decorations); + if (COLORS.containsKey(code)) { + color = COLORS.get(code); + decorations.clear(); + } else if (DECORATIONS.containsKey(code)) { + decorations.put(DECORATIONS.get(code), TextDecoration.State.TRUE); + } else { + color = null; + decorations.clear(); + } + index += 2; + continue; + } + buffer.append(current); + index++; + } + flush(segments, buffer, color, decorations); + return Component.text().append(segments).build(); + } + + /** + * Parses config lore lines into components. + * + * @param lines the raw lines, may be null + * @return the parsed lines, empty for null or empty input + */ + public static List lore(List lines) { + List lore = new ArrayList<>(); + if (lines == null) { + return lore; + } + for (String line : lines) { + lore.add(component(line)); + } + return lore; + } + + /** + * Removes every colour code from a config line. + * + * @param text the raw line, may be null + * @return the plain text + */ + public static String strip(String text) { + if (text == null || text.isEmpty()) { + return ""; + } + StringBuilder plain = new StringBuilder(); + int index = 0; + while (index < text.length()) { + if (codeAt(text, index) != 0) { + index += 2; + continue; + } + plain.append(text.charAt(index)); + index++; + } + return plain.toString(); + } + + /** + * Reads the colour code at the given position. + * + * @return the lower case code character or 0 when there is no code + */ + private static char codeAt(String text, int index) { + if (index + 1 >= text.length()) { + return 0; + } + char prefix = text.charAt(index); + if (prefix != CODE_PREFIX && prefix != LEGACY_CODE_PREFIX) { + return 0; + } + char code = Character.toLowerCase(text.charAt(index + 1)); + boolean known = COLORS.containsKey(code) || DECORATIONS.containsKey(code) || code == 'r'; + return known ? code : 0; + } + + /** Appends the buffered text as a segment with the given style. */ + private static void flush(List segments, StringBuilder buffer, + NamedTextColor color, Map decorations) { + if (buffer.isEmpty()) { + return; + } + TextComponent segment = Component.text(buffer.toString()).color(color); + for (Map.Entry decoration : decorations.entrySet()) { + segment = segment.decoration(decoration.getKey(), decoration.getValue()); + } + segments.add(segment); + buffer.setLength(0); + } +} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml index 0e5a9d3..4d96eb6 100644 --- a/src/main/resources/config.yml +++ b/src/main/resources/config.yml @@ -46,6 +46,9 @@ gui: # GUI item definitions — customize materials, textures, and positions # Set custom-model-data to your resource pack model ID (-1 to disable) # Use slots to make an item span multiple slots (empty = default position) + # The bottom row (slots 45-53) is reserved for the navigation buttons. + # The entries of a list fill the rows above it when no slots are configured. + # Material names accept both spellings: PLAYER_HEAD and minecraft:player_head items: prev-page: material: ARROW @@ -223,3 +226,18 @@ messages: status-reviewing: "&eReviewing" status-resolved: "&aResolved" status-dismissed: "&7Dismissed" + # Fallback entries of the GUI lists, used when gui.items. is missing + report-entry-name: "&c%target_name%" + report-entry-reporter: "&eBy: &f%reporter_name%" + report-entry-reason: "&eReason: &f%reason%" + report-entry-time: "&eTime: &f%time%" + report-entry-status: "&eStatus: &f%status%" + report-entry-server: "&eServer: &f%server%" + report-entry-reports: "&eReports: &c%report_count%" + anticheat-entry-name: "&c%player_name%" + anticheat-entry-flags: "&eFlags (%hours%h): &c%flag_count%" + anticheat-entry-last-flag: "&eLast flag: &f%last_flag%" + anticheat-entry-reports: "&eReports: &c%report_count%" + anticheat-detail-name: "&c%player_name%" + anticheat-detail-reports: "&eReports: &c%report_count%" + anticheat-detail-flag: "&8- &f%check% &7(%server%, %time%) &8%detail%" diff --git a/src/main/resources/messages.yml b/src/main/resources/messages.yml index 81de613..701e7cb 100644 --- a/src/main/resources/messages.yml +++ b/src/main/resources/messages.yml @@ -39,6 +39,22 @@ teleported-to: "&aTeleported to %player%" player-offline: "&cPlayer %player% is offline" screenshot-link: "&aScreenshot: &e%url%" +# GUI fallback entries (used when gui.items. is not configured) +report-entry-name: "&c%target_name%" +report-entry-reporter: "&eBy: &f%reporter_name%" +report-entry-reason: "&eReason: &f%reason%" +report-entry-time: "&eTime: &f%time%" +report-entry-status: "&eStatus: &f%status%" +report-entry-server: "&eServer: &f%server%" +report-entry-reports: "&eReports: &c%report_count%" +anticheat-entry-name: "&c%player_name%" +anticheat-entry-flags: "&eFlags (%hours%h): &c%flag_count%" +anticheat-entry-last-flag: "&eLast flag: &f%last_flag%" +anticheat-entry-reports: "&eReports: &c%report_count%" +anticheat-detail-name: "&c%player_name%" +anticheat-detail-reports: "&eReports: &c%report_count%" +anticheat-detail-flag: "&8- &f%check% &7(%server%, %time%) &8%detail%" + # Stats online-status: "&aOnline now" no-reports: "&eThis player has no reports." diff --git a/src/test/java/dev/loki/lorep/config/MaterialParsingTest.java b/src/test/java/dev/loki/lorep/config/MaterialParsingTest.java new file mode 100644 index 0000000..4b90ffe --- /dev/null +++ b/src/test/java/dev/loki/lorep/config/MaterialParsingTest.java @@ -0,0 +1,73 @@ +package dev.loki.lorep.config; + +import org.bukkit.Material; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +/** + * **Feature: lorep-report-plugin, Property 9: Configuration Parsing** + * **Validates: Requirements 7.1, 7.3, 7.4** + * + *

The GUI items of the config must never fall back to a plain stone block: + * an unknown or missing material has to be reported instead.

+ */ +public class MaterialParsingTest { + + /** + * Property 9: Configuration Parsing + * A material name of the config resolves to the material it names, no + * matter which of the accepted spellings is used. + */ + @Test + void resolvesPlainMaterialNames() { + assertEquals(Material.PLAYER_HEAD, ConfigManager.resolveMaterial("PLAYER_HEAD")); + assertEquals(Material.PAPER, ConfigManager.resolveMaterial("PAPER")); + assertEquals(Material.STONE, ConfigManager.resolveMaterial("STONE")); + } + + /** + * Property 9: Configuration Parsing + * A namespaced material name resolves to the same material as the plain + * spelling of it. + */ + @Test + void resolvesNamespacedMaterialNames() { + assertEquals(Material.PLAYER_HEAD, ConfigManager.resolveMaterial("minecraft:player_head")); + assertEquals(Material.PAPER, ConfigManager.resolveMaterial("minecraft:paper")); + } + + /** + * Property 9: Configuration Parsing + * The material lookup is case insensitive. + */ + @Test + void resolvesMaterialNamesCaseInsensitive() { + assertEquals(Material.PLAYER_HEAD, ConfigManager.resolveMaterial("player_head")); + assertEquals(Material.PLAYER_HEAD, ConfigManager.resolveMaterial("Player_Head")); + } + + /** + * Property 9: Configuration Parsing + * A typo in the material name does not resolve to any material, so the + * caller can report it and use a meaningful fallback. + */ + @Test + void rejectsUnknownMaterialNames() { + assertNull(ConfigManager.resolveMaterial("PLAYERHEAD")); + assertNull(ConfigManager.resolveMaterial("minecraft:playerhead")); + assertNull(ConfigManager.resolveMaterial("not_a_material")); + } + + /** + * Property 9: Configuration Parsing + * An empty material name does not resolve to any material either. + */ + @Test + void rejectsEmptyMaterialNames() { + assertNull(ConfigManager.resolveMaterial(null)); + assertNull(ConfigManager.resolveMaterial("")); + assertNull(ConfigManager.resolveMaterial(" ")); + } +} diff --git a/src/test/java/dev/loki/lorep/gui/EntrySlotsTest.java b/src/test/java/dev/loki/lorep/gui/EntrySlotsTest.java new file mode 100644 index 0000000..56e513a --- /dev/null +++ b/src/test/java/dev/loki/lorep/gui/EntrySlotsTest.java @@ -0,0 +1,91 @@ +package dev.loki.lorep.gui.item; + +import dev.loki.lorep.config.GuiItemConfig; +import org.bukkit.Material; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * **Feature: lorep-report-plugin, Property 6: Pagination Correctness** + * **Validates: Requirements 4.4** + * + *

The entries of a list must fill the free rows of the inventory and must + * never overlap with the navigation buttons of the bottom row.

+ */ +public class EntrySlotsTest { + + private static final int INVENTORY_SIZE = 54; + private static final int FIRST_RESERVED_SLOT = 45; + + /** + * Property 6: Pagination Correctness + * Without configured slots the entries fill the rows above the navigation + * row, so a full page never touches the buttons. + */ + @Test + void usesFreeRowsByDefault() { + List slots = EntrySlots.resolve(null, INVENTORY_SIZE); + + assertEquals(45, slots.size()); + assertEquals(0, slots.get(0)); + assertEquals(44, slots.get(slots.size() - 1)); + for (int slot : slots) { + assertTrue(slot < FIRST_RESERVED_SLOT, "slot " + slot + " is reserved for the navigation"); + } + } + + /** + * Property 6: Pagination Correctness + * The configured slots are used first, the remaining free slots follow so + * that no entry of a page is lost. + */ + @Test + void prefersConfiguredSlots() { + GuiItemConfig config = new GuiItemConfig(Material.PLAYER_HEAD, GuiItemConfig.NO_CUSTOM_MODEL, + null, List.of(), List.of(20, 21), false); + + List slots = EntrySlots.resolve(config, INVENTORY_SIZE); + + assertEquals(20, slots.get(0)); + assertEquals(21, slots.get(1)); + assertEquals(0, slots.get(2)); + assertEquals(45, slots.size()); + } + + /** + * Property 6: Pagination Correctness + * A slot of the navigation row is never used by an entry, no matter how it + * is configured. + */ + @Test + void ignoresReservedSlots() { + GuiItemConfig config = new GuiItemConfig(Material.PLAYER_HEAD, GuiItemConfig.NO_CUSTOM_MODEL, + null, List.of(), List.of(45, 49, 53), false); + + List slots = EntrySlots.resolve(config, INVENTORY_SIZE); + + for (int slot : slots) { + assertTrue(slot < FIRST_RESERVED_SLOT, "slot " + slot + " is reserved for the navigation"); + } + } + + /** + * Property 6: Pagination Correctness + * Every slot is used at most once, the entries never overlap. + */ + @Test + void usesEverySlotOnlyOnce() { + GuiItemConfig config = new GuiItemConfig(Material.PLAYER_HEAD, GuiItemConfig.NO_CUSTOM_MODEL, + null, List.of(), List.of(5, 5, 6), false); + + List slots = EntrySlots.resolve(config, INVENTORY_SIZE); + + assertEquals(slots.size(), slots.stream().distinct().count()); + assertFalse(slots.contains(FIRST_RESERVED_SLOT)); + } +} diff --git a/src/test/java/dev/loki/lorep/util/TextFormatTest.java b/src/test/java/dev/loki/lorep/util/TextFormatTest.java new file mode 100644 index 0000000..c206783 --- /dev/null +++ b/src/test/java/dev/loki/lorep/util/TextFormatTest.java @@ -0,0 +1,85 @@ +package dev.loki.lorep.util; + +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * **Feature: lorep-report-plugin, Property 9: Configuration Parsing** + * **Validates: Requirements 7.1, 7.3, 7.4** + * + *

The ampersand colour codes of the config have to be turned into + * components, player provided text must stay literal text.

+ */ +public class TextFormatTest { + + /** + * Property 9: Configuration Parsing + * A colour code colours the text that follows it. + */ + @Test + void coloursTextWithCode() { + Component component = TextFormat.component("&cHello"); + + List children = component.children(); + assertEquals(1, children.size()); + assertEquals("Hello", ((TextComponent) children.get(0)).content()); + assertEquals(NamedTextColor.RED, children.get(0).color()); + } + + /** + * Property 9: Configuration Parsing + * A decoration code decorates the text that follows it. + */ + @Test + void decoratesTextWithCode() { + Component component = TextFormat.component("&lBold"); + + List children = component.children(); + assertEquals(TextDecoration.State.TRUE, children.get(0).decoration(TextDecoration.BOLD)); + } + + /** + * Property 9: Configuration Parsing + * A text without a colour code stays plain text. + */ + @Test + void keepsPlainText() { + Component component = TextFormat.component("plain text"); + + List children = component.children(); + assertEquals(1, children.size()); + assertEquals("plain text", ((TextComponent) children.get(0)).content()); + } + + /** + * Property 9: Configuration Parsing + * A text of a player is never interpreted as a formatting instruction. + */ + @Test + void keepsPlayerTextLiteral() { + Component component = TextFormat.component("not a tag &x also not"); + + List children = component.children(); + assertEquals(1, children.size()); + assertEquals("not a tag &x also not", ((TextComponent) children.get(0)).content()); + assertTrue(children.get(0).color() == null, "player text must not be coloured"); + } + + /** + * Property 9: Configuration Parsing + * The colour codes can be removed again. + */ + @Test + void stripsColourCodes() { + assertEquals("Hello", TextFormat.strip("&cHello")); + assertEquals("", TextFormat.strip(null)); + } +}