feat: anticheat integration (ServGuard summary + tab), server attribution, Folia readiness
This commit is contained in:
parent
c9f75fbcf2
commit
023c8d1325
18 changed files with 1197 additions and 61 deletions
|
|
@ -48,6 +48,7 @@ LoReport is a modern and performant player report system for Minecraft servers.
|
|||
| `/report <player> <reason>` | `lorep.report` | Report a player |
|
||||
| `/report gui` | `lorep.admin` | Open reports GUI |
|
||||
| `/report stats <player>` | `lorep.admin` | View player report stats |
|
||||
| `/report ac` | `lorep.admin` | Open the anticheat (ServGuard) GUI |
|
||||
| `/rep` | `lorep.report` | Alias for /report |
|
||||
|
||||
### Dependencies
|
||||
|
|
@ -99,6 +100,7 @@ LoReport - современная и производительная систе
|
|||
| `/report <игрок> <причина>` | `lorep.report` | Отправить репорт |
|
||||
| `/report gui` | `lorep.admin` | Открыть GUI репортов |
|
||||
| `/report stats <игрок>` | `lorep.admin` | Статистика репортов игрока |
|
||||
| `/report ac` | `lorep.admin` | GUI античита (ServGuard) |
|
||||
|
||||
### Зависимости
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
package dev.loki.lorep;
|
||||
|
||||
import dev.loki.lorep.anticheat.AnticheatService;
|
||||
import dev.loki.lorep.command.ReportCommand;
|
||||
import dev.loki.lorep.config.ConfigManager;
|
||||
import dev.loki.lorep.database.DatabaseManager;
|
||||
|
|
@ -15,6 +16,7 @@ public final class LorepPlugin extends JavaPlugin {
|
|||
private ConfigManager configManager;
|
||||
private DatabaseManager databaseManager;
|
||||
private DiscordWebhook discordWebhook;
|
||||
private AnticheatService anticheatService;
|
||||
|
||||
@Override
|
||||
public void onEnable() {
|
||||
|
|
@ -27,6 +29,9 @@ public final class LorepPlugin extends JavaPlugin {
|
|||
// Initialize database
|
||||
initializeDatabase();
|
||||
|
||||
// Initialize ServGuard anticheat integration
|
||||
anticheatService = new AnticheatService(databaseManager, configManager, getLogger());
|
||||
|
||||
// Initialize webhook
|
||||
String webhookUrl = configManager.getWebhookUrl();
|
||||
if (webhookUrl != null && !webhookUrl.isEmpty()) {
|
||||
|
|
@ -97,6 +102,10 @@ public final class LorepPlugin extends JavaPlugin {
|
|||
return discordWebhook;
|
||||
}
|
||||
|
||||
public AnticheatService getAnticheatService() {
|
||||
return anticheatService;
|
||||
}
|
||||
|
||||
public void setConfigManager(ConfigManager configManager) {
|
||||
this.configManager = configManager;
|
||||
}
|
||||
|
|
|
|||
151
src/main/java/dev/loki/lorep/anticheat/AnticheatService.java
Normal file
151
src/main/java/dev/loki/lorep/anticheat/AnticheatService.java
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
package dev.loki.lorep.anticheat;
|
||||
|
||||
import dev.loki.lorep.config.ConfigManager;
|
||||
import dev.loki.lorep.database.DatabaseManager;
|
||||
import dev.loki.lorep.database.DatabaseManager.CheckCount;
|
||||
import dev.loki.lorep.database.DatabaseManager.FlaggedPlayer;
|
||||
import dev.loki.lorep.database.DatabaseManager.ViolationEntry;
|
||||
import dev.loki.lorep.util.PaginationUtil;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* ServGuard anticheat integration: aggregates the guard.violations rows stored in
|
||||
* the same database the plugin is connected to. The guard table is probed lazily
|
||||
* on first use; when it is missing the feature disables itself for this database
|
||||
* and logs a single INFO line.
|
||||
*/
|
||||
public class AnticheatService {
|
||||
|
||||
/** The rendered summary appended to a reason is bounded so the 500-char limit stays sane. */
|
||||
private static final int MAX_SUMMARY_CHARS = 120;
|
||||
private static final int MAX_RECENT_VIOLATIONS = 20;
|
||||
private static final String CHECK_SEPARATOR = ", ";
|
||||
private static final String COUNT_SEPARATOR = " ×";
|
||||
|
||||
private final DatabaseManager database;
|
||||
private final ConfigManager config;
|
||||
private final Logger logger;
|
||||
private Boolean tableAvailable;
|
||||
|
||||
public AnticheatService(DatabaseManager database, ConfigManager config, Logger logger) {
|
||||
this.database = database;
|
||||
this.config = config;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
/** Whether the anticheat integration is enabled in the config. */
|
||||
public boolean isEnabled() {
|
||||
return config.isAnticheatEnabled();
|
||||
}
|
||||
|
||||
/** Lookback window in hours used by every anticheat query. */
|
||||
public int getLookbackHours() {
|
||||
return config.getAnticheatLookbackHours();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether anticheat data can be queried: enabled and the guard table probe
|
||||
* succeeded. The probe runs once; a missing table logs one INFO line.
|
||||
*/
|
||||
public synchronized boolean isAvailable() {
|
||||
if (!isEnabled()) {
|
||||
return false;
|
||||
}
|
||||
if (tableAvailable == null) {
|
||||
tableAvailable = database.isAnticheatAvailable();
|
||||
if (!tableAvailable) {
|
||||
logger.info("anticheat table not available - feature disabled for this database");
|
||||
}
|
||||
}
|
||||
return tableAvailable;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the summary suffix appended to a report reason, e.g.
|
||||
* "[AC] flags 72h: move.timer ×7, combat.reach ×5"; empty when there is nothing to show.
|
||||
*/
|
||||
public String buildSummary(UUID playerUuid) {
|
||||
if (!isAvailable()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
int lookbackHours = getLookbackHours();
|
||||
List<CheckCount> topChecks =
|
||||
database.getTopCheckCounts(playerUuid, lookbackHours, config.getAnticheatSummaryMaxChecks());
|
||||
List<String> entries = collectEntries(topChecks, config.getAnticheatSummaryMaxFlags());
|
||||
if (entries.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
String summary = renderSummary(String.join(CHECK_SEPARATOR, entries), lookbackHours);
|
||||
while (summary.length() > MAX_SUMMARY_CHARS && entries.size() > 1) {
|
||||
entries.remove(entries.size() - 1);
|
||||
summary = renderSummary(String.join(CHECK_SEPARATOR, entries), lookbackHours);
|
||||
}
|
||||
if (summary.length() > MAX_SUMMARY_CHARS) {
|
||||
// A single oversized entry: hard-truncate and mark the cut with an ellipsis.
|
||||
summary = summary.substring(0, MAX_SUMMARY_CHARS - 1) + "…";
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
/** Formats "check ×count" entries, bounded by the total flag cap from the config. */
|
||||
private List<String> collectEntries(List<CheckCount> topChecks, int maxFlags) {
|
||||
List<String> entries = new ArrayList<>();
|
||||
int cumulative = 0;
|
||||
for (CheckCount check : topChecks) {
|
||||
// The most frequent check is always included; the flag cap bounds the rest.
|
||||
if (!entries.isEmpty() && cumulative + check.count() > maxFlags) {
|
||||
break;
|
||||
}
|
||||
entries.add(check.checkKey() + COUNT_SEPARATOR + check.count());
|
||||
cumulative += check.count();
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
private String renderSummary(String checks, int lookbackHours) {
|
||||
return config.getMessage("anticheat-summary", "%checks%", checks, "%hours%", String.valueOf(lookbackHours));
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregated flagged players for one list page.
|
||||
*
|
||||
* @return the page, or null when anticheat data is unavailable
|
||||
*/
|
||||
public List<FlaggedPlayer> getFlaggedPlayers(int page, int pageSize) {
|
||||
if (!isAvailable()) {
|
||||
return null;
|
||||
}
|
||||
int offset = PaginationUtil.calculateStartIndex(page, pageSize);
|
||||
return database.getFlaggedPlayers(getLookbackHours(), pageSize, offset);
|
||||
}
|
||||
|
||||
/**
|
||||
* Distinct flagged player count in the lookback window.
|
||||
*
|
||||
* @return the count, or 0 when anticheat data is unavailable
|
||||
*/
|
||||
public int getFlaggedPlayerCount() {
|
||||
if (!isAvailable()) {
|
||||
return 0;
|
||||
}
|
||||
return database.getFlaggedPlayerCount(getLookbackHours());
|
||||
}
|
||||
|
||||
/**
|
||||
* Most recent violations for one player in the lookback window.
|
||||
*
|
||||
* @return the violations, empty when anticheat data is unavailable
|
||||
*/
|
||||
public List<ViolationEntry> getRecentViolations(UUID playerUuid) {
|
||||
if (!isAvailable()) {
|
||||
return List.of();
|
||||
}
|
||||
return database.getRecentViolations(playerUuid, getLookbackHours(), MAX_RECENT_VIOLATIONS);
|
||||
}
|
||||
}
|
||||
|
|
@ -2,6 +2,7 @@ package dev.loki.lorep.command;
|
|||
|
||||
import dev.loki.lorep.LorepPlugin;
|
||||
import dev.loki.lorep.database.Report;
|
||||
import dev.loki.lorep.gui.AnticheatGui;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.OfflinePlayer;
|
||||
import org.bukkit.command.Command;
|
||||
|
|
@ -13,10 +14,13 @@ import org.bukkit.entity.Player;
|
|||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public class ReportCommand implements CommandExecutor, TabCompleter {
|
||||
|
||||
private static final int MAX_REASON_LENGTH = 500;
|
||||
|
||||
private final LorepPlugin plugin;
|
||||
|
||||
public ReportCommand(LorepPlugin plugin) {
|
||||
|
|
@ -47,6 +51,10 @@ public class ReportCommand implements CommandExecutor, TabCompleter {
|
|||
return handleReportImage(player, args[1], args[2]);
|
||||
}
|
||||
|
||||
if (args[0].equalsIgnoreCase("ac")) {
|
||||
return handleAnticheat(player);
|
||||
}
|
||||
|
||||
if (!player.hasPermission("lorep.report")) {
|
||||
player.sendMessage(plugin.getConfigManager().getMessage("no-permission"));
|
||||
return true;
|
||||
|
|
@ -73,11 +81,6 @@ public class ReportCommand implements CommandExecutor, TabCompleter {
|
|||
return true;
|
||||
}
|
||||
|
||||
if (reason.length() > 500) {
|
||||
player.sendMessage(plugin.getConfigManager().getMessage("reason-too-long", "%max%", "500"));
|
||||
return true;
|
||||
}
|
||||
|
||||
return handleReport(player, targetName, reason, imageUrl);
|
||||
}
|
||||
|
||||
|
|
@ -104,13 +107,23 @@ public class ReportCommand implements CommandExecutor, TabCompleter {
|
|||
return true;
|
||||
}
|
||||
|
||||
// Validate the final reason (player text plus anticheat summary); the summary
|
||||
// is truncated first so the player's own text is never cut.
|
||||
String finalReason = appendAnticheatSummary(target.getUniqueId(), reason);
|
||||
if (finalReason.length() > MAX_REASON_LENGTH) {
|
||||
reporter.sendMessage(plugin.getConfigManager().getMessage("reason-too-long",
|
||||
"%max%", String.valueOf(MAX_REASON_LENGTH)));
|
||||
return true;
|
||||
}
|
||||
|
||||
Report report = new Report(
|
||||
reporter.getUniqueId(),
|
||||
reporter.getName(),
|
||||
target.getUniqueId(),
|
||||
target.getName() != null ? target.getName() : targetName,
|
||||
reason,
|
||||
imageUrl
|
||||
finalReason,
|
||||
imageUrl,
|
||||
plugin.getConfigManager().getServerName()
|
||||
);
|
||||
|
||||
plugin.getDatabaseManager().saveReport(report);
|
||||
|
|
@ -123,6 +136,26 @@ public class ReportCommand implements CommandExecutor, TabCompleter {
|
|||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends the ServGuard anticheat summary to the player's reason, truncating
|
||||
* the summary so the combined text stays within the reason length limit.
|
||||
*/
|
||||
private String appendAnticheatSummary(UUID targetUuid, String reason) {
|
||||
String summary = plugin.getAnticheatService().buildSummary(targetUuid);
|
||||
if (summary.isEmpty()) {
|
||||
return reason;
|
||||
}
|
||||
|
||||
int budget = MAX_REASON_LENGTH - reason.length();
|
||||
if (budget <= 0) {
|
||||
return reason;
|
||||
}
|
||||
if (summary.length() > budget) {
|
||||
summary = summary.substring(0, budget);
|
||||
}
|
||||
return reason + " " + summary;
|
||||
}
|
||||
|
||||
private boolean handleReportImage(Player player, String idStr, String imageUrl) {
|
||||
if (!player.hasPermission("lorep.admin")) {
|
||||
player.sendMessage(plugin.getConfigManager().getMessage("no-permission"));
|
||||
|
|
@ -154,7 +187,8 @@ public class ReportCommand implements CommandExecutor, TabCompleter {
|
|||
report.reason(),
|
||||
imageUrl,
|
||||
report.status(),
|
||||
report.createdAt()
|
||||
report.createdAt(),
|
||||
report.serverName()
|
||||
);
|
||||
|
||||
if (plugin.getDiscordWebhook() != null) {
|
||||
|
|
@ -175,6 +209,16 @@ public class ReportCommand implements CommandExecutor, TabCompleter {
|
|||
return true;
|
||||
}
|
||||
|
||||
private boolean handleAnticheat(Player player) {
|
||||
if (!player.hasPermission("lorep.admin")) {
|
||||
player.sendMessage(plugin.getConfigManager().getMessage("no-permission"));
|
||||
return true;
|
||||
}
|
||||
|
||||
new AnticheatGui(plugin, 0).open(player);
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean handleStats(Player player, String targetName) {
|
||||
new ReportStatsCommand(plugin).execute(player, targetName);
|
||||
return true;
|
||||
|
|
@ -197,6 +241,9 @@ public class ReportCommand implements CommandExecutor, TabCompleter {
|
|||
if ("image".startsWith(input)) {
|
||||
completions.add("image");
|
||||
}
|
||||
if ("ac".startsWith(input)) {
|
||||
completions.add("ac");
|
||||
}
|
||||
}
|
||||
|
||||
completions.addAll(
|
||||
|
|
|
|||
|
|
@ -74,6 +74,26 @@ public class ConfigManager {
|
|||
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) {
|
||||
String message = messages.getString(key);
|
||||
if (message == null) {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
package dev.loki.lorep.database;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
|
|
@ -28,4 +29,42 @@ public interface DatabaseManager {
|
|||
void updateReportImage(int reportId, String imageUrl);
|
||||
|
||||
Report getReportById(int id);
|
||||
|
||||
/**
|
||||
* Probes the ServGuard anticheat violations table in the same database.
|
||||
*
|
||||
* @return true when the table exists and is queryable
|
||||
*/
|
||||
boolean isAnticheatAvailable();
|
||||
|
||||
/**
|
||||
* Top anticheat check counts for one player inside the lookback window.
|
||||
*
|
||||
* @return most frequent checks first, empty when the player has no flags
|
||||
*/
|
||||
List<CheckCount> getTopCheckCounts(UUID playerUuid, int lookbackHours, int limit);
|
||||
|
||||
/**
|
||||
* Distinct flagged player count inside the lookback window.
|
||||
*/
|
||||
int getFlaggedPlayerCount(int lookbackHours);
|
||||
|
||||
/**
|
||||
* Aggregated flagged players inside the lookback window, most flags first.
|
||||
*/
|
||||
List<FlaggedPlayer> getFlaggedPlayers(int lookbackHours, int limit, int offset);
|
||||
|
||||
/**
|
||||
* Most recent anticheat violations for one player inside the lookback window.
|
||||
*/
|
||||
List<ViolationEntry> getRecentViolations(UUID playerUuid, int lookbackHours, int limit);
|
||||
|
||||
/** One aggregated check of the ServGuard guard.violations table. */
|
||||
record CheckCount(String checkKey, int count) {}
|
||||
|
||||
/** One player aggregated over the ServGuard guard.violations table. */
|
||||
record FlaggedPlayer(UUID playerUuid, String playerName, int flagCount, Instant lastFlagAt) {}
|
||||
|
||||
/** One raw ServGuard guard.violations row. */
|
||||
record ViolationEntry(String checkKey, String detail, String server, double weight, Instant createdAt) {}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import java.sql.PreparedStatement;
|
|||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
|
@ -81,12 +82,15 @@ public class PostgreSQLDatabaseManager implements DatabaseManager {
|
|||
|
||||
String createTargetIndex = "CREATE INDEX IF NOT EXISTS idx_target_uuid ON reports(target_uuid)";
|
||||
String createReporterTargetIndex = "CREATE INDEX IF NOT EXISTS idx_reporter_target ON reports(reporter_uuid, target_uuid)";
|
||||
// Server attribution column for reports created on this network node
|
||||
String addServerName = "ALTER TABLE reports ADD COLUMN IF NOT EXISTS server_name TEXT";
|
||||
|
||||
try (Connection conn = dataSource.getConnection();
|
||||
Statement stmt = conn.createStatement()) {
|
||||
stmt.execute(createTable);
|
||||
stmt.execute(createTargetIndex);
|
||||
stmt.execute(createReporterTargetIndex);
|
||||
stmt.execute(addServerName);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -101,7 +105,7 @@ public class PostgreSQLDatabaseManager implements DatabaseManager {
|
|||
@Override
|
||||
public void saveReport(Report report) {
|
||||
String sql = "INSERT INTO reports (reporter_uuid, reporter_name, target_uuid, "
|
||||
+ "target_name, reason, image_url, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
|
||||
+ "target_name, reason, image_url, status, created_at, server_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
|
||||
|
||||
try (Connection conn = dataSource.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(sql)) {
|
||||
|
|
@ -117,6 +121,7 @@ public class PostgreSQLDatabaseManager implements DatabaseManager {
|
|||
}
|
||||
stmt.setString(7, report.status());
|
||||
stmt.setLong(8, report.createdAt().toEpochMilli());
|
||||
stmt.setString(9, report.serverName() != null ? report.serverName() : Report.UNKNOWN_SERVER);
|
||||
stmt.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, "Failed to save report", e);
|
||||
|
|
@ -243,6 +248,10 @@ public class PostgreSQLDatabaseManager implements DatabaseManager {
|
|||
if (rs.wasNull()) {
|
||||
imageUrl = null;
|
||||
}
|
||||
String serverName = rs.getString("server_name");
|
||||
if (rs.wasNull()) {
|
||||
serverName = Report.UNKNOWN_SERVER;
|
||||
}
|
||||
return new Report(
|
||||
rs.getInt("id"),
|
||||
UUID.fromString(rs.getString("reporter_uuid")),
|
||||
|
|
@ -252,7 +261,8 @@ public class PostgreSQLDatabaseManager implements DatabaseManager {
|
|||
rs.getString("reason"),
|
||||
imageUrl,
|
||||
rs.getString("status"),
|
||||
Instant.ofEpochMilli(rs.getLong("created_at"))
|
||||
Instant.ofEpochMilli(rs.getLong("created_at")),
|
||||
serverName
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -306,4 +316,125 @@ public class PostgreSQLDatabaseManager implements DatabaseManager {
|
|||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAnticheatAvailable() {
|
||||
String sql = "SELECT to_regclass('guard.violations')";
|
||||
|
||||
try (Connection conn = dataSource.getConnection();
|
||||
Statement stmt = conn.createStatement();
|
||||
ResultSet rs = stmt.executeQuery(sql)) {
|
||||
return rs.next() && rs.getString(1) != null;
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.WARNING, "Failed to probe anticheat table", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<CheckCount> getTopCheckCounts(UUID playerUuid, int lookbackHours, int limit) {
|
||||
String sql = "SELECT check_key, COUNT(*) AS cnt FROM guard.violations "
|
||||
+ "WHERE player_uuid = ? AND created_at > NOW() - (? * INTERVAL '1 hour') "
|
||||
+ "GROUP BY check_key ORDER BY cnt DESC LIMIT ?";
|
||||
List<CheckCount> counts = new ArrayList<>();
|
||||
|
||||
try (Connection conn = dataSource.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(sql)) {
|
||||
stmt.setString(1, playerUuid.toString());
|
||||
stmt.setInt(2, lookbackHours);
|
||||
stmt.setInt(3, limit);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
counts.add(new CheckCount(rs.getString("check_key"), rs.getInt("cnt")));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, "Failed to get anticheat check counts", e);
|
||||
}
|
||||
|
||||
return counts;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getFlaggedPlayerCount(int lookbackHours) {
|
||||
String sql = "SELECT COUNT(*) FROM (SELECT player_uuid FROM guard.violations "
|
||||
+ "WHERE created_at > NOW() - (? * INTERVAL '1 hour') GROUP BY player_uuid) AS flagged";
|
||||
|
||||
try (Connection conn = dataSource.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(sql)) {
|
||||
stmt.setInt(1, lookbackHours);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
return rs.getInt(1);
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, "Failed to count flagged players", e);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<FlaggedPlayer> getFlaggedPlayers(int lookbackHours, int limit, int offset) {
|
||||
String sql = "SELECT player_uuid, player_name, COUNT(*) AS cnt, MAX(created_at) AS last_at "
|
||||
+ "FROM guard.violations WHERE created_at > NOW() - (? * INTERVAL '1 hour') "
|
||||
+ "GROUP BY player_uuid, player_name ORDER BY cnt DESC, last_at DESC LIMIT ? OFFSET ?";
|
||||
List<FlaggedPlayer> players = new ArrayList<>();
|
||||
|
||||
try (Connection conn = dataSource.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(sql)) {
|
||||
stmt.setInt(1, lookbackHours);
|
||||
stmt.setInt(2, limit);
|
||||
stmt.setInt(3, offset);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
players.add(new FlaggedPlayer(
|
||||
UUID.fromString(rs.getString("player_uuid")),
|
||||
rs.getString("player_name"),
|
||||
rs.getInt("cnt"),
|
||||
toInstant(rs.getTimestamp("last_at"))
|
||||
));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, "Failed to get flagged players", e);
|
||||
}
|
||||
|
||||
return players;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ViolationEntry> getRecentViolations(UUID playerUuid, int lookbackHours, int limit) {
|
||||
String sql = "SELECT check_key, detail, server, weight, created_at FROM guard.violations "
|
||||
+ "WHERE player_uuid = ? AND created_at > NOW() - (? * INTERVAL '1 hour') "
|
||||
+ "ORDER BY created_at DESC LIMIT ?";
|
||||
List<ViolationEntry> violations = new ArrayList<>();
|
||||
|
||||
try (Connection conn = dataSource.getConnection();
|
||||
PreparedStatement stmt = conn.prepareStatement(sql)) {
|
||||
stmt.setString(1, playerUuid.toString());
|
||||
stmt.setInt(2, lookbackHours);
|
||||
stmt.setInt(3, limit);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
violations.add(new ViolationEntry(
|
||||
rs.getString("check_key"),
|
||||
rs.getString("detail"),
|
||||
rs.getString("server"),
|
||||
rs.getDouble("weight"),
|
||||
toInstant(rs.getTimestamp("created_at"))
|
||||
));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, "Failed to get recent anticheat violations", e);
|
||||
}
|
||||
|
||||
return violations;
|
||||
}
|
||||
|
||||
private static Instant toInstant(Timestamp timestamp) {
|
||||
return timestamp != null ? timestamp.toInstant() : Instant.EPOCH;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,13 +12,23 @@ public record Report(
|
|||
String reason,
|
||||
String imageUrl,
|
||||
String status,
|
||||
Instant createdAt
|
||||
Instant createdAt,
|
||||
String serverName
|
||||
) {
|
||||
/** Server attribution used when the origin network node is unknown. */
|
||||
public static final String UNKNOWN_SERVER = "unknown";
|
||||
|
||||
public Report(UUID reporterUuid, String reporterName, UUID targetUuid, String targetName, String reason) {
|
||||
this(0, reporterUuid, reporterName, targetUuid, targetName, reason, null, "PENDING", Instant.now());
|
||||
this(0, reporterUuid, reporterName, targetUuid, targetName, reason, null, "PENDING", Instant.now(), UNKNOWN_SERVER);
|
||||
}
|
||||
|
||||
public Report(UUID reporterUuid, String reporterName, UUID targetUuid, String targetName, String reason, String imageUrl) {
|
||||
this(0, reporterUuid, reporterName, targetUuid, targetName, reason, imageUrl, "PENDING", Instant.now());
|
||||
this(0, reporterUuid, reporterName, targetUuid, targetName, reason, imageUrl, "PENDING", Instant.now(), UNKNOWN_SERVER);
|
||||
}
|
||||
|
||||
/** Convenience constructor for reports created on a known network node. */
|
||||
public Report(UUID reporterUuid, String reporterName, UUID targetUuid, String targetName, String reason,
|
||||
String imageUrl, String serverName) {
|
||||
this(0, reporterUuid, reporterName, targetUuid, targetName, reason, imageUrl, "PENDING", Instant.now(), serverName);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import java.sql.PreparedStatement;
|
|||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
|
@ -14,6 +15,10 @@ import java.util.UUID;
|
|||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* SQLite-backed database. All methods are synchronized on this instance because
|
||||
* Folia region threads may invoke them concurrently.
|
||||
*/
|
||||
public class SQLiteDatabaseManager implements DatabaseManager {
|
||||
|
||||
private final File dataFolder;
|
||||
|
|
@ -28,7 +33,7 @@ public class SQLiteDatabaseManager implements DatabaseManager {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void initialize() {
|
||||
public synchronized void initialize() {
|
||||
try {
|
||||
if (!dataFolder.exists()) {
|
||||
dataFolder.mkdirs();
|
||||
|
|
@ -68,10 +73,31 @@ public class SQLiteDatabaseManager implements DatabaseManager {
|
|||
stmt.execute(createTargetIndex);
|
||||
stmt.execute(createReporterTargetIndex);
|
||||
}
|
||||
|
||||
addServerNameColumn();
|
||||
}
|
||||
|
||||
/**
|
||||
* SQLite has no ALTER TABLE ... ADD COLUMN IF NOT EXISTS, so the column
|
||||
* presence is checked via PRAGMA before altering the table.
|
||||
*/
|
||||
private void addServerNameColumn() throws SQLException {
|
||||
try (Statement stmt = connection.createStatement();
|
||||
ResultSet rs = stmt.executeQuery("PRAGMA table_info(reports)")) {
|
||||
while (rs.next()) {
|
||||
if ("server_name".equalsIgnoreCase(rs.getString("name"))) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try (Statement stmt = connection.createStatement()) {
|
||||
stmt.execute("ALTER TABLE reports ADD COLUMN server_name TEXT");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
public synchronized void close() {
|
||||
try {
|
||||
if (connection != null && !connection.isClosed()) {
|
||||
connection.close();
|
||||
|
|
@ -83,9 +109,9 @@ public class SQLiteDatabaseManager implements DatabaseManager {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void saveReport(Report report) {
|
||||
public synchronized void saveReport(Report report) {
|
||||
String sql = "INSERT INTO reports (reporter_uuid, reporter_name, target_uuid, "
|
||||
+ "target_name, reason, image_url, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
|
||||
+ "target_name, reason, image_url, status, created_at, server_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
|
||||
stmt.setString(1, report.reporterUuid().toString());
|
||||
|
|
@ -100,6 +126,7 @@ public class SQLiteDatabaseManager implements DatabaseManager {
|
|||
}
|
||||
stmt.setString(7, report.status());
|
||||
stmt.setLong(8, report.createdAt().toEpochMilli());
|
||||
stmt.setString(9, report.serverName() != null ? report.serverName() : Report.UNKNOWN_SERVER);
|
||||
stmt.executeUpdate();
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, "Failed to save report", e);
|
||||
|
|
@ -107,7 +134,7 @@ public class SQLiteDatabaseManager implements DatabaseManager {
|
|||
}
|
||||
|
||||
@Override
|
||||
public List<Report> getReportsForTarget(UUID targetUuid) {
|
||||
public synchronized List<Report> getReportsForTarget(UUID targetUuid) {
|
||||
String sql = "SELECT * FROM reports WHERE target_uuid = ? ORDER BY created_at DESC";
|
||||
List<Report> reports = new ArrayList<>();
|
||||
|
||||
|
|
@ -126,7 +153,7 @@ public class SQLiteDatabaseManager implements DatabaseManager {
|
|||
}
|
||||
|
||||
@Override
|
||||
public List<Report> getAllReports() {
|
||||
public synchronized List<Report> getAllReports() {
|
||||
String sql = "SELECT * FROM reports ORDER BY created_at DESC";
|
||||
List<Report> reports = new ArrayList<>();
|
||||
|
||||
|
|
@ -143,7 +170,7 @@ public class SQLiteDatabaseManager implements DatabaseManager {
|
|||
}
|
||||
|
||||
@Override
|
||||
public int getReportCount(UUID targetUuid) {
|
||||
public synchronized int getReportCount(UUID targetUuid) {
|
||||
String sql = "SELECT COUNT(*) FROM reports WHERE target_uuid = ?";
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
|
||||
|
|
@ -161,7 +188,7 @@ public class SQLiteDatabaseManager implements DatabaseManager {
|
|||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReported(UUID reporterUuid, UUID targetUuid) {
|
||||
public synchronized boolean hasReported(UUID reporterUuid, UUID targetUuid) {
|
||||
String sql = "SELECT COUNT(*) FROM reports WHERE reporter_uuid = ? AND target_uuid = ?";
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
|
||||
|
|
@ -180,7 +207,7 @@ public class SQLiteDatabaseManager implements DatabaseManager {
|
|||
}
|
||||
|
||||
@Override
|
||||
public List<Report> getReportsPaginated(int page, int pageSize) {
|
||||
public synchronized List<Report> getReportsPaginated(int page, int pageSize) {
|
||||
String sql = "SELECT * FROM reports ORDER BY created_at DESC LIMIT ? OFFSET ?";
|
||||
List<Report> reports = new ArrayList<>();
|
||||
|
||||
|
|
@ -200,7 +227,7 @@ public class SQLiteDatabaseManager implements DatabaseManager {
|
|||
}
|
||||
|
||||
@Override
|
||||
public int getTotalReportCount() {
|
||||
public synchronized int getTotalReportCount() {
|
||||
String sql = "SELECT COUNT(*) FROM reports";
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(sql);
|
||||
|
|
@ -220,6 +247,10 @@ public class SQLiteDatabaseManager implements DatabaseManager {
|
|||
if (rs.wasNull()) {
|
||||
imageUrl = null;
|
||||
}
|
||||
String serverName = rs.getString("server_name");
|
||||
if (rs.wasNull()) {
|
||||
serverName = Report.UNKNOWN_SERVER;
|
||||
}
|
||||
return new Report(
|
||||
rs.getInt("id"),
|
||||
UUID.fromString(rs.getString("reporter_uuid")),
|
||||
|
|
@ -229,12 +260,13 @@ public class SQLiteDatabaseManager implements DatabaseManager {
|
|||
rs.getString("reason"),
|
||||
imageUrl,
|
||||
rs.getString("status"),
|
||||
Instant.ofEpochMilli(rs.getLong("created_at"))
|
||||
Instant.ofEpochMilli(rs.getLong("created_at")),
|
||||
serverName
|
||||
);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateReportStatus(int reportId, String status) {
|
||||
public synchronized void updateReportStatus(int reportId, String status) {
|
||||
String sql = "UPDATE reports SET status = ? WHERE id = ?";
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
|
||||
|
|
@ -247,7 +279,7 @@ public class SQLiteDatabaseManager implements DatabaseManager {
|
|||
}
|
||||
|
||||
@Override
|
||||
public void updateReportImage(int reportId, String imageUrl) {
|
||||
public synchronized void updateReportImage(int reportId, String imageUrl) {
|
||||
String sql = "UPDATE reports SET image_url = ? WHERE id = ?";
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
|
||||
|
|
@ -264,7 +296,7 @@ public class SQLiteDatabaseManager implements DatabaseManager {
|
|||
}
|
||||
|
||||
@Override
|
||||
public Report getReportById(int id) {
|
||||
public synchronized Report getReportById(int id) {
|
||||
String sql = "SELECT * FROM reports WHERE id = ?";
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
|
||||
|
|
@ -280,4 +312,126 @@ public class SQLiteDatabaseManager implements DatabaseManager {
|
|||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized boolean isAnticheatAvailable() {
|
||||
// ServGuard persists violations to PostgreSQL; guard.violations normally
|
||||
// does not exist here, the probe fails and the feature disables itself.
|
||||
String sql = "SELECT 1 FROM guard.violations LIMIT 1";
|
||||
|
||||
try (Statement stmt = connection.createStatement();
|
||||
ResultSet rs = stmt.executeQuery(sql)) {
|
||||
return rs.next();
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.FINE, "Anticheat table not available in SQLite database", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized List<CheckCount> getTopCheckCounts(UUID playerUuid, int lookbackHours, int limit) {
|
||||
String sql = "SELECT check_key, COUNT(*) AS cnt FROM guard.violations "
|
||||
+ "WHERE player_uuid = ? AND created_at > datetime('now', ?) "
|
||||
+ "GROUP BY check_key ORDER BY cnt DESC LIMIT ?";
|
||||
List<CheckCount> counts = new ArrayList<>();
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
|
||||
stmt.setString(1, playerUuid.toString());
|
||||
stmt.setString(2, hoursClause(lookbackHours));
|
||||
stmt.setInt(3, limit);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
counts.add(new CheckCount(rs.getString("check_key"), rs.getInt("cnt")));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, "Failed to get anticheat check counts", e);
|
||||
}
|
||||
|
||||
return counts;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized int getFlaggedPlayerCount(int lookbackHours) {
|
||||
String sql = "SELECT COUNT(*) FROM (SELECT player_uuid FROM guard.violations "
|
||||
+ "WHERE created_at > datetime('now', ?) GROUP BY player_uuid) AS flagged";
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
|
||||
stmt.setString(1, hoursClause(lookbackHours));
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
return rs.getInt(1);
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, "Failed to count flagged players", e);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized List<FlaggedPlayer> getFlaggedPlayers(int lookbackHours, int limit, int offset) {
|
||||
String sql = "SELECT player_uuid, player_name, COUNT(*) AS cnt, MAX(created_at) AS last_at "
|
||||
+ "FROM guard.violations WHERE created_at > datetime('now', ?) "
|
||||
+ "GROUP BY player_uuid, player_name ORDER BY cnt DESC, last_at DESC LIMIT ? OFFSET ?";
|
||||
List<FlaggedPlayer> players = new ArrayList<>();
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
|
||||
stmt.setString(1, hoursClause(lookbackHours));
|
||||
stmt.setInt(2, limit);
|
||||
stmt.setInt(3, offset);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
players.add(new FlaggedPlayer(
|
||||
UUID.fromString(rs.getString("player_uuid")),
|
||||
rs.getString("player_name"),
|
||||
rs.getInt("cnt"),
|
||||
toInstant(rs.getTimestamp("last_at"))
|
||||
));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, "Failed to get flagged players", e);
|
||||
}
|
||||
|
||||
return players;
|
||||
}
|
||||
|
||||
@Override
|
||||
public synchronized List<ViolationEntry> getRecentViolations(UUID playerUuid, int lookbackHours, int limit) {
|
||||
String sql = "SELECT check_key, detail, server, weight, created_at FROM guard.violations "
|
||||
+ "WHERE player_uuid = ? AND created_at > datetime('now', ?) "
|
||||
+ "ORDER BY created_at DESC LIMIT ?";
|
||||
List<ViolationEntry> violations = new ArrayList<>();
|
||||
|
||||
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
|
||||
stmt.setString(1, playerUuid.toString());
|
||||
stmt.setString(2, hoursClause(lookbackHours));
|
||||
stmt.setInt(3, limit);
|
||||
try (ResultSet rs = stmt.executeQuery()) {
|
||||
while (rs.next()) {
|
||||
violations.add(new ViolationEntry(
|
||||
rs.getString("check_key"),
|
||||
rs.getString("detail"),
|
||||
rs.getString("server"),
|
||||
rs.getDouble("weight"),
|
||||
toInstant(rs.getTimestamp("created_at"))
|
||||
));
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
logger.log(Level.SEVERE, "Failed to get recent anticheat violations", e);
|
||||
}
|
||||
|
||||
return violations;
|
||||
}
|
||||
|
||||
private static String hoursClause(int lookbackHours) {
|
||||
return "-" + lookbackHours + " hours";
|
||||
}
|
||||
|
||||
private static Instant toInstant(Timestamp timestamp) {
|
||||
return timestamp != null ? timestamp.toInstant() : Instant.EPOCH;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
29
src/main/java/dev/loki/lorep/gui/ActionInventory.java
Normal file
29
src/main/java/dev/loki/lorep/gui/ActionInventory.java
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
package dev.loki.lorep.gui;
|
||||
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Inventory that exposes slot-keyed click actions. Both {@link ReportGui} and
|
||||
* {@link AnticheatGui} implement it so {@link GuiClickListener} can cancel,
|
||||
* dispatch and paginate generically for either view.
|
||||
*/
|
||||
public interface ActionInventory extends InventoryHolder {
|
||||
|
||||
/** Slot index to action string mapping used for click dispatch. */
|
||||
Map<Integer, String> slotActions();
|
||||
|
||||
/** Zero-based page currently shown in the list view. */
|
||||
int getPage();
|
||||
|
||||
/** Whether the current view is a detail view. */
|
||||
boolean isDetailView();
|
||||
|
||||
/** Open the list view of this inventory family at the given zero-based page. */
|
||||
void openPage(Player player, int page);
|
||||
|
||||
/** Total pages available in the list view, at least 1. */
|
||||
int getTotalPages();
|
||||
}
|
||||
358
src/main/java/dev/loki/lorep/gui/AnticheatGui.java
Normal file
358
src/main/java/dev/loki/lorep/gui/AnticheatGui.java
Normal file
|
|
@ -0,0 +1,358 @@
|
|||
package dev.loki.lorep.gui;
|
||||
|
||||
import dev.loki.lorep.LorepPlugin;
|
||||
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.util.PaginationUtil;
|
||||
import dev.loki.lorep.util.TimeUtil;
|
||||
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;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* ServGuard anticheat overview GUI: paginated list of flagged players and a
|
||||
* per-player view of recent flags. Actions: ac_detail, prev/next page, back to
|
||||
* the report list, open-reports, close.
|
||||
*/
|
||||
public class AnticheatGui implements ActionInventory {
|
||||
|
||||
public static final int INVENTORY_SIZE = 54;
|
||||
private static final int INFO_SLOT = 22;
|
||||
|
||||
private final LorepPlugin plugin;
|
||||
private final int page;
|
||||
private boolean detailView;
|
||||
private final Map<UUID, String> playerNames = new HashMap<>();
|
||||
private final Map<Integer, String> slotActions = new HashMap<>();
|
||||
private Inventory inventory;
|
||||
|
||||
public AnticheatGui(LorepPlugin plugin, int page) {
|
||||
this.plugin = plugin;
|
||||
this.page = page;
|
||||
}
|
||||
|
||||
public void open(Player player) {
|
||||
detailView = false;
|
||||
playerNames.clear();
|
||||
slotActions.clear();
|
||||
|
||||
String title = plugin.getConfigManager().getMessage("anticheat-list-title",
|
||||
"%page%", String.valueOf(page + 1));
|
||||
this.inventory = Bukkit.createInventory(this, INVENTORY_SIZE, title);
|
||||
|
||||
AnticheatService service = plugin.getAnticheatService();
|
||||
int pageSize = plugin.getConfig().getInt("gui.reports-per-page", 45);
|
||||
List<FlaggedPlayer> flagged = service.getFlaggedPlayers(page, pageSize);
|
||||
if (flagged == null) {
|
||||
placeInfoItem(plugin.getConfigManager().getMessage("anticheat-unavailable"));
|
||||
player.openInventory(inventory);
|
||||
return;
|
||||
}
|
||||
|
||||
int totalPlayers = service.getFlaggedPlayerCount();
|
||||
GuiItemConfig entryConfig = plugin.getConfigManager().getGuiItem("anticheat-entry");
|
||||
|
||||
for (int i = 0; i < flagged.size(); i++) {
|
||||
FlaggedPlayer entry = flagged.get(i);
|
||||
if (entry.playerUuid() != null) {
|
||||
playerNames.put(entry.playerUuid(), entry.playerName());
|
||||
}
|
||||
List<Integer> slots = entryConfig != null ? entryConfig.slots() : List.of();
|
||||
int slot = !slots.isEmpty() && i < slots.size() ? slots.get(i) : i;
|
||||
inventory.setItem(slot, createEntryItem(entry, entryConfig));
|
||||
slotActions.put(slot, "ac_detail:" + entry.playerUuid());
|
||||
}
|
||||
|
||||
addNavigation(PaginationUtil.calculateTotalPages(totalPlayers, pageSize), totalPlayers);
|
||||
player.openInventory(inventory);
|
||||
}
|
||||
|
||||
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);
|
||||
this.inventory = Bukkit.createInventory(this, INVENTORY_SIZE, title);
|
||||
|
||||
AnticheatService service = plugin.getAnticheatService();
|
||||
if (!service.isAvailable()) {
|
||||
placeInfoItem(plugin.getConfigManager().getMessage("anticheat-unavailable"));
|
||||
player.openInventory(inventory);
|
||||
return;
|
||||
}
|
||||
|
||||
List<ViolationEntry> violations = service.getRecentViolations(playerUuid);
|
||||
if (violations.isEmpty()) {
|
||||
placeInfoItem(plugin.getConfigManager().getMessage("anticheat-detail-empty"));
|
||||
} else {
|
||||
placeDetailItem(playerUuid, name, violations);
|
||||
}
|
||||
|
||||
placeConfigItem("anticheat-tab", 45, "back");
|
||||
placeConfigItem("close", 47, "close");
|
||||
placeConfigItem("anticheat-reports", 49, "open-reports");
|
||||
player.openInventory(inventory);
|
||||
}
|
||||
|
||||
private void addNavigation(int totalPages, int totalPlayers) {
|
||||
if (page > 0) {
|
||||
placeConfigItem("prev-page", 45, "prev_page");
|
||||
}
|
||||
placeConfigItem("anticheat-tab", 46, "back");
|
||||
placeConfigItem("close", 47, "close");
|
||||
placePageInfo(totalPages, totalPlayers);
|
||||
if (page < totalPages - 1) {
|
||||
placeConfigItem("next-page", 53, "next_page");
|
||||
}
|
||||
}
|
||||
|
||||
private void placeConfigItem(String configPath, int defaultSlot, String action) {
|
||||
GuiItemConfig config = plugin.getConfigManager().getGuiItem(configPath);
|
||||
if (config == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<Integer> 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);
|
||||
slotActions.put(slot, action);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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<String> lore = new ArrayList<>();
|
||||
for (String line : meta.getLore()) {
|
||||
lore.add(replacePagePlaceholders(line, totalPages, totalPlayers));
|
||||
}
|
||||
meta.setLore(lore);
|
||||
}
|
||||
item.setItemMeta(meta);
|
||||
}
|
||||
|
||||
List<Integer> slots = config.slots();
|
||||
if (slots.isEmpty()) {
|
||||
inventory.setItem(49, item);
|
||||
} else {
|
||||
for (int slot : slots) {
|
||||
inventory.setItem(slot, item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void placeDetailItem(UUID playerUuid, String name, List<ViolationEntry> violations) {
|
||||
GuiItemConfig config = plugin.getConfigManager().getGuiItem("anticheat-detail");
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
List<Integer> 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<String> buildDetailLore(List<String> configLore, List<ViolationEntry> violations,
|
||||
String name, int reportCount) {
|
||||
List<String> 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<String> 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()));
|
||||
}
|
||||
|
||||
private String replacePagePlaceholders(String text, int totalPages, int totalPlayers) {
|
||||
return text
|
||||
.replace("%page%", String.valueOf(page + 1))
|
||||
.replace("%total%", String.valueOf(Math.max(1, totalPages)))
|
||||
.replace("%total_players%", String.valueOf(totalPlayers));
|
||||
}
|
||||
|
||||
private void placeInfoItem(String text) {
|
||||
ItemStack item = new ItemStack(Material.PAPER);
|
||||
ItemMeta meta = item.getItemMeta();
|
||||
if (meta != null) {
|
||||
meta.setDisplayName(text);
|
||||
item.setItemMeta(meta);
|
||||
}
|
||||
inventory.setItem(INFO_SLOT, item);
|
||||
}
|
||||
|
||||
private ItemStack createFallbackHead(UUID owner, String name, List<String> 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<String> buildFallbackEntryLore(FlaggedPlayer entry, int reportCount) {
|
||||
String lastFlag = entry.lastFlagAt() != null ? TimeUtil.formatTimeAgo(entry.lastFlagAt()) : "";
|
||||
List<String> 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<String> buildFallbackDetailLore(List<ViolationEntry> violations, int reportCount) {
|
||||
List<String> 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);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Integer, String> slotActions() {
|
||||
return slotActions;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPage() {
|
||||
return page;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isDetailView() {
|
||||
return detailView;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void openPage(Player player, int page) {
|
||||
new AnticheatGui(plugin, page).open(player);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTotalPages() {
|
||||
int pageSize = plugin.getConfig().getInt("gui.reports-per-page", 45);
|
||||
int totalPlayers = plugin.getAnticheatService().getFlaggedPlayerCount();
|
||||
return PaginationUtil.calculateTotalPages(totalPlayers, pageSize);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Inventory getInventory() {
|
||||
return inventory;
|
||||
}
|
||||
}
|
||||
|
|
@ -2,7 +2,6 @@ package dev.loki.lorep.gui;
|
|||
|
||||
import dev.loki.lorep.LorepPlugin;
|
||||
import dev.loki.lorep.database.Report;
|
||||
import dev.loki.lorep.util.PaginationUtil;
|
||||
import org.bukkit.Bukkit;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.event.EventHandler;
|
||||
|
|
@ -10,6 +9,8 @@ import org.bukkit.event.Listener;
|
|||
import org.bukkit.event.inventory.InventoryClickEvent;
|
||||
import org.bukkit.event.inventory.InventoryDragEvent;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public class GuiClickListener implements Listener {
|
||||
|
||||
private final LorepPlugin plugin;
|
||||
|
|
@ -20,7 +21,7 @@ public class GuiClickListener implements Listener {
|
|||
|
||||
@EventHandler
|
||||
public void onInventoryClick(InventoryClickEvent event) {
|
||||
if (!(event.getInventory().getHolder() instanceof ReportGui gui)) {
|
||||
if (!(event.getInventory().getHolder() instanceof ActionInventory gui)) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -30,7 +31,7 @@ public class GuiClickListener implements Listener {
|
|||
return;
|
||||
}
|
||||
|
||||
String action = gui.slotActions.get(event.getRawSlot());
|
||||
String action = gui.slotActions().get(event.getRawSlot());
|
||||
|
||||
if (action == null) {
|
||||
return;
|
||||
|
|
@ -40,61 +41,95 @@ public class GuiClickListener implements Listener {
|
|||
case "prev_page" -> handlePrevPage(player, gui);
|
||||
case "next_page" -> handleNextPage(player, gui);
|
||||
case "close" -> handleClose(player, gui);
|
||||
case "back" -> handleBack(player, gui);
|
||||
case "teleport" -> handleTeleport(player, gui);
|
||||
case "screenshot" -> handleScreenshot(player, gui);
|
||||
default -> handleDefaultAction(player, gui, action);
|
||||
}
|
||||
}
|
||||
|
||||
private void handlePrevPage(Player player, ReportGui gui) {
|
||||
if (gui.page > 0) {
|
||||
new ReportGui(plugin, gui.page - 1).open(player);
|
||||
private void handlePrevPage(Player player, ActionInventory gui) {
|
||||
if (gui.getPage() > 0) {
|
||||
gui.openPage(player, gui.getPage() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleNextPage(Player player, ReportGui gui) {
|
||||
int totalReports = plugin.getDatabaseManager().getTotalReportCount();
|
||||
int pageSize = plugin.getConfig().getInt("gui.reports-per-page", 45);
|
||||
int totalPages = PaginationUtil.calculateTotalPages(totalReports, pageSize);
|
||||
if (gui.page < totalPages - 1) {
|
||||
new ReportGui(plugin, gui.page + 1).open(player);
|
||||
private void handleNextPage(Player player, ActionInventory gui) {
|
||||
if (gui.getPage() < gui.getTotalPages() - 1) {
|
||||
gui.openPage(player, gui.getPage() + 1);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleClose(Player player, ReportGui gui) {
|
||||
if (gui.detailView) {
|
||||
new ReportGui(plugin, gui.page).open(player);
|
||||
private void handleClose(Player player, ActionInventory gui) {
|
||||
if (gui instanceof ReportGui && gui.isDetailView()) {
|
||||
gui.openPage(player, gui.getPage());
|
||||
} else {
|
||||
player.closeInventory();
|
||||
}
|
||||
}
|
||||
|
||||
private void handleTeleport(Player player, ReportGui gui) {
|
||||
Report report = gui.currentReport;
|
||||
private void handleBack(Player player, ActionInventory gui) {
|
||||
if (!(gui instanceof AnticheatGui anticheatGui)) {
|
||||
return;
|
||||
}
|
||||
if (anticheatGui.isDetailView()) {
|
||||
anticheatGui.openPage(player, anticheatGui.getPage());
|
||||
} else {
|
||||
new ReportGui(plugin, 0).open(player);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleTeleport(Player player, ActionInventory gui) {
|
||||
if (!(gui instanceof ReportGui reportGui)) {
|
||||
return;
|
||||
}
|
||||
Report report = reportGui.getCurrentReport();
|
||||
if (report == null) {
|
||||
return;
|
||||
}
|
||||
Player target = Bukkit.getPlayer(report.targetUuid());
|
||||
if (target != null && target.isOnline()) {
|
||||
player.teleport(target.getLocation());
|
||||
player.sendMessage(plugin.getConfigManager().getMessage("teleported-to", "%player%", report.targetName()));
|
||||
} else {
|
||||
player.sendMessage(plugin.getConfigManager().getMessage("player-offline", "%player%", report.targetName()));
|
||||
// Folia-safe: cross-region teleports must go through the async scheduler
|
||||
player.teleportAsync(target.getLocation());
|
||||
player.sendMessage(plugin.getConfigManager().getMessage("teleported-to", "%player%", report.targetName()));
|
||||
} else {
|
||||
player.sendMessage(plugin.getConfigManager().getMessage("player-offline", "%player%", report.targetName()));
|
||||
}
|
||||
}
|
||||
|
||||
private void handleScreenshot(Player player, ReportGui gui) {
|
||||
Report report = gui.currentReport;
|
||||
private void handleScreenshot(Player player, ActionInventory gui) {
|
||||
if (!(gui instanceof ReportGui reportGui)) {
|
||||
return;
|
||||
}
|
||||
Report report = reportGui.getCurrentReport();
|
||||
if (report != null && report.imageUrl() != null && !report.imageUrl().isEmpty()) {
|
||||
player.sendMessage(plugin.getConfigManager().getMessage("screenshot-link", "%url%", report.imageUrl()));
|
||||
}
|
||||
}
|
||||
|
||||
private void handleDefaultAction(Player player, ReportGui gui, String action) {
|
||||
private void handleDefaultAction(Player player, ActionInventory gui, String action) {
|
||||
if (gui instanceof AnticheatGui anticheatGui) {
|
||||
handleAnticheatAction(player, anticheatGui, action);
|
||||
} else if (gui instanceof ReportGui reportGui) {
|
||||
handleReportAction(player, reportGui, action);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleReportAction(Player player, ReportGui gui, String action) {
|
||||
if (action.startsWith("status_set:")) {
|
||||
handleStatusSet(player, gui, action.substring("status_set:".length()));
|
||||
} else if (action.startsWith("report_detail:")) {
|
||||
handleReportDetail(player, gui, action.substring("report_detail:".length()));
|
||||
} else if ("anticheat_open".equals(action)) {
|
||||
new AnticheatGui(plugin, 0).open(player);
|
||||
}
|
||||
}
|
||||
|
||||
private void handleAnticheatAction(Player player, AnticheatGui gui, String action) {
|
||||
if (action.startsWith("ac_detail:")) {
|
||||
handleAnticheatDetail(player, gui, action.substring("ac_detail:".length()));
|
||||
} else if ("open-reports".equals(action)) {
|
||||
new ReportGui(plugin, 0).open(player);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -124,9 +159,17 @@ public class GuiClickListener implements Listener {
|
|||
}
|
||||
}
|
||||
|
||||
private void handleAnticheatDetail(Player player, AnticheatGui gui, String uuidStr) {
|
||||
try {
|
||||
UUID playerUuid = UUID.fromString(uuidStr);
|
||||
new AnticheatGui(plugin, gui.getPage()).openDetail(player, playerUuid, gui.getPlayerName(playerUuid));
|
||||
} catch (IllegalArgumentException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
@EventHandler
|
||||
public void onInventoryDrag(InventoryDragEvent event) {
|
||||
if (event.getInventory().getHolder() instanceof ReportGui) {
|
||||
if (event.getInventory().getHolder() instanceof ActionInventory) {
|
||||
event.setCancelled(true);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,6 @@ import org.bukkit.OfflinePlayer;
|
|||
import org.bukkit.enchantments.Enchantment;
|
||||
import org.bukkit.entity.Player;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.bukkit.inventory.ItemFlag;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
|
|
@ -22,7 +21,7 @@ import java.util.HashMap;
|
|||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public class ReportGui implements InventoryHolder {
|
||||
public class ReportGui implements ActionInventory {
|
||||
|
||||
public static final int INVENTORY_SIZE = 54;
|
||||
|
||||
|
|
@ -315,6 +314,7 @@ public class ReportGui implements InventoryHolder {
|
|||
.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));
|
||||
}
|
||||
|
||||
|
|
@ -349,6 +349,23 @@ public class ReportGui implements InventoryHolder {
|
|||
return currentReport;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<Integer, String> slotActions() {
|
||||
return slotActions;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void openPage(Player player, int page) {
|
||||
new ReportGui(plugin, page).open(player);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getTotalPages() {
|
||||
int pageSize = plugin.getConfig().getInt("gui.reports-per-page", 45);
|
||||
int totalReports = plugin.getDatabaseManager().getTotalReportCount();
|
||||
return PaginationUtil.calculateTotalPages(totalReports, pageSize);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Inventory getInventory() {
|
||||
return inventory;
|
||||
|
|
|
|||
|
|
@ -125,7 +125,7 @@ public class DiscordWebhook {
|
|||
|
||||
JsonObject reasonField = new JsonObject();
|
||||
reasonField.addProperty("name", "\uD83D\uDCCB Причина");
|
||||
reasonField.addProperty("value", report.reason());
|
||||
reasonField.addProperty("value", stripLegacyColors(report.reason()));
|
||||
reasonField.addProperty("inline", false);
|
||||
fields.add(reasonField);
|
||||
|
||||
|
|
@ -141,6 +141,12 @@ public class DiscordWebhook {
|
|||
timeField.addProperty("inline", true);
|
||||
fields.add(timeField);
|
||||
|
||||
JsonObject serverField = new JsonObject();
|
||||
serverField.addProperty("name", "\uD83D\uDDA5 \u0421\u0435\u0440\u0432\u0435\u0440");
|
||||
serverField.addProperty("value", report.serverName() != null ? report.serverName() : "unknown");
|
||||
serverField.addProperty("inline", true);
|
||||
fields.add(serverField);
|
||||
|
||||
embed.add("fields", fields);
|
||||
|
||||
if (report.imageUrl() != null && !report.imageUrl().isEmpty()) {
|
||||
|
|
@ -222,6 +228,26 @@ public class DiscordWebhook {
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Strips legacy paragraph-sign color codes so colorized GUI-only text (for
|
||||
* example the appended anticheat summary) stays readable in Discord embeds.
|
||||
*/
|
||||
private static String stripLegacyColors(String text) {
|
||||
if (text == null) {
|
||||
return "";
|
||||
}
|
||||
StringBuilder stripped = new StringBuilder(text.length());
|
||||
for (int i = 0; i < text.length(); i++) {
|
||||
char c = text.charAt(i);
|
||||
if (c == '§' && i + 1 < text.length()) {
|
||||
i++; // skip the color code character itself
|
||||
continue;
|
||||
}
|
||||
stripped.append(c);
|
||||
}
|
||||
return stripped.toString();
|
||||
}
|
||||
|
||||
private String escapeJson(String text) {
|
||||
if (text == null) {
|
||||
return "";
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
# Discord webhook URL for report notifications
|
||||
webhook-url: ""
|
||||
|
||||
# Network node this server reports from; stored in reports and shown in the GUI/Discord (e.g. hub, hide, games)
|
||||
server-name: "unknown"
|
||||
|
||||
# Database configuration
|
||||
database:
|
||||
# Database type: "sqlite" or "postgresql"
|
||||
|
|
@ -19,6 +22,17 @@ database:
|
|||
password: "password"
|
||||
pool-size: 10
|
||||
|
||||
# ServGuard anticheat integration (reads the guard.violations table from the database above)
|
||||
anticheat:
|
||||
# Append an anticheat flag summary to new report reasons
|
||||
enabled: true
|
||||
# Hours of violation history to consider
|
||||
lookback-hours: 72
|
||||
# Maximum distinct checks listed in the report summary
|
||||
summary-max-checks: 5
|
||||
# Maximum total flags represented in the report summary
|
||||
summary-max-flags: 50
|
||||
|
||||
# GUI settings
|
||||
gui:
|
||||
# Reports per page in GUI
|
||||
|
|
@ -70,6 +84,7 @@ gui:
|
|||
- "&eReason: &f%reason%"
|
||||
- "&eTime: &f%time%"
|
||||
- "&eStatus: &f%status%"
|
||||
- "&eServer: &f%server%"
|
||||
- "&7"
|
||||
- "&eReports: &c%report_count%"
|
||||
slots: []
|
||||
|
|
@ -116,6 +131,51 @@ gui:
|
|||
lore: []
|
||||
slots: []
|
||||
glowing: false
|
||||
anticheat-tab:
|
||||
material: REDSTONE
|
||||
custom-model-data: -1
|
||||
name: "&cAnticheat"
|
||||
lore: []
|
||||
slots: [46]
|
||||
glowing: false
|
||||
anticheat-entry:
|
||||
material: PLAYER_HEAD
|
||||
custom-model-data: -1
|
||||
name: "&c%player_name%"
|
||||
lore:
|
||||
- "&7"
|
||||
- "&eFlags (%hours%h): &c%flag_count%"
|
||||
- "&eLast flag: &f%last_flag%"
|
||||
- "&7"
|
||||
- "&eReports: &c%report_count%"
|
||||
slots: []
|
||||
glowing: false
|
||||
anticheat-detail:
|
||||
material: PLAYER_HEAD
|
||||
custom-model-data: -1
|
||||
name: "&c%player_name%"
|
||||
lore:
|
||||
- "&7"
|
||||
- "&eReports: &c%report_count%"
|
||||
- "&7Recent flags (%hours%h):"
|
||||
- "&8- &f%check% &7(%server%, %time%) &8%detail%"
|
||||
slots: []
|
||||
glowing: false
|
||||
anticheat-reports:
|
||||
material: BOOK
|
||||
custom-model-data: -1
|
||||
name: "&eOpen reports"
|
||||
lore: []
|
||||
slots: [49]
|
||||
glowing: false
|
||||
anticheat-page-info:
|
||||
material: PAPER
|
||||
custom-model-data: -1
|
||||
name: "&ePage %page% of %total%"
|
||||
lore:
|
||||
- "&7Flagged players: %total_players%"
|
||||
slots: [49]
|
||||
glowing: false
|
||||
|
||||
# Limits
|
||||
limits:
|
||||
|
|
@ -142,7 +202,7 @@ messages:
|
|||
self-report: "&cYou cannot report yourself!"
|
||||
player-not-found: "&cPlayer not found!"
|
||||
no-permission: "&cYou don't have permission!"
|
||||
usage: "&eUsage: /report <player> <reason> [screenshot_url] | /report gui | /report stats <player> | /report image <id> <url>"
|
||||
usage: "&eUsage: /report <player> <reason> [screenshot_url] | /report gui | /report stats <player> | /report image <id> <url> | /report ac"
|
||||
no-reports: "&eThis player has no reports."
|
||||
stats-header: "&6=== Report stats: %player% ==="
|
||||
stats-count: "&eTotal reports: &f%count%"
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@
|
|||
# General
|
||||
console-only: "&cThis command is for players only!"
|
||||
no-permission: "&cYou don't have permission to use this command!"
|
||||
usage: "&eUsage: /report <player> <reason> [screenshot_url] | /report gui | /report stats <player> | /report image <id> <url>"
|
||||
usage: "&eUsage: /report <player> <reason> [screenshot_url] | /report gui | /report stats <player> | /report image <id> <url> | /report ac"
|
||||
|
||||
# Reporting
|
||||
report-sent: "&aReport sent successfully!"
|
||||
|
|
@ -48,3 +48,10 @@ stats-last-online: "&eLast online: &f%time%"
|
|||
stats-report-entry: "&7- %reason% &8(%time% ago)"
|
||||
stats-recent-header: "&7Recent reports:"
|
||||
stats-more-reports: "&7... and %count% more reports"
|
||||
|
||||
# Anticheat (ServGuard)
|
||||
anticheat-summary: "&8[&cAC&8] &7flags %hours%h: %checks%"
|
||||
anticheat-unavailable: "&eAnticheat data is not available on this server."
|
||||
anticheat-list-title: "Anticheat - Page %page%"
|
||||
anticheat-detail-title: "&8Flags: %player_name%"
|
||||
anticheat-detail-empty: "&eNo recent flags for this player."
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ name: Loreport
|
|||
version: ${version}
|
||||
main: dev.loki.lorep.LorepPlugin
|
||||
api-version: '1.19'
|
||||
folia-supported: true
|
||||
author: loki5512344
|
||||
description: Modern player report system with Discord integration and GUI
|
||||
website: https://codeberg.org/loki5512344/Loreport
|
||||
|
|
@ -9,7 +10,7 @@ website: https://codeberg.org/loki5512344/Loreport
|
|||
commands:
|
||||
report:
|
||||
description: Report a player or manage reports
|
||||
usage: /report <player> <reason> [image_url] | /report gui | /report stats <player> | /report image <id> <url>
|
||||
usage: /report <player> <reason> [image_url] | /report gui | /report stats <player> | /report image <id> <url> | /report ac
|
||||
permission: lorep.report
|
||||
aliases: [rep, reports]
|
||||
|
||||
|
|
@ -18,7 +19,7 @@ permissions:
|
|||
description: Allows players to report other players
|
||||
default: true
|
||||
lorep.admin:
|
||||
description: Allows access to admin commands (gui, stats)
|
||||
description: Allows access to admin commands (gui, stats, image, ac)
|
||||
default: op
|
||||
lorep.*:
|
||||
description: Gives access to all Loreport permissions
|
||||
|
|
|
|||
|
|
@ -121,7 +121,8 @@ public class DatabaseManagerTest {
|
|||
String targetName = "Target_" + targetUuid.toString().substring(0, 8);
|
||||
Instant createdAt = Instant.now();
|
||||
|
||||
Report original = new Report(0, reporterUuid, reporterName, targetUuid, targetName, reason, null, "PENDING", createdAt);
|
||||
Report original = new Report(0, reporterUuid, reporterName, targetUuid, targetName, reason, null, "PENDING", createdAt,
|
||||
Report.UNKNOWN_SERVER);
|
||||
dbManager.saveReport(original);
|
||||
|
||||
// Close and reopen database
|
||||
|
|
@ -154,7 +155,7 @@ public class DatabaseManagerTest {
|
|||
Instant reportTime = Instant.now().minusSeconds(count - i);
|
||||
Report report = new Report(
|
||||
0, UUID.randomUUID(), "Reporter" + i, targetUuid, "Target",
|
||||
"Reason " + i, null, "PENDING", reportTime
|
||||
"Reason " + i, null, "PENDING", reportTime, Report.UNKNOWN_SERVER
|
||||
);
|
||||
dbManager.saveReport(report);
|
||||
}
|
||||
|
|
@ -220,4 +221,35 @@ public class DatabaseManagerTest {
|
|||
assertTrue(dbManager.getReportsForTarget(randomUuid).isEmpty());
|
||||
assertFalse(dbManager.hasReported(randomUuid, UUID.randomUUID()));
|
||||
}
|
||||
|
||||
/**
|
||||
* **Property: Server Attribution Persistence**
|
||||
* A report saved with a known server name SHALL be retrievable with the same
|
||||
* server name; reports created without one SHALL default to "unknown".
|
||||
*/
|
||||
@Test
|
||||
void serverNameRoundTrip() {
|
||||
UUID targetUuid = UUID.randomUUID();
|
||||
Report report = new Report(UUID.randomUUID(), "Reporter", targetUuid, "Target", "Test reason", null, "games");
|
||||
dbManager.saveReport(report);
|
||||
|
||||
List<Report> loaded = dbManager.getReportsForTarget(targetUuid);
|
||||
assertEquals(1, loaded.size());
|
||||
assertEquals("games", loaded.get(0).serverName());
|
||||
|
||||
UUID defaultTarget = UUID.randomUUID();
|
||||
dbManager.saveReport(new Report(UUID.randomUUID(), "Reporter", defaultTarget, "Target", "Test reason"));
|
||||
assertEquals(Report.UNKNOWN_SERVER, dbManager.getReportsForTarget(defaultTarget).get(0).serverName());
|
||||
}
|
||||
|
||||
/**
|
||||
* **Property: Anticheat Probe Safety**
|
||||
* A plain SQLite database has no guard.violations table, so the anticheat
|
||||
* availability probe SHALL report false instead of throwing.
|
||||
*/
|
||||
@Test
|
||||
void anticheatTableUnavailableOnSqlite() {
|
||||
assertFalse(dbManager.isAnticheatAvailable(),
|
||||
"guard.violations should not exist in a plain SQLite database");
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue