Upload folder via GUI - StatusAPI

This commit is contained in:
Git Manager GUI
2026-05-07 21:56:09 +02:00
parent 3b2218e37e
commit 417947c396
52 changed files with 12291 additions and 0 deletions

Binary file not shown.

107
StatusAPI/pom.xml Normal file
View File

@@ -0,0 +1,107 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.viper.bungee</groupId>
<artifactId>StatusAPI</artifactId>
<version>4.1.0</version>
<packaging>jar</packaging>
<name>StatusAPI</name>
<description>BungeeCord Status API Plugin</description>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- BungeeCord API direkt aus lokalem JAR, kein Repository noetig -->
<dependency>
<groupId>net.md-5</groupId>
<artifactId>bungeecord-api</artifactId>
<version>1.20</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/BungeeCord.jar</systemPath>
</dependency>
<!-- LuckPerms API (Optional) -->
<dependency>
<groupId>net.luckperms</groupId>
<artifactId>api</artifactId>
<version>5.4</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<!-- HikariCP Connection Pool (wird ins JAR gepackt) -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>5.1.0</version>
<scope>compile</scope>
</dependency>
<!-- MySQL JDBC Treiber (wird ins JAR gepackt) -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>9.1.0</version>
<scope>compile</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<id>central</id>
<url>https://repo.maven.apache.org/maven2</url>
</repository>
<repository>
<id>luckperms</id>
<url>https://repo.luckperms.net/releases/</url>
</repository>
</repositories>
<build>
<finalName>StatusAPI</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.5.0</version>
<executions>
<execution>
<phase>package</phase>
<goals><goal>shade</goal></goals>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<relocations>
<relocation>
<pattern>com.zaxxer.hikari</pattern>
<shadedPattern>net.viper.status.hikari</shadedPattern>
</relocation>
<relocation>
<pattern>com.mysql</pattern>
<shadedPattern>net.viper.status.mysql</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,142 @@
package net.viper.status;
import net.md_5.bungee.api.plugin.Plugin;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class UpdateChecker {
private final Plugin plugin;
private final String currentVersion;
private final int intervalHours;
// Neue Domain und korrekter API-Pfad für Releases
private final String apiUrl = "https://git.viper.ipv64.net/api/v1/repos/M_Viper/StatusAPI/releases";
private volatile String latestVersion = "";
private volatile String latestUrl = "";
private static final Pattern ASSET_NAME_PATTERN = Pattern.compile("\"name\"\\s*:\\s*\"([^\"]+)\"", Pattern.CASE_INSENSITIVE);
private static final Pattern DOWNLOAD_PATTERN = Pattern.compile("\"browser_download_url\"\\s*:\\s*\"([^\"]+)\"", Pattern.CASE_INSENSITIVE);
private static final Pattern TAG_NAME_PATTERN = Pattern.compile("\"tag_name\"\\s*:\\s*\"([^\"]+)\"", Pattern.CASE_INSENSITIVE);
public UpdateChecker(Plugin plugin, String currentVersion, int intervalHours) {
this.plugin = plugin;
this.currentVersion = currentVersion != null ? currentVersion : "0.0.0";
this.intervalHours = Math.max(1, intervalHours);
}
public void checkNow() {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(apiUrl).openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("User-Agent", "StatusAPI-UpdateChecker/2.0");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
int code = conn.getResponseCode();
if (code != 200) {
plugin.getLogger().warning("Gitea/Forgejo API nicht erreichbar (HTTP " + code + ")");
return;
}
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"))) {
String line;
while ((line = br.readLine()) != null) sb.append(line).append("\n");
}
String body = sb.toString();
// Neu: Da die API ein JSON-Array von Releases zurückgibt, nehmen wir das erste (neueste) Release
// Wir suchen den ersten Block mit tag_name
String foundVersion = null;
Matcher tagM = TAG_NAME_PATTERN.matcher(body);
if (tagM.find()) {
foundVersion = tagM.group(1).trim();
}
if (foundVersion == null) {
plugin.getLogger().warning("Keine Version (Tag) im Release gefunden.");
return;
}
if (foundVersion.startsWith("v") || foundVersion.startsWith("V")) {
foundVersion = foundVersion.substring(1);
}
String foundUrl = null;
// Wir suchen im gesamten Body nach der JAR-Datei "StatusAPI.jar"
// Da das neueste Release zuerst kommt, brechen wir ab, sobald wir eine passende JAR finden
Matcher nameMatcher = ASSET_NAME_PATTERN.matcher(body);
Matcher downloadMatcher = DOWNLOAD_PATTERN.matcher(body);
java.util.List<String> names = new java.util.ArrayList<>();
java.util.List<String> urls = new java.util.ArrayList<>();
while (nameMatcher.find()) {
names.add(nameMatcher.group(1));
}
while (downloadMatcher.find()) {
urls.add(downloadMatcher.group(1));
}
int pairs = Math.min(names.size(), urls.size());
for (int i = 0; i < pairs; i++) {
String name = names.get(i).trim();
String url = urls.get(i);
if ("StatusAPI.jar".equalsIgnoreCase(name)) {
foundUrl = url;
break; // Erste (also neueste) passende JAR nehmen
}
}
if (foundUrl == null) {
plugin.getLogger().warning("Keine StatusAPI.jar im neuesten Release gefunden.");
return;
}
latestVersion = foundVersion;
latestUrl = foundUrl;
} catch (Exception e) {
plugin.getLogger().log(Level.SEVERE, "Fehler beim Update-Check: " + e.getMessage(), e);
}
}
public String getLatestVersion() {
return latestVersion != null ? latestVersion : "";
}
public String getLatestUrl() {
return latestUrl != null ? latestUrl : "";
}
public boolean isUpdateAvailable(String currentVer) {
String lv = getLatestVersion();
if (lv.isEmpty()) return false;
return compareVersions(lv, currentVer) > 0;
}
private int compareVersions(String a, String b) {
try {
String[] aa = a.split("\\.");
String[] bb = b.split("\\.");
int len = Math.max(aa.length, bb.length);
for (int i = 0; i < len; i++) {
int ai = i < aa.length ? Integer.parseInt(aa[i].replaceAll("\\D", "")) : 0;
int bi = i < bb.length ? Integer.parseInt(bb[i].replaceAll("\\D", "")) : 0;
if (ai != bi) return Integer.compare(ai, bi);
}
return 0;
} catch (Exception ex) {
return a.compareTo(b);
}
}
}

View File

@@ -0,0 +1,24 @@
package net.viper.status.module;
import net.md_5.bungee.api.plugin.Plugin;
/**
* Interface für alle zukünftigen Erweiterungen.
*/
public interface Module {
/**
* Wird aufgerufen, wenn die API startet.
*/
void onEnable(Plugin plugin);
/**
* Wird aufgerufen, wenn die API stoppt.
*/
void onDisable(Plugin plugin);
/**
* Eindeutiger Name des Moduls (z.B. "StatsModule").
*/
String getName();
}

View File

@@ -0,0 +1,59 @@
package net.viper.status.module;
import net.md_5.bungee.api.plugin.Plugin;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Verwaltet alle geladenen Module.
* Verwendet LinkedHashMap um die Registrierungsreihenfolge zu erhalten,
* damit Abhängigkeiten (z.B. VanishModule → ChatModule) korrekt aufgelöst werden.
*/
public class ModuleManager {
private final Map<String, Module> modules = new LinkedHashMap<>();
public void registerModule(Module module) {
modules.put(module.getName().toLowerCase(), module);
}
public void enableAll(Plugin plugin) {
for (Module module : modules.values()) {
try {
module.onEnable(plugin);
} catch (Exception e) {
plugin.getLogger().severe("Fehler beim Aktivieren von Modul " + module.getName() + ": " + e.getMessage());
e.printStackTrace();
}
}
}
public void disableAll(Plugin plugin) {
for (Module module : modules.values()) {
try {
module.onDisable(plugin);
} catch (Exception e) {
plugin.getLogger().warning("Fehler beim Deaktivieren von Modul " + module.getName());
}
}
modules.clear();
}
/**
* Ermöglicht anderen Komponenten (wie dem WebServer) Zugriff auf spezifische Module.
*/
public Module getModule(String name) {
return modules.get(name.toLowerCase());
}
@SuppressWarnings("unchecked")
public <T extends Module> T getModule(Class<T> clazz) {
for (Module m : modules.values()) {
if (clazz.isInstance(m)) {
return (T) m;
}
}
return null;
}
}

View File

@@ -0,0 +1,132 @@
package net.viper.status.modules.AutoMessage;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.Plugin;
import net.viper.status.StatusAPI;
import net.viper.status.module.Module;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* AutoMessageModule
*
* Fix #5:
* - Nachrichten werden bei jedem Zyklus frisch aus der Datei gelesen,
* damit Änderungen an messages.txt sofort wirken ohne Neustart.
* - Neuer Befehl /automessage reload (Permission: statusapi.automessage)
* lädt die Konfiguration neu und setzt den Zähler zurück.
* - TextComponent.fromLegacy() → ChatColor.translateAlternateColorCodes für §-Codes.
*/
public class AutoMessageModule implements Module {
private int taskId = -1;
private StatusAPI api;
private final AtomicInteger currentIndex = new AtomicInteger(0);
// Konfiguration (für Reload zugänglich)
private volatile boolean enabled = false;
private volatile int intervalSeconds = 300;
private volatile String fileName = "messages.txt";
private volatile String prefix = "";
@Override
public String getName() { return "AutoMessage"; }
@Override
public void onEnable(Plugin plugin) {
this.api = (StatusAPI) plugin;
loadSettings();
if (!enabled) return;
registerReloadCommand();
scheduleTask();
}
@Override
public void onDisable(Plugin plugin) {
cancelTask();
}
private void loadSettings() {
Properties props = api.getVerifyProperties();
enabled = Boolean.parseBoolean(props.getProperty("automessage.enabled", "false"));
String rawInterval = props.getProperty("automessage.interval", "300");
try { intervalSeconds = Integer.parseInt(rawInterval); }
catch (NumberFormatException e) { api.getLogger().warning("Ungültiges Intervall für AutoMessage! Nutze Standard (300s)."); intervalSeconds = 300; }
fileName = props.getProperty("automessage.file", "messages.txt");
prefix = props.getProperty("automessage.prefix", "");
}
private void registerReloadCommand() {
ProxyServer.getInstance().getPluginManager().registerCommand(api, new Command("automessage", "statusapi.automessage") {
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length > 0 && "reload".equalsIgnoreCase(args[0])) {
cancelTask();
loadSettings();
currentIndex.set(0);
if (enabled) {
scheduleTask();
sender.sendMessage(ChatColor.GREEN + "[AutoMessage] Neu geladen. Intervall: " + intervalSeconds + "s");
} else {
sender.sendMessage(ChatColor.YELLOW + "[AutoMessage] Modul ist deaktiviert (automessage.enabled=false).");
}
} else {
sender.sendMessage(ChatColor.YELLOW + "/automessage reload");
}
}
});
}
private void scheduleTask() {
taskId = ProxyServer.getInstance().getScheduler().schedule(api, () -> {
File messageFile = new File(api.getDataFolder(), fileName);
if (!messageFile.exists()) {
api.getLogger().warning("[AutoMessage] Datei nicht gefunden: " + messageFile.getAbsolutePath());
return;
}
// Fix #5: Datei bei jedem Tick neu einlesen → Änderungen wirken sofort
List<String> messages;
try {
messages = Files.readAllLines(messageFile.toPath(), StandardCharsets.UTF_8);
} catch (IOException e) {
api.getLogger().severe("[AutoMessage] Fehler beim Lesen von '" + fileName + "': " + e.getMessage());
return;
}
messages.removeIf(line -> line.trim().isEmpty() || line.trim().startsWith("#"));
if (messages.isEmpty()) return;
// Index wrappen (threadsafe)
int idx = currentIndex.getAndUpdate(i -> (i + 1) % messages.size());
if (idx >= messages.size()) idx = 0;
String raw = messages.get(idx);
String prefixPart = prefix.isEmpty() ? "" : ChatColor.translateAlternateColorCodes('&', prefix) + " ";
// Fix: §-Codes direkt übersetzen (messages.txt nutzt §-Codes)
String text = prefixPart + ChatColor.translateAlternateColorCodes('&',
raw.replace("\u00a7", "&").replace("§", "&"));
ProxyServer.getInstance().broadcast(new TextComponent(text));
}, intervalSeconds, intervalSeconds, TimeUnit.SECONDS).getId();
}
private void cancelTask() {
if (taskId != -1) {
ProxyServer.getInstance().getScheduler().cancel(taskId);
taskId = -1;
}
}
}

View File

@@ -0,0 +1,840 @@
package net.viper.status.modules.antibot;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.PendingConnection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PreLoginEvent;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.event.EventHandler;
import net.viper.status.StatusAPI;
import net.viper.status.module.Module;
import net.viper.status.modules.network.NetworkInfoModule;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.nio.file.Files;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Date;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* Eigenständiger AntiBot/Attack-Guard.
*
* Fixes:
* - cleanupExpired() nutzt jetzt removeIf() statt Iteration + remove() (Bug #3)
* - applyProfileDefaults() setzt korrekten attackDefaultSource aus Config
*/
public class AntiBotModule implements Module, Listener {
private static final String CONFIG_FILE_NAME = "network-guard.properties";
private StatusAPI plugin;
private boolean enabled = true;
private String profile = "high-traffic";
private int maxCps = 120;
private int attackStartCps = 220;
private int attackStopCps = 120;
private int attackCalmSeconds = 20;
private int ipConnectionsPerMinute = 18;
private int ipBlockSeconds = 600;
private String kickMessage = "Zu viele Verbindungen von deiner IP. Bitte warte kurz.";
private boolean vpnCheckEnabled = false;
private boolean vpnBlockProxy = true;
private boolean vpnBlockHosting = true;
private int vpnCacheMinutes = 30;
private int vpnTimeoutMs = 2500;
private boolean securityLogEnabled = true;
private String securityLogFileName = "antibot-security.log";
private File securityLogFile;
private final Object securityLogLock = new Object();
private boolean learningModeEnabled = true;
private int learningScoreThreshold = 100;
private int learningDecayPerSecond = 2;
private int learningStateWindowSeconds = 120;
private int learningRapidWindowMs = 1500;
private int learningRapidPoints = 12;
private int learningIpRateExceededPoints = 30;
private int learningVpnProxyPoints = 40;
private int learningVpnHostingPoints = 30;
private int learningAttackModePoints = 12;
private int learningHighCpsPoints = 10;
private int learningRecentEventLimit = 30;
private final AtomicInteger currentSecondConnections = new AtomicInteger(0);
private volatile long currentSecond = System.currentTimeMillis() / 1000L;
private volatile int lastCps = 0;
private final AtomicInteger peakCps = new AtomicInteger(0);
private volatile boolean attackMode = false;
private volatile long attackCalmSince = 0L;
private final AtomicLong blockedConnectionsTotal = new AtomicLong(0L);
private final AtomicLong blockedConnectionsCurrentAttack = new AtomicLong(0L);
private final Set<String> blockedIpsCurrentAttack = ConcurrentHashMap.newKeySet();
private final Map<String, IpWindow> perIpWindows = new ConcurrentHashMap<>();
private final Map<String, Long> blockedIpsUntil = new ConcurrentHashMap<>();
private final Map<String, VpnCacheEntry> vpnCache = new ConcurrentHashMap<>();
private final Map<String, RecentPlayerIdentity> recentIdentityByIp = new ConcurrentHashMap<>();
private final Map<String, LearningProfile> learningProfiles = new ConcurrentHashMap<>();
private final Deque<String> learningRecentEvents = new ArrayDeque<>();
@Override
public String getName() { return "AntiBotModule"; }
@Override
public void onEnable(Plugin plugin) {
if (!(plugin instanceof StatusAPI)) return;
this.plugin = (StatusAPI) plugin;
ensureModuleConfigExists();
loadConfig();
ensureSecurityLogFile();
if (!enabled) {
this.plugin.getLogger().info("[AntiBotModule] deaktiviert via " + CONFIG_FILE_NAME);
return;
}
ProxyServer.getInstance().getPluginManager().registerListener(this.plugin, this);
ProxyServer.getInstance().getPluginManager().registerCommand(this.plugin, new AntiBotCommand());
ProxyServer.getInstance().getScheduler().schedule(this.plugin, this::tick, 1, 1, TimeUnit.SECONDS);
this.plugin.getLogger().info("[AntiBotModule] aktiviert. maxCps=" + maxCps
+ ", attackStartCps=" + attackStartCps + ", ip/min=" + ipConnectionsPerMinute);
}
@Override
public void onDisable(Plugin plugin) {
perIpWindows.clear();
blockedIpsUntil.clear();
vpnCache.clear();
learningProfiles.clear();
synchronized (learningRecentEvents) { learningRecentEvents.clear(); }
blockedIpsCurrentAttack.clear();
attackMode = false;
}
public boolean isEnabled() { return enabled; }
private void reloadRuntimeState() {
perIpWindows.clear();
blockedIpsUntil.clear();
vpnCache.clear();
learningProfiles.clear();
synchronized (learningRecentEvents) { learningRecentEvents.clear(); }
blockedIpsCurrentAttack.clear();
attackMode = false;
attackCalmSince = 0L;
blockedConnectionsCurrentAttack.set(0L);
currentSecondConnections.set(0);
lastCps = 0;
peakCps.set(0);
loadConfig();
ensureSecurityLogFile();
}
public Map<String, Object> buildSnapshot() {
Map<String, Object> out = new LinkedHashMap<>();
out.put("enabled", enabled);
out.put("profile", profile);
out.put("attack_mode", attackMode);
out.put("protection_enabled", enabled);
out.put("attack_mode_status", attackMode ? "active" : "normal");
out.put("attack_mode_display", attackMode ? "Angriff erkannt" : "Normalbetrieb");
out.put("status_message", enabled
? (attackMode ? "AntiBot aktiv: Angriff erkannt" : "AntiBot aktiv: kein Angriff erkannt")
: "AntiBot deaktiviert");
out.put("last_cps", lastCps);
out.put("peak_cps", peakCps.get());
out.put("blocked_ips_active", blockedIpsUntil.size());
out.put("blocked_connections_total", blockedConnectionsTotal.get());
out.put("vpn_check_enabled", vpnCheckEnabled);
out.put("learning_mode_enabled", learningModeEnabled);
out.put("learning_profiles", learningProfiles.size());
out.put("thresholds", buildThresholds());
return out;
}
private Map<String, Object> buildThresholds() {
Map<String, Object> m = new LinkedHashMap<>();
m.put("max_cps", maxCps);
m.put("attack_start_cps", attackStartCps);
m.put("attack_stop_cps", attackStopCps);
m.put("attack_calm_seconds", attackCalmSeconds);
m.put("ip_connections_per_minute", ipConnectionsPerMinute);
m.put("ip_block_seconds", ipBlockSeconds);
m.put("learning_score_threshold", learningScoreThreshold);
m.put("learning_decay_per_second", learningDecayPerSecond);
return m;
}
@EventHandler
public void onPreLogin(PreLoginEvent event) {
if (!enabled) return;
String ip = extractIp(event.getConnection());
if (ip == null || ip.isEmpty()) return;
cacheRecentIdentity(ip, event.getConnection(), System.currentTimeMillis());
recordConnection();
long now = System.currentTimeMillis();
// FIX #3: cleanupExpired verwendet removeIf statt Iteration+remove
cleanupExpired(now);
Long blockedUntil = blockedIpsUntil.get(ip);
if (blockedUntil != null && blockedUntil > now) {
logSecurityEvent("ip_block_active", ip, event.getConnection(), "blocked_until_ms=" + blockedUntil);
blockEvent(event);
return;
}
if (learningModeEnabled) {
evaluateLearningBaseline(ip, now);
Long learningBlock = blockedIpsUntil.get(ip);
if (learningBlock != null && learningBlock > now) {
blockEvent(event);
return;
}
}
boolean ipRateExceeded = isIpRateExceeded(ip, now);
if (ipRateExceeded) {
if (learningModeEnabled) {
int score = addLearningScore(ip, now, learningIpRateExceededPoints, "ip-rate-exceeded", true);
logSecurityEvent("ip_rate_exceeded_scored", ip, event.getConnection(), "score=" + score + ", threshold=" + learningScoreThreshold);
if (score >= learningScoreThreshold) {
logSecurityEvent("learning_threshold_block", ip, event.getConnection(), "reason=ip-rate-exceeded, score=" + score);
blockEvent(event);
return;
}
} else {
blockIp(ip, now);
logSecurityEvent("ip_rate_limit_block", ip, event.getConnection(), "mode=direct");
blockEvent(event);
return;
}
}
if (vpnCheckEnabled) {
VpnCheckResult info = getVpnInfo(ip, now);
if (info != null) {
boolean shouldBlock = (vpnBlockProxy && info.proxy) || (vpnBlockHosting && info.hosting);
if (shouldBlock) {
logSecurityEvent("vpn_detected", ip, event.getConnection(), "proxy=" + info.proxy + ", hosting=" + info.hosting);
if (learningModeEnabled) {
if (vpnBlockProxy && info.proxy) addLearningScore(ip, now, learningVpnProxyPoints, "vpn-proxy", false);
if (vpnBlockHosting && info.hosting) addLearningScore(ip, now, learningVpnHostingPoints, "vpn-hosting", false);
int current = getLearningScore(ip, now);
if (current >= learningScoreThreshold) {
blockIp(ip, now);
logSecurityEvent("learning_threshold_block", ip, event.getConnection(), "reason=vpn, score=" + current);
recordLearningEvent("BLOCK " + ip + " reason=vpn score=" + current);
blockEvent(event);
}
} else {
blockIp(ip, now);
logSecurityEvent("vpn_block", ip, event.getConnection(), "mode=direct, proxy=" + info.proxy + ", hosting=" + info.hosting);
blockEvent(event);
}
}
}
}
}
@EventHandler
public void onPostLogin(PostLoginEvent event) {
if (!enabled || event == null || event.getPlayer() == null) return;
ProxiedPlayer player = event.getPlayer();
String ip = extractIpFromPlayer(player);
if (ip == null || ip.isEmpty()) return;
cacheRecentIdentityDirect(ip, player.getName(), player.getUniqueId(), System.currentTimeMillis());
}
private void blockEvent(PreLoginEvent event) {
event.setCancelled(true);
}
private String extractIp(PendingConnection conn) {
if (conn == null || conn.getAddress() == null) return null;
if (conn.getAddress() instanceof InetSocketAddress) {
InetSocketAddress sa = (InetSocketAddress) conn.getAddress();
return sa.getAddress() != null ? sa.getAddress().getHostAddress() : sa.getHostString();
}
return String.valueOf(conn.getAddress());
}
private String extractIpFromPlayer(ProxiedPlayer player) {
if (player == null || player.getAddress() == null) return null;
if (player.getAddress() instanceof InetSocketAddress) {
InetSocketAddress sa = (InetSocketAddress) player.getAddress();
return sa.getAddress() != null ? sa.getAddress().getHostAddress() : sa.getHostString();
}
return String.valueOf(player.getAddress());
}
private void recordConnection() {
long sec = System.currentTimeMillis() / 1000L;
if (sec != currentSecond) {
synchronized (this) {
if (sec != currentSecond) {
currentSecond = sec;
currentSecondConnections.set(0);
}
}
}
currentSecondConnections.incrementAndGet();
}
private boolean isIpRateExceeded(String ip, long now) {
IpWindow window = perIpWindows.computeIfAbsent(ip, k -> new IpWindow(now));
synchronized (window) {
long diff = now - window.windowStart;
if (diff > 60_000L) {
window.windowStart = now;
window.count = 0;
}
window.count++;
return window.count > Math.max(1, ipConnectionsPerMinute);
}
}
private void blockIp(String ip, long now) {
blockedIpsUntil.put(ip, now + Math.max(1, ipBlockSeconds) * 1000L);
blockedConnectionsTotal.incrementAndGet();
if (attackMode) {
blockedConnectionsCurrentAttack.incrementAndGet();
blockedIpsCurrentAttack.add(ip);
}
}
/**
* FIX #3: Verwendet removeIf() statt for-each + remove() um ConcurrentModificationException zu vermeiden.
*/
private void cleanupExpired(long now) {
blockedIpsUntil.entrySet().removeIf(e -> e.getValue() <= now);
vpnCache.entrySet().removeIf(e -> e.getValue().expiresAt <= now);
recentIdentityByIp.entrySet().removeIf(e -> {
RecentPlayerIdentity id = e.getValue();
return id == null || (now - id.updatedAtMs) > 600_000L;
});
if (learningModeEnabled) {
long staleAfter = Math.max(60, learningStateWindowSeconds) * 1000L;
learningProfiles.entrySet().removeIf(e -> {
LearningProfile lp = e.getValue();
return lp == null || ((now - lp.lastSeenAt) > staleAfter && lp.score <= 0);
});
}
}
private void tick() {
if (!enabled) return;
int cps = currentSecondConnections.getAndSet(0);
lastCps = cps;
if (cps > peakCps.get()) peakCps.set(cps);
long now = System.currentTimeMillis();
if (!attackMode && cps >= Math.max(1, attackStartCps)) {
attackMode = true;
attackCalmSince = 0L;
blockedConnectionsCurrentAttack.set(0L);
blockedIpsCurrentAttack.clear();
sendAttackToWebhook("detected", cps, null, null, "StatusAPI AntiBot");
plugin.getLogger().warning("[AntiBotModule] Attack erkannt. CPS=" + cps);
return;
}
if (attackMode) {
if (cps <= Math.max(1, attackStopCps)) {
if (attackCalmSince == 0L) attackCalmSince = now;
long calmFor = now - attackCalmSince;
if (calmFor >= Math.max(1, attackCalmSeconds) * 1000L) {
attackMode = false;
attackCalmSince = 0L;
int blockedIps = blockedIpsCurrentAttack.size();
long blockedConns = blockedConnectionsCurrentAttack.get();
sendAttackToWebhook("stopped", cps, blockedIps, blockedConns, "StatusAPI AntiBot");
plugin.getLogger().warning("[AntiBotModule] Attack beendet. blockedIps=" + blockedIps + ", blockedConnections=" + blockedConns);
}
} else {
attackCalmSince = 0L;
}
}
}
private void sendAttackToWebhook(String type, Integer cps, Integer blockedIps, Long blockedConnections, String source) {
NetworkInfoModule networkInfoModule = getNetworkInfoModule();
if (networkInfoModule == null) return;
networkInfoModule.sendAttackNotification(type, cps, blockedIps, blockedConnections, source);
}
private NetworkInfoModule getNetworkInfoModule() {
if (plugin == null || plugin.getModuleManager() == null) return null;
return (NetworkInfoModule) plugin.getModuleManager().getModule("NetworkInfoModule");
}
private void loadConfig() {
File file = new File(plugin.getDataFolder(), CONFIG_FILE_NAME);
if (!file.exists()) return;
Properties props = new Properties();
try (FileInputStream in = new FileInputStream(file)) {
props.load(new InputStreamReader(in, StandardCharsets.UTF_8));
enabled = parseBoolean(props.getProperty("antibot.enabled"), true);
profile = normalizeProfile(props.getProperty("antibot.profile", "high-traffic"));
applyProfileDefaults(profile);
maxCps = parseInt(props.getProperty("antibot.max_cps"), maxCps);
attackStartCps = parseInt(props.getProperty("antibot.attack.start_cps"), attackStartCps);
attackStopCps = parseInt(props.getProperty("antibot.attack.stop_cps"), attackStopCps);
attackCalmSeconds = parseInt(props.getProperty("antibot.attack.stop_grace_seconds"), attackCalmSeconds);
ipConnectionsPerMinute = parseInt(props.getProperty("antibot.ip.max_connections_per_minute"), ipConnectionsPerMinute);
ipBlockSeconds = parseInt(props.getProperty("antibot.ip.block_seconds"), ipBlockSeconds);
kickMessage = props.getProperty("antibot.kick_message", kickMessage);
vpnCheckEnabled = parseBoolean(props.getProperty("antibot.vpn_check.enabled"), vpnCheckEnabled);
vpnBlockProxy = parseBoolean(props.getProperty("antibot.vpn_check.block_proxy"), vpnBlockProxy);
vpnBlockHosting = parseBoolean(props.getProperty("antibot.vpn_check.block_hosting"), vpnBlockHosting);
vpnCacheMinutes = parseInt(props.getProperty("antibot.vpn_check.cache_minutes"), vpnCacheMinutes);
vpnTimeoutMs = parseInt(props.getProperty("antibot.vpn_check.timeout_ms"), vpnTimeoutMs);
securityLogEnabled = parseBoolean(props.getProperty("antibot.security_log.enabled"), securityLogEnabled);
securityLogFileName = props.getProperty("antibot.security_log.file", securityLogFileName).trim();
if (securityLogFileName.isEmpty()) securityLogFileName = "antibot-security.log";
learningModeEnabled = parseBoolean(props.getProperty("antibot.learning.enabled"), learningModeEnabled);
learningScoreThreshold = parseInt(props.getProperty("antibot.learning.score_threshold"), learningScoreThreshold);
learningDecayPerSecond = parseInt(props.getProperty("antibot.learning.decay_per_second"), learningDecayPerSecond);
learningStateWindowSeconds = parseInt(props.getProperty("antibot.learning.state_window_seconds"), learningStateWindowSeconds);
learningRapidWindowMs = parseInt(props.getProperty("antibot.learning.rapid.window_ms"), learningRapidWindowMs);
learningRapidPoints = parseInt(props.getProperty("antibot.learning.rapid.points"), learningRapidPoints);
learningIpRateExceededPoints = parseInt(props.getProperty("antibot.learning.ip_rate_exceeded.points"), learningIpRateExceededPoints);
learningVpnProxyPoints = parseInt(props.getProperty("antibot.learning.vpn_proxy.points"), learningVpnProxyPoints);
learningVpnHostingPoints = parseInt(props.getProperty("antibot.learning.vpn_hosting.points"), learningVpnHostingPoints);
learningAttackModePoints = parseInt(props.getProperty("antibot.learning.attack_mode.points"), learningAttackModePoints);
learningHighCpsPoints = parseInt(props.getProperty("antibot.learning.high_cps.points"), learningHighCpsPoints);
learningRecentEventLimit = parseInt(props.getProperty("antibot.learning.recent_events.limit"), learningRecentEventLimit);
} catch (Exception e) {
plugin.getLogger().warning("[AntiBotModule] Fehler beim Laden von " + CONFIG_FILE_NAME + ": " + e.getMessage());
}
}
private String normalizeProfile(String raw) {
if (raw == null) return "high-traffic";
String v = raw.trim().toLowerCase(Locale.ROOT);
return "strict".equals(v) ? "strict" : "high-traffic";
}
private void applyProfileDefaults(String profileName) {
if ("strict".equals(profileName)) {
maxCps = 120; attackStartCps = 220; attackStopCps = 120; attackCalmSeconds = 20;
ipConnectionsPerMinute = 18; ipBlockSeconds = 900;
vpnCheckEnabled = true; vpnBlockProxy = true; vpnBlockHosting = true;
vpnCacheMinutes = 30; vpnTimeoutMs = 2500;
} else {
maxCps = 180; attackStartCps = 300; attackStopCps = 170; attackCalmSeconds = 25;
ipConnectionsPerMinute = 24; ipBlockSeconds = 600;
vpnCheckEnabled = false; vpnBlockProxy = true; vpnBlockHosting = true;
vpnCacheMinutes = 30; vpnTimeoutMs = 2500;
}
}
private boolean isSupportedProfile(String raw) {
if (raw == null) return false;
String v = raw.trim().toLowerCase(Locale.ROOT);
return "strict".equals(v) || "high-traffic".equals(v);
}
private boolean applyProfileAndPersist(String requestedProfile) {
if (!isSupportedProfile(requestedProfile)) return false;
String normalized = normalizeProfile(requestedProfile);
profile = normalized;
applyProfileDefaults(normalized);
Map<String, String> values = new LinkedHashMap<>();
values.put("antibot.profile", normalized);
values.put("antibot.max_cps", String.valueOf(maxCps));
values.put("antibot.attack.start_cps", String.valueOf(attackStartCps));
values.put("antibot.attack.stop_cps", String.valueOf(attackStopCps));
values.put("antibot.attack.stop_grace_seconds", String.valueOf(attackCalmSeconds));
values.put("antibot.ip.max_connections_per_minute", String.valueOf(ipConnectionsPerMinute));
values.put("antibot.ip.block_seconds", String.valueOf(ipBlockSeconds));
values.put("antibot.vpn_check.enabled", String.valueOf(vpnCheckEnabled));
values.put("antibot.vpn_check.block_proxy", String.valueOf(vpnBlockProxy));
values.put("antibot.vpn_check.block_hosting", String.valueOf(vpnBlockHosting));
values.put("antibot.vpn_check.cache_minutes", String.valueOf(vpnCacheMinutes));
values.put("antibot.vpn_check.timeout_ms", String.valueOf(vpnTimeoutMs));
try { updateConfigValues(values); return true; }
catch (Exception e) { plugin.getLogger().warning("[AntiBotModule] Konnte Profil nicht speichern: " + e.getMessage()); return false; }
}
private synchronized void updateConfigValues(Map<String, String> keyValues) throws Exception {
File target = new File(plugin.getDataFolder(), CONFIG_FILE_NAME);
List<String> lines = target.exists()
? Files.readAllLines(target.toPath(), StandardCharsets.UTF_8)
: new ArrayList<>();
for (Map.Entry<String, String> entry : keyValues.entrySet()) {
String key = entry.getKey();
String newLine = key + "=" + entry.getValue();
boolean replaced = false;
for (int i = 0; i < lines.size(); i++) {
if (lines.get(i).trim().startsWith(key + "=")) {
lines.set(i, newLine);
replaced = true;
break;
}
}
if (!replaced) lines.add(newLine);
}
Files.write(target.toPath(), lines, StandardCharsets.UTF_8);
}
private void ensureModuleConfigExists() {
File target = new File(plugin.getDataFolder(), CONFIG_FILE_NAME);
if (target.exists()) return;
if (!plugin.getDataFolder().exists()) plugin.getDataFolder().mkdirs();
try (InputStream in = plugin.getResourceAsStream(CONFIG_FILE_NAME);
FileOutputStream out = new FileOutputStream(target)) {
if (in == null) { plugin.getLogger().warning("[AntiBotModule] Standarddatei nicht im JAR."); return; }
byte[] buffer = new byte[4096]; int read;
while ((read = in.read(buffer)) != -1) out.write(buffer, 0, read);
} catch (Exception e) {
plugin.getLogger().warning("[AntiBotModule] Konnte Config nicht erstellen: " + e.getMessage());
}
}
private void evaluateLearningBaseline(String ip, long now) {
LearningProfile lp = learningProfiles.computeIfAbsent(ip, k -> new LearningProfile(now));
synchronized (lp) {
decayLearningProfile(lp, now);
long delta = now - lp.lastConnectionAt;
if (lp.lastConnectionAt > 0 && delta <= Math.max(250L, learningRapidWindowMs)) {
lp.rapidStreak++;
int points = learningRapidPoints + Math.min(lp.rapidStreak, 5);
lp.score += Math.max(1, points);
recordLearningEvent("IP=" + ip + " +" + points + " rapid-connect score=" + lp.score);
} else {
lp.rapidStreak = 0;
}
if (attackMode) { lp.score += Math.max(1, learningAttackModePoints); recordLearningEvent("IP=" + ip + " +" + learningAttackModePoints + " attack-mode score=" + lp.score); }
if (lastCps >= Math.max(1, maxCps)) { lp.score += Math.max(1, learningHighCpsPoints); recordLearningEvent("IP=" + ip + " +" + learningHighCpsPoints + " high-cps score=" + lp.score); }
lp.lastConnectionAt = now;
lp.lastSeenAt = now;
if (lp.score >= learningScoreThreshold) {
blockIp(ip, now);
recordLearningEvent("BLOCK " + ip + " reason=learning-threshold score=" + lp.score);
}
}
}
private int addLearningScore(String ip, long now, int points, String reason, boolean checkThreshold) {
LearningProfile lp = learningProfiles.computeIfAbsent(ip, k -> new LearningProfile(now));
synchronized (lp) {
decayLearningProfile(lp, now);
int add = Math.max(1, points);
lp.score += add;
lp.lastSeenAt = now;
recordLearningEvent("IP=" + ip + " +" + add + " " + reason + " score=" + lp.score);
if (checkThreshold && lp.score >= learningScoreThreshold) {
blockIp(ip, now);
recordLearningEvent("BLOCK " + ip + " reason=" + reason + " score=" + lp.score);
}
return lp.score;
}
}
private int getLearningScore(String ip, long now) {
LearningProfile lp = learningProfiles.get(ip);
if (lp == null) return 0;
synchronized (lp) { decayLearningProfile(lp, now); return lp.score; }
}
private void decayLearningProfile(LearningProfile lp, long now) {
long elapsedMs = Math.max(0L, now - lp.lastScoreUpdateAt);
if (elapsedMs > 0L) {
long decay = (elapsedMs / 1000L) * Math.max(0, learningDecayPerSecond);
if (decay > 0L) lp.score = (int) Math.max(0L, lp.score - decay);
lp.lastScoreUpdateAt = now;
}
long resetAfter = Math.max(30, learningStateWindowSeconds) * 1000L;
if (lp.lastSeenAt > 0L && now - lp.lastSeenAt > resetAfter) {
lp.score = 0;
lp.rapidStreak = 0;
}
}
private void recordLearningEvent(String event) {
String line = new SimpleDateFormat("HH:mm:ss").format(new Date()) + " " + event;
synchronized (learningRecentEvents) {
learningRecentEvents.addLast(line);
while (learningRecentEvents.size() > Math.max(5, learningRecentEventLimit)) learningRecentEvents.pollFirst();
}
}
private void ensureSecurityLogFile() {
if (plugin == null) return;
if (!plugin.getDataFolder().exists()) plugin.getDataFolder().mkdirs();
securityLogFile = new File(plugin.getDataFolder(), securityLogFileName);
try { if (!securityLogFile.exists()) securityLogFile.createNewFile(); }
catch (Exception e) { plugin.getLogger().warning("[AntiBotModule] Konnte Sicherheitslog nicht erstellen: " + e.getMessage()); }
}
private void logSecurityEvent(String eventType, String ip, PendingConnection conn, String details) {
if (!securityLogEnabled || plugin == null) return;
if (securityLogFile == null) { ensureSecurityLogFile(); if (securityLogFile == null) return; }
String name = extractPlayerName(conn);
String uuid = extractPlayerUuid(conn, name);
if ((name == null || name.isEmpty() || "unknown".equalsIgnoreCase(name)) && ip != null) {
RecentPlayerIdentity cached = recentIdentityByIp.get(ip);
if (cached != null) {
if (cached.playerName != null && !cached.playerName.trim().isEmpty()) name = cached.playerName;
if ((uuid == null || uuid.isEmpty()) && cached.playerUuid != null && !cached.playerUuid.trim().isEmpty()) uuid = cached.playerUuid;
}
}
if (name == null || name.trim().isEmpty()) name = "unknown";
if (uuid == null || uuid.trim().isEmpty()) uuid = "unknown";
String line = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())
+ " | event=" + safeLog(eventType)
+ " | ip=" + safeLog(ip)
+ " | player=" + safeLog(name)
+ " | uuid=" + safeLog(uuid)
+ " | details=" + safeLog(details);
synchronized (securityLogLock) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(securityLogFile, true))) {
bw.write(line); bw.newLine();
} catch (Exception e) {
plugin.getLogger().warning("[AntiBotModule] Sicherheitslog-Schreibfehler: " + e.getMessage());
}
}
}
private void cacheRecentIdentity(String ip, PendingConnection conn, long now) {
if (ip == null || ip.isEmpty() || conn == null) return;
String name = extractPlayerName(conn);
String uuid = extractPlayerUuid(conn, name);
if ((name == null || name.isEmpty()) && (uuid == null || uuid.isEmpty())) return;
RecentPlayerIdentity identity = recentIdentityByIp.computeIfAbsent(ip, k -> new RecentPlayerIdentity());
synchronized (identity) {
if (name != null && !name.trim().isEmpty()) identity.playerName = name.trim();
if (uuid != null && !uuid.trim().isEmpty()) identity.playerUuid = uuid.trim();
identity.updatedAtMs = now;
}
}
private void cacheRecentIdentityDirect(String ip, String playerName, UUID playerUuid, long now) {
if (ip == null || ip.isEmpty()) return;
String name = playerName == null ? "" : playerName.trim();
String uuid = playerUuid == null ? "" : playerUuid.toString();
if (name.isEmpty() && uuid.isEmpty()) return;
RecentPlayerIdentity identity = recentIdentityByIp.computeIfAbsent(ip, k -> new RecentPlayerIdentity());
synchronized (identity) {
if (!name.isEmpty()) identity.playerName = name;
if (!uuid.isEmpty()) identity.playerUuid = uuid;
identity.updatedAtMs = now;
}
}
private String extractPlayerName(PendingConnection conn) {
if (conn == null) return "";
try { String raw = conn.getName(); return raw == null ? "" : raw.trim(); } catch (Exception ignored) { return ""; }
}
private String extractPlayerUuid(PendingConnection conn, String playerName) {
if (conn != null) {
try { UUID uuid = conn.getUniqueId(); if (uuid != null) return uuid.toString(); } catch (Exception ignored) {}
}
if (playerName != null && !playerName.trim().isEmpty()) {
return UUID.nameUUIDFromBytes(("OfflinePlayer:" + playerName.trim()).getBytes(StandardCharsets.UTF_8)).toString();
}
return "";
}
private String safeLog(String input) {
if (input == null || input.isEmpty()) return "-";
return input.replace("\n", " ").replace("\r", " ").trim();
}
private List<String> getRecentLearningEvents(int max) {
List<String> out = new ArrayList<>();
synchronized (learningRecentEvents) {
int skip = Math.max(0, learningRecentEvents.size() - Math.max(1, max));
int idx = 0;
for (String line : learningRecentEvents) {
if (idx++ < skip) continue;
out.add(line);
}
}
return out;
}
private boolean parseBoolean(String s, boolean fallback) {
if (s == null) return fallback;
return Boolean.parseBoolean(s.trim());
}
private int parseInt(String s, int fallback) {
try { return Integer.parseInt(s == null ? "" : s.trim()); } catch (Exception ignored) { return fallback; }
}
private VpnCheckResult getVpnInfo(String ip, long now) {
VpnCacheEntry cached = vpnCache.get(ip);
if (cached != null && cached.expiresAt > now) return cached.result;
VpnCheckResult fresh = requestIpApi(ip);
if (fresh != null) {
VpnCacheEntry entry = new VpnCacheEntry();
entry.result = fresh;
entry.expiresAt = now + Math.max(1, vpnCacheMinutes) * 60_000L;
vpnCache.put(ip, entry);
}
return fresh;
}
private VpnCheckResult requestIpApi(String ip) {
HttpURLConnection conn = null;
try {
String url = "http://ip-api.com/json/" + ip + "?fields=status,proxy,hosting";
conn = (HttpURLConnection) new URL(url).openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(vpnTimeoutMs);
conn.setReadTimeout(vpnTimeoutMs);
conn.setRequestProperty("User-Agent", "StatusAPI-AntiBot/1.0");
if (conn.getResponseCode() < 200 || conn.getResponseCode() >= 300) return null;
StringBuilder sb = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
String line; while ((line = br.readLine()) != null) sb.append(line);
}
String json = sb.toString();
if (json.isEmpty() || !json.contains("\"status\":\"success\"")) return null;
VpnCheckResult result = new VpnCheckResult();
result.proxy = json.contains("\"proxy\":true");
result.hosting = json.contains("\"hosting\":true");
return result;
} catch (Exception ignored) { return null; }
finally { if (conn != null) conn.disconnect(); }
}
// --- Interne Klassen ---
private static class IpWindow {
long windowStart; int count;
IpWindow(long now) { this.windowStart = now; this.count = 0; }
}
private static class VpnCacheEntry { VpnCheckResult result; long expiresAt; }
private static class VpnCheckResult { boolean proxy; boolean hosting; }
private static class LearningProfile {
long lastConnectionAt, lastScoreUpdateAt, lastSeenAt;
int rapidStreak, score;
LearningProfile(long now) { lastConnectionAt = lastScoreUpdateAt = lastSeenAt = now; }
}
private static class RecentPlayerIdentity { String playerName; String playerUuid; long updatedAtMs; }
// --- Command ---
private class AntiBotCommand extends Command {
AntiBotCommand() { super("antibot", "statusapi.antibot"); }
@Override
public void execute(CommandSender sender, String[] args) {
if (!enabled) { sender.sendMessage(ChatColor.RED + "AntiBotModule ist deaktiviert."); return; }
if (args.length == 0 || "status".equalsIgnoreCase(args[0])) {
sender.sendMessage(ChatColor.GOLD + "----- AntiBot Status -----");
sender.sendMessage(ChatColor.YELLOW + "Schutz aktiv: " + ChatColor.WHITE + enabled);
sender.sendMessage(ChatColor.YELLOW + "Profil: " + ChatColor.WHITE + profile);
if (attackMode) sender.sendMessage(ChatColor.YELLOW + "Attack Mode: " + ChatColor.RED + "AKTIV");
else sender.sendMessage(ChatColor.YELLOW + "Attack Mode: " + ChatColor.GREEN + "Normal");
sender.sendMessage(ChatColor.YELLOW + "CPS: " + ChatColor.WHITE + lastCps + ChatColor.GRAY + " (Peak " + peakCps.get() + ")");
sender.sendMessage(ChatColor.YELLOW + "Schwellen: " + ChatColor.WHITE + "start " + attackStartCps + ChatColor.GRAY + " / " + ChatColor.WHITE + "stop " + attackStopCps + ChatColor.GRAY + " CPS");
sender.sendMessage(ChatColor.YELLOW + "Active IP Blocks: " + ChatColor.WHITE + blockedIpsUntil.size());
sender.sendMessage(ChatColor.YELLOW + "Total blocked connections: " + ChatColor.WHITE + blockedConnectionsTotal.get());
sender.sendMessage(ChatColor.YELLOW + "VPN Check: " + ChatColor.WHITE + vpnCheckEnabled);
sender.sendMessage(ChatColor.YELLOW + "Learning Mode: " + ChatColor.WHITE + learningModeEnabled
+ ChatColor.GRAY + " (threshold=" + learningScoreThreshold + ")");
List<String> recent = getRecentLearningEvents(3);
if (!recent.isEmpty()) {
sender.sendMessage(ChatColor.YELLOW + "Learning Events:");
for (String line : recent) sender.sendMessage(ChatColor.GRAY + "- " + line);
}
return;
}
if ("clearblocks".equalsIgnoreCase(args[0])) {
blockedIpsUntil.clear();
sender.sendMessage(ChatColor.GREEN + "Alle IP-Blocks wurden entfernt.");
return;
}
if ("unblock".equalsIgnoreCase(args[0]) && args.length >= 2) {
String ip = args[1].trim();
if (blockedIpsUntil.remove(ip) != null) sender.sendMessage(ChatColor.GREEN + "IP entblockt: " + ip);
else sender.sendMessage(ChatColor.RED + "IP war nicht geblockt: " + ip);
return;
}
if ("profile".equalsIgnoreCase(args[0])) {
if (args.length < 2) {
sender.sendMessage(ChatColor.YELLOW + "Aktuelles Profil: " + ChatColor.WHITE + profile);
sender.sendMessage(ChatColor.YELLOW + "Benutzung: /antibot profile <strict|high-traffic>");
return;
}
String requested = args[1].trim().toLowerCase(Locale.ROOT);
if (!isSupportedProfile(requested)) { sender.sendMessage(ChatColor.RED + "Unbekanntes Profil. Erlaubt: strict, high-traffic"); return; }
boolean ok = applyProfileAndPersist(requested);
if (!ok) { sender.sendMessage(ChatColor.RED + "Profil konnte nicht gespeichert werden."); return; }
sender.sendMessage(ChatColor.GREEN + "AntiBot-Profil umgestellt auf: " + requested);
sender.sendMessage(ChatColor.GRAY + "Werte wurden in " + CONFIG_FILE_NAME + " gespeichert.");
return;
}
if ("reload".equalsIgnoreCase(args[0])) {
reloadRuntimeState();
sender.sendMessage(ChatColor.GREEN + "AntiBot-Konfiguration neu geladen.");
sender.sendMessage(ChatColor.GRAY + "Aktives Profil: " + profile);
return;
}
sender.sendMessage(ChatColor.YELLOW + "/antibot status");
sender.sendMessage(ChatColor.YELLOW + "/antibot clearblocks");
sender.sendMessage(ChatColor.YELLOW + "/antibot unblock <ip>");
sender.sendMessage(ChatColor.YELLOW + "/antibot profile <strict|high-traffic>");
sender.sendMessage(ChatColor.YELLOW + "/antibot reload");
}
}
}

View File

@@ -0,0 +1,378 @@
package net.viper.status.modules.broadcast;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.plugin.Listener;
import net.viper.status.module.Module;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
/**
* BroadcastModule
*
* Fixes:
* - loadSchedules(): ID-Split nutzt jetzt indexOf/lastIndexOf statt split("\\.") mit length==2-Check.
* Damit werden auch clientScheduleIds die Punkte enthalten korrekt geladen. (Bug #2)
* - handleBroadcast(): &-Farbcodes werden jetzt auch in der Nachricht selbst übersetzt. (Bug #3)
* - handleBroadcast(): Literal \n in der Nachricht wird als echter Zeilenumbruch gerendert. (Bug #4)
* - handleBroadcast(): URLs (http/https) werden als anklickbare TextComponents eingebettet. (Bug #5)
*/
public class BroadcastModule implements Module, Listener {
private Plugin plugin;
private boolean enabled = true;
private String requiredApiKey = "";
private String format = "%prefix% %message%";
private String fallbackPrefix = "[Broadcast]";
private String fallbackPrefixColor = "&c";
private String fallbackBracketColor = "&8";
private String fallbackMessageColor = "&f";
private final Map<String, ScheduledBroadcast> scheduledByClientId = new ConcurrentHashMap<>();
private File schedulesFile;
private final SimpleDateFormat dateFormat;
public BroadcastModule() {
dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
}
@Override
public String getName() { return "BroadcastModule"; }
@Override
public void onEnable(Plugin plugin) {
this.plugin = plugin;
schedulesFile = new File(plugin.getDataFolder(), "broadcasts.schedules");
loadConfig();
if (!enabled) return;
try { plugin.getProxy().getPluginManager().registerListener(plugin, this); } catch (Throwable ignored) {}
plugin.getLogger().info("[BroadcastModule] aktiviert. Format: " + format);
loadSchedules();
plugin.getProxy().getScheduler().schedule(plugin, this::processScheduled, 1, 1, TimeUnit.SECONDS);
}
@Override
public void onDisable(Plugin plugin) {
saveSchedules();
scheduledByClientId.clear();
}
private void loadConfig() {
File file = new File(plugin.getDataFolder(), "verify.properties");
if (!file.exists()) return;
try (InputStream in = new FileInputStream(file)) {
Properties props = new Properties();
props.load(new InputStreamReader(in, StandardCharsets.UTF_8));
enabled = Boolean.parseBoolean(props.getProperty("broadcast.enabled", "true"));
requiredApiKey = props.getProperty("broadcast.api_key", "").trim();
format = props.getProperty("broadcast.format", format).trim();
if (format.isEmpty()) format = "%prefix% %message%";
fallbackPrefix = props.getProperty("broadcast.prefix", fallbackPrefix).trim();
fallbackPrefixColor = props.getProperty("broadcast.prefix-color", fallbackPrefixColor).trim();
fallbackBracketColor = props.getProperty("broadcast.bracket-color", fallbackBracketColor).trim();
fallbackMessageColor = props.getProperty("broadcast.message-color", fallbackMessageColor).trim();
} catch (IOException e) {
plugin.getLogger().warning("[BroadcastModule] Fehler beim Laden von verify.properties: " + e.getMessage());
}
}
public boolean handleBroadcast(String sourceName, String message, String type, String apiKeyHeader,
String prefix, String prefixColor, String bracketColor, String messageColor) {
loadConfig();
if (!enabled) return false;
if (requiredApiKey != null && !requiredApiKey.isEmpty()) {
if (apiKeyHeader == null || !requiredApiKey.equals(apiKeyHeader)) {
plugin.getLogger().warning("[BroadcastModule] Broadcast abgelehnt: API-Key fehlt oder inkorrekt.");
return false;
}
}
if (message == null) message = "";
if (sourceName == null || sourceName.isEmpty()) sourceName = "System";
if (type == null) type = "global";
String usedPrefix = (prefix != null && !prefix.trim().isEmpty()) ? prefix.trim() : fallbackPrefix;
String usedPrefixColor = (prefixColor != null && !prefixColor.trim().isEmpty()) ? prefixColor.trim() : fallbackPrefixColor;
String usedBracketColor = (bracketColor != null && !bracketColor.trim().isEmpty()) ? bracketColor.trim() : fallbackBracketColor;
String usedMessageColor = (messageColor != null && !messageColor.trim().isEmpty()) ? messageColor.trim() : fallbackMessageColor;
String prefixColorCode = normalizeColorCode(usedPrefixColor);
String bracketColorCode = normalizeColorCode(usedBracketColor);
String messageColorCode = normalizeColorCode(usedMessageColor);
String finalPrefix;
if (!bracketColorCode.isEmpty()) {
String textContent = usedPrefix;
if (textContent.startsWith("[")) textContent = textContent.substring(1);
if (textContent.endsWith("]")) textContent = textContent.substring(0, textContent.length() - 1);
finalPrefix = bracketColorCode + "[" + prefixColorCode + textContent + bracketColorCode + "]" + ChatColor.RESET;
} else {
finalPrefix = prefixColorCode + usedPrefix + ChatColor.RESET;
}
// FIX #1: &-Farbcodes auch in der Nachricht selbst übersetzen
String translatedMessage = ChatColor.translateAlternateColorCodes('&', message);
String coloredMessage = (messageColorCode.isEmpty() ? "" : messageColorCode) + translatedMessage;
String out = format
.replace("%name%", sourceName)
.replace("%prefix%", finalPrefix)
.replace("%prefixColored%", finalPrefix)
.replace("%message%", translatedMessage)
.replace("%messageColored%",coloredMessage)
.replace("%type%", type);
// FIX #2: \r entfernen (Windows CRLF -> nur LF), Literal \\n als Fallback
out = out.replace("\r\n", "\n").replace("\r", "").replace("\\n", "\n");
// FIX #3: Nachricht mit anklickbaren URLs aufbauen
BaseComponent[] components = buildClickableComponents(out);
int sent = 0;
for (ProxiedPlayer p : plugin.getProxy().getPlayers()) {
try { p.sendMessage(components); sent++; } catch (Throwable ignored) {}
}
plugin.getLogger().info("[BroadcastModule] Broadcast gesendet (Empfänger=" + sent + "): " + message);
return true;
}
/**
* Baut ein BaseComponent-Array aus einem formatierten String.
* URLs (http/https) werden als anklickbare TextComponents eingebettet.
* Unterstützt auch echte Newlines (\n) als Zeilenumbruch.
*/
private BaseComponent[] buildClickableComponents(String text) {
// Regex für URLs
java.util.regex.Pattern urlPattern = java.util.regex.Pattern.compile(
"(https?://[^\\s\\n]+)", java.util.regex.Pattern.CASE_INSENSITIVE);
ComponentBuilder builder = new ComponentBuilder("");
// Zeilenweise aufteilen (echte \n)
String[] lines = text.split("\n", -1);
for (int li = 0; li < lines.length; li++) {
if (li > 0) {
// Zeilenumbruch als eigene Komponente
builder.append(TextComponent.fromLegacyText("\n"));
}
String line = lines[li];
java.util.regex.Matcher matcher = urlPattern.matcher(line);
int lastEnd = 0;
while (matcher.find()) {
// Text vor der URL (mit Minecraft-Farbcodes)
if (matcher.start() > lastEnd) {
String before = line.substring(lastEnd, matcher.start());
builder.append(TextComponent.fromLegacyText(before));
}
// URL selbst: anklickbar + unterstrichen
String url = matcher.group(1);
TextComponent urlComponent = new TextComponent(url);
urlComponent.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url));
// Farbe der URL auf Cyan setzen damit sie sich abhebt
urlComponent.setColor(ChatColor.AQUA);
urlComponent.setUnderlined(true);
builder.append(urlComponent, ComponentBuilder.FormatRetention.NONE);
lastEnd = matcher.end();
}
// Restlicher Text nach der letzten URL
if (lastEnd < line.length()) {
builder.append(TextComponent.fromLegacyText(line.substring(lastEnd)));
}
}
return builder.create();
}
private String normalizeColorCode(String code) {
if (code == null) return "";
code = code.trim();
if (code.isEmpty()) return "";
return code.contains("&") ? ChatColor.translateAlternateColorCodes('&', code) : code;
}
private void saveSchedules() {
Properties props = new Properties();
for (Map.Entry<String, ScheduledBroadcast> entry : scheduledByClientId.entrySet()) {
String id = entry.getKey();
ScheduledBroadcast sb = entry.getValue();
// Wir escapen den ID-Wert damit Punkte in der ID nicht den Parser verwirren
props.setProperty(id + ".nextRunMillis", String.valueOf(sb.nextRunMillis));
props.setProperty(id + ".sourceName", sb.sourceName);
props.setProperty(id + ".message", sb.message);
props.setProperty(id + ".type", sb.type);
props.setProperty(id + ".prefix", sb.prefix);
props.setProperty(id + ".prefixColor", sb.prefixColor);
props.setProperty(id + ".bracketColor", sb.bracketColor);
props.setProperty(id + ".messageColor", sb.messageColor);
props.setProperty(id + ".recur", sb.recur);
}
try (OutputStream out = new FileOutputStream(schedulesFile)) {
props.store(out, "PulseCast Scheduled Broadcasts");
} catch (IOException e) {
plugin.getLogger().severe("[BroadcastModule] Konnte Schedules nicht speichern: " + e.getMessage());
}
}
/**
* FIX #2: Robusteres Parsen der Property-Keys.
* Statt split("\\.") mit length==2-Check nutzen wir lastIndexOf('.') um den letzten
* Punkt als Trenner zu verwenden. Damit funktionieren auch IDs die Punkte enthalten.
*
* Bekannte Felder: nextRunMillis, sourceName, message, type, prefix, prefixColor,
* bracketColor, messageColor, recur → alle ohne Punkte im Namen.
*/
private void loadSchedules() {
if (!schedulesFile.exists()) return;
Properties props = new Properties();
try (InputStream in = new FileInputStream(schedulesFile)) {
props.load(in);
} catch (IOException e) {
plugin.getLogger().severe("[BroadcastModule] Konnte Schedules nicht laden: " + e.getMessage());
return;
}
// Bekannte Feld-Suffixe
Set<String> knownFields = new HashSet<>(Arrays.asList(
"nextRunMillis", "sourceName", "message", "type",
"prefix", "prefixColor", "bracketColor", "messageColor", "recur"
));
Map<String, ScheduledBroadcast> loaded = new LinkedHashMap<>();
for (String key : props.stringPropertyNames()) {
// Finde das letzte '.' das einen bekannten Feldnamen abtrennt
int lastDot = key.lastIndexOf('.');
if (lastDot < 0) continue;
String field = key.substring(lastDot + 1);
if (!knownFields.contains(field)) continue;
String id = key.substring(0, lastDot);
if (id.isEmpty()) continue;
String value = props.getProperty(key);
ScheduledBroadcast sb = loaded.computeIfAbsent(id,
k -> new ScheduledBroadcast(k, 0, "", "", "", "", "", "", "", ""));
switch (field) {
case "nextRunMillis": try { sb.nextRunMillis = Long.parseLong(value); } catch (NumberFormatException ignored) {} break;
case "sourceName": sb.sourceName = value; break;
case "message": sb.message = value; break;
case "type": sb.type = value; break;
case "prefix": sb.prefix = value; break;
case "prefixColor": sb.prefixColor = value; break;
case "bracketColor": sb.bracketColor = value; break;
case "messageColor": sb.messageColor = value; break;
case "recur": sb.recur = value; break;
}
}
scheduledByClientId.putAll(loaded);
plugin.getLogger().info("[BroadcastModule] " + loaded.size() + " geplante Broadcasts aus Datei wiederhergestellt.");
}
public boolean scheduleBroadcast(long timestampMillis, String sourceName, String message, String type,
String apiKeyHeader, String prefix, String prefixColor, String bracketColor,
String messageColor, String recur, String clientScheduleId) {
loadConfig();
if (!enabled) return false;
if (requiredApiKey != null && !requiredApiKey.isEmpty()) {
if (apiKeyHeader == null || !requiredApiKey.equals(apiKeyHeader)) {
plugin.getLogger().warning("[BroadcastModule] schedule abgelehnt: API-Key fehlt oder inkorrekt.");
return false;
}
}
if (message == null) message = "";
if (sourceName == null || sourceName.isEmpty()) sourceName = "System";
if (type == null) type = "global";
if (recur == null) recur = "none";
String id = (clientScheduleId != null && !clientScheduleId.trim().isEmpty())
? clientScheduleId.trim() : UUID.randomUUID().toString();
long now = System.currentTimeMillis();
if (timestampMillis <= now) {
plugin.getLogger().warning("[BroadcastModule] Geplante Zeit in der Vergangenheit → sende sofort!");
return handleBroadcast(sourceName, message, type, apiKeyHeader, prefix, prefixColor, bracketColor, messageColor);
}
ScheduledBroadcast sb = new ScheduledBroadcast(id, timestampMillis, sourceName, message, type,
prefix, prefixColor, bracketColor, messageColor, recur);
scheduledByClientId.put(id, sb);
saveSchedules();
plugin.getLogger().info("[BroadcastModule] Neue geplante Nachricht registriert: " + id
+ " @ " + dateFormat.format(new Date(timestampMillis)));
return true;
}
public boolean cancelScheduled(String clientScheduleId) {
if (clientScheduleId == null || clientScheduleId.trim().isEmpty()) return false;
ScheduledBroadcast removed = scheduledByClientId.remove(clientScheduleId);
if (removed != null) { plugin.getLogger().info("[BroadcastModule] Schedule abgebrochen: " + clientScheduleId); saveSchedules(); return true; }
return false;
}
private void processScheduled() {
if (scheduledByClientId.isEmpty()) return;
long now = System.currentTimeMillis();
List<String> toRemove = new ArrayList<>();
boolean changed = false;
for (Map.Entry<String, ScheduledBroadcast> entry : scheduledByClientId.entrySet()) {
ScheduledBroadcast sb = entry.getValue();
if (sb.nextRunMillis <= now) {
plugin.getLogger().info("[BroadcastModule] ⏰ Sende geplante Nachricht (ID: " + entry.getKey() + ")");
handleBroadcast(sb.sourceName, sb.message, sb.type, "", sb.prefix, sb.prefixColor, sb.bracketColor, sb.messageColor);
if (!"none".equalsIgnoreCase(sb.recur)) {
long next = computeNextMillis(sb.nextRunMillis, sb.recur);
if (next > 0) { sb.nextRunMillis = next; changed = true; }
else { toRemove.add(entry.getKey()); changed = true; }
} else { toRemove.add(entry.getKey()); changed = true; }
}
}
if (changed || !toRemove.isEmpty()) {
for (String k : toRemove) { scheduledByClientId.remove(k); }
saveSchedules();
}
}
private long computeNextMillis(long currentMillis, String recur) {
switch (recur.toLowerCase(Locale.ROOT)) {
case "hourly": return currentMillis + TimeUnit.HOURS.toMillis(1);
case "daily": return currentMillis + TimeUnit.DAYS.toMillis(1);
case "weekly": return currentMillis + TimeUnit.DAYS.toMillis(7);
default: return -1L;
}
}
private static class ScheduledBroadcast {
final String clientId;
long nextRunMillis;
String sourceName, message, type, prefix, prefixColor, bracketColor, messageColor, recur;
ScheduledBroadcast(String clientId, long nextRunMillis, String sourceName, String message, String type,
String prefix, String prefixColor, String bracketColor, String messageColor, String recur) {
this.clientId = clientId;
this.nextRunMillis = nextRunMillis;
this.sourceName = sourceName;
this.message = message;
this.type = type;
this.prefix = prefix;
this.prefixColor = prefixColor;
this.bracketColor = bracketColor;
this.messageColor = messageColor;
this.recur = recur == null ? "none" : recur;
}
}
}

View File

@@ -0,0 +1,318 @@
package net.viper.status.modules.chat;
import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
/**
* Verwaltet die Verknüpfung von Minecraft-Accounts mit Discord/Telegram.
*
* Ablauf:
* 1. Spieler tippt /linkdiscord oder /linktelegram → Token wird generiert
* 2. Spieler schickt Token an den Bot
* 3. Bot-Polling erkennt Token → Verknüpfung wird gespeichert
*
* Speicherformat (chat_links.dat):
* minecraft:<uuid>|name:<spielername>|discord:<discord-user-id>|telegram:<telegram-user-id>
*/
public class AccountLinkManager {
private final File file;
private final Logger logger;
// UUID → verknüpfte Accounts
private final ConcurrentHashMap<UUID, LinkedAccount> links = new ConcurrentHashMap<>();
// Ausstehende Token: token → UUID (läuft nach 10 Min ab)
private final ConcurrentHashMap<String, PendingToken> pendingTokens = new ConcurrentHashMap<>();
public AccountLinkManager(File dataFolder, Logger logger) {
this.file = new File(dataFolder, "chat_links.dat");
this.logger = logger;
}
// ===== Datenklassen =====
public static class LinkedAccount {
public UUID minecraftUUID;
public String minecraftName;
public String discordUserId = ""; // leer = nicht verknüpft
public String telegramUserId = ""; // leer = nicht verknüpft
public String telegramUsername = ""; // @username für Anzeige
public String discordUsername = ""; // für Anzeige
}
private static class PendingToken {
UUID uuid;
String playerName;
String type; // "discord" oder "telegram"
long expiresAt; // Unix-Millis
PendingToken(UUID uuid, String playerName, String type) {
this.uuid = uuid;
this.playerName = playerName;
this.type = type;
this.expiresAt = System.currentTimeMillis() + (10 * 60 * 1000L); // 10 Min
}
boolean isExpired() {
return System.currentTimeMillis() > expiresAt;
}
}
// ===== Token-Generierung =====
/**
* Generiert einen neuen Verknüpfungs-Token für einen Spieler.
* Bestehende Token für denselben Spieler+Typ werden überschrieben.
*
* @param uuid UUID des Spielers
* @param playerName Anzeigename
* @param type "discord" oder "telegram"
* @return 6-stelliger alphanumerischer Token (z.B. "A3F9K2")
*/
public String generateToken(UUID uuid, String playerName, String type) {
// Alte Token für diesen Spieler+Typ entfernen
pendingTokens.entrySet().removeIf(e ->
e.getValue().uuid.equals(uuid) && e.getValue().type.equals(type));
// Abgelaufene Token bereinigen
pendingTokens.entrySet().removeIf(e -> e.getValue().isExpired());
String token;
do {
token = generateRandomToken();
} while (pendingTokens.containsKey(token));
pendingTokens.put(token, new PendingToken(uuid, playerName, type));
return token;
}
private String generateRandomToken() {
String chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; // ohne I,O,0,1 (Verwechslungsgefahr)
Random rnd = new Random();
StringBuilder sb = new StringBuilder(6);
for (int i = 0; i < 6; i++) sb.append(chars.charAt(rnd.nextInt(chars.length())));
return sb.toString();
}
// ===== Token einlösen =====
/**
* Versucht einen Token einzulösen (aufgerufen wenn Bot eine Nachricht empfängt).
*
* @param token Der eingesendete Token
* @param externalId Discord User-ID oder Telegram User-ID (als String)
* @param externalName Discord-Username oder Telegram-@username
* @return LinkedAccount wenn erfolgreich, null wenn Token ungültig/abgelaufen
*/
public LinkedAccount redeemToken(String token, String externalId, String externalName, String type) {
token = token.trim().toUpperCase();
PendingToken pending = pendingTokens.get(token);
if (pending == null || pending.isExpired()) {
pendingTokens.remove(token);
return null;
}
// Typ muss übereinstimmen
if (!pending.type.equals(type)) return null;
pendingTokens.remove(token);
// Bestehenden Account holen oder neu anlegen
LinkedAccount account = links.computeIfAbsent(pending.uuid, k -> {
LinkedAccount a = new LinkedAccount();
a.minecraftUUID = pending.uuid;
a.minecraftName = pending.playerName;
return a;
});
account.minecraftName = pending.playerName; // aktuell halten
if ("discord".equals(pending.type)) {
account.discordUserId = externalId;
account.discordUsername = externalName;
} else if ("telegram".equals(pending.type)) {
account.telegramUserId = externalId;
account.telegramUsername = externalName;
}
save();
return account;
}
// ===== Lookup =====
public LinkedAccount getByUUID(UUID uuid) {
return links.get(uuid);
}
public LinkedAccount getByDiscordId(String discordUserId) {
for (LinkedAccount a : links.values()) {
if (discordUserId.equals(a.discordUserId)) return a;
}
return null;
}
public LinkedAccount getByTelegramId(String telegramUserId) {
for (LinkedAccount a : links.values()) {
if (telegramUserId.equals(a.telegramUserId)) return a;
}
return null;
}
/** Gibt den Minecraft-Namen für eine Discord-User-ID zurück, oder null. */
public String getMinecraftNameByDiscordId(String discordUserId) {
LinkedAccount a = getByDiscordId(discordUserId);
return a != null ? a.minecraftName : null;
}
/** Gibt den Minecraft-Namen für eine Telegram-User-ID zurück, oder null. */
public String getMinecraftNameByTelegramId(String telegramUserId) {
LinkedAccount a = getByTelegramId(telegramUserId);
return a != null ? a.minecraftName : null;
}
/** Prüft ob ein Token gerade aussteht (für Tab-Complete etc.). */
public boolean hasPendingToken(UUID uuid, String type) {
for (PendingToken t : pendingTokens.values()) {
if (t.uuid.equals(uuid) && t.type.equals(type) && !t.isExpired()) return true;
}
return false;
}
// ===== Verknüpfung aufheben =====
public boolean unlinkDiscord(UUID uuid) {
LinkedAccount a = links.get(uuid);
if (a == null || a.discordUserId.isEmpty()) return false;
a.discordUserId = "";
a.discordUsername = "";
cleanupEmpty(uuid);
save();
return true;
}
public boolean unlinkTelegram(UUID uuid) {
LinkedAccount a = links.get(uuid);
if (a == null || a.telegramUserId.isEmpty()) return false;
a.telegramUserId = "";
a.telegramUsername = "";
cleanupEmpty(uuid);
save();
return true;
}
private void cleanupEmpty(UUID uuid) {
LinkedAccount a = links.get(uuid);
if (a != null && a.discordUserId.isEmpty() && a.telegramUserId.isEmpty()) {
links.remove(uuid);
}
}
// ===== Convenience-Methoden für Bridges =====
/**
* Löst einen Telegram-Token ein.
* Wrapper für redeemToken mit type="telegram".
*/
public LinkedAccount redeemTelegram(String token, String telegramUserId, String telegramUsername) {
return redeemToken(token, telegramUserId, telegramUsername, "telegram");
}
/**
* Löst einen Discord-Token ein.
* Wrapper für redeemToken mit type="discord".
*/
public LinkedAccount redeemDiscord(String token, String discordUserId, String discordUsername) {
return redeemToken(token, discordUserId, discordUsername, "discord");
}
/**
* Gibt den Anzeigenamen für einen Telegram-Nutzer zurück.
* Wenn verknüpft: "MinecraftName (@telegram)", sonst: "@telegram"
*/
public String resolveTelegramName(String telegramUserId, String fallbackName) {
String mc = getMinecraftNameByTelegramId(telegramUserId);
return mc != null ? mc : fallbackName;
}
/**
* Gibt den Anzeigenamen für einen Discord-Nutzer zurück.
* Wenn verknüpft: Minecraft-Name, sonst: Discord-Username
*/
public String resolveDiscordName(String discordUserId, String fallbackName) {
String mc = getMinecraftNameByDiscordId(discordUserId);
return mc != null ? mc : fallbackName;
}
/**
* Gibt das korrekte Format-String zurück abhängig ob Account verknüpft.
* linked=true → linkedFormat (mit {player}), false → unlinkedFormat (mit {user})
*/
public boolean isLinkedTelegram(String telegramUserId) {
return getByTelegramId(telegramUserId) != null;
}
public boolean isLinkedDiscord(String discordUserId) {
return getByDiscordId(discordUserId) != null;
}
// ===== Persistenz =====
public void save() {
try (BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))) {
for (LinkedAccount a : links.values()) {
bw.write(a.minecraftUUID
+ "|" + esc(a.minecraftName)
+ "|" + esc(a.discordUserId)
+ "|" + esc(a.discordUsername)
+ "|" + esc(a.telegramUserId)
+ "|" + esc(a.telegramUsername));
bw.newLine();
}
} catch (IOException e) {
logger.warning("[ChatModule] Fehler beim Speichern der Account-Links: " + e.getMessage());
}
}
public void load() {
links.clear();
if (!file.exists()) return;
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) continue;
String[] p = line.split("\\|", -1);
if (p.length < 6) continue;
try {
LinkedAccount a = new LinkedAccount();
a.minecraftUUID = UUID.fromString(p[0]);
a.minecraftName = unesc(p[1]);
a.discordUserId = unesc(p[2]);
a.discordUsername = unesc(p[3]);
a.telegramUserId = unesc(p[4]);
a.telegramUsername = unesc(p[5]);
if (!a.discordUserId.isEmpty() || !a.telegramUserId.isEmpty()) {
links.put(a.minecraftUUID, a);
}
} catch (Exception ignored) {}
}
} catch (IOException e) {
logger.warning("[ChatModule] Fehler beim Laden der Account-Links: " + e.getMessage());
}
}
private static String esc(String s) {
if (s == null) return "";
return s.replace("\\", "\\\\").replace("|", "\\p");
}
private static String unesc(String s) {
if (s == null) return "";
return s.replace("\\p", "|").replace("\\\\", "\\");
}
}

View File

@@ -0,0 +1,124 @@
package net.viper.status.modules.chat;
import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
/**
* Verwaltet den gegenseitigen Blockier-/Ignore-Status zwischen Spielern.
*
* Admins/OPs mit dem Bypass-Permission sind nicht blockierbar.
*
* Format der Speicherdatei:
* <blocker-uuid>|<blocked-uuid1>,<blocked-uuid2>,...
*/
public class BlockManager {
private final File file;
private final Logger logger;
// blocker UUID → Set der blockierten UUIDs
private final ConcurrentHashMap<UUID, Set<UUID>> blocked = new ConcurrentHashMap<>();
public BlockManager(File dataFolder, Logger logger) {
this.file = new File(dataFolder, "chat_blocked.dat");
this.logger = logger;
}
// ===== Block-Logik =====
/** Spieler `blocker` blockiert Spieler `target`. */
public void block(UUID blocker, UUID target) {
blocked.computeIfAbsent(blocker, k -> Collections.newSetFromMap(new ConcurrentHashMap<>()))
.add(target);
save();
}
/** Spieler `blocker` hebt den Block für `target` auf. */
public void unblock(UUID blocker, UUID target) {
Set<UUID> set = blocked.get(blocker);
if (set != null) {
set.remove(target);
if (set.isEmpty()) blocked.remove(blocker);
}
save();
}
/**
* Prüft ob `blocker` den Spieler `target` blockiert hat.
* Admins (isAdmin=true) sind niemals blockiert.
*/
public boolean isBlocked(UUID blocker, UUID target) {
Set<UUID> set = blocked.get(blocker);
return set != null && set.contains(target);
}
/**
* Prüft ob eine Nachricht von `sender` an `receiver` zugestellt werden soll.
* Gibt false zurück, wenn einer der beiden den anderen blockiert.
*/
public boolean canReceive(UUID sender, UUID receiver) {
// receiver hat sender blockiert → keine Nachricht
if (isBlocked(receiver, sender)) return false;
// sender hat receiver blockiert → keine Nachricht (Komfort)
if (isBlocked(sender, receiver)) return false;
return true;
}
/** Gibt alle UUIDs zurück, die `blocker` blockiert hat. */
public Set<UUID> getBlockedBy(UUID blocker) {
Set<UUID> set = blocked.get(blocker);
if (set == null) return Collections.emptySet();
return Collections.unmodifiableSet(set);
}
// ===== Persistenz =====
public void save() {
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))) {
for (Map.Entry<UUID, Set<UUID>> e : blocked.entrySet()) {
if (e.getValue().isEmpty()) continue;
StringBuilder sb = new StringBuilder();
sb.append(e.getKey()).append("|");
Iterator<UUID> it = e.getValue().iterator();
while (it.hasNext()) {
sb.append(it.next());
if (it.hasNext()) sb.append(",");
}
bw.write(sb.toString());
bw.newLine();
}
} catch (IOException e) {
logger.warning("[ChatModule] Fehler beim Speichern der Block-Liste: " + e.getMessage());
}
}
public void load() {
blocked.clear();
if (!file.exists()) return;
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) continue;
String[] parts = line.split("\\|", 2);
if (parts.length < 2) continue;
try {
UUID blocker = UUID.fromString(parts[0]);
Set<UUID> targets = Collections.newSetFromMap(new ConcurrentHashMap<>());
for (String rawUUID : parts[1].split(",")) {
rawUUID = rawUUID.trim();
if (!rawUUID.isEmpty()) {
try { targets.add(UUID.fromString(rawUUID)); }
catch (Exception ignored) {}
}
}
if (!targets.isEmpty()) blocked.put(blocker, targets);
} catch (Exception ignored) {}
}
} catch (IOException e) {
logger.warning("[ChatModule] Fehler beim Laden der Block-Liste: " + e.getMessage());
}
}
}

View File

@@ -0,0 +1,69 @@
package net.viper.status.modules.chat;
/**
* Repräsentiert einen Chat-Kanal mit allen zugehörigen Einstellungen.
*/
public class ChatChannel {
private final String id;
private final String name;
private final String symbol;
private final String permission;
private final String color;
private final String format;
private final boolean localOnly;
// Bridge-Einstellungen
private final String discordWebhook;
private final String discordChannelId;
private final String telegramChatId;
private final int telegramThreadId; // 0 = kein Thema, >0 = Themen-ID
private final boolean useAdminBridge;
public ChatChannel(String id, String name, String symbol, String permission,
String color, String format, boolean localOnly,
String discordWebhook, String discordChannelId,
String telegramChatId, int telegramThreadId, boolean useAdminBridge) {
this.id = id;
this.name = name;
this.symbol = symbol;
this.permission = permission;
this.color = color;
this.format = format;
this.localOnly = localOnly;
this.discordWebhook = discordWebhook;
this.discordChannelId = discordChannelId;
this.telegramChatId = telegramChatId;
this.telegramThreadId = telegramThreadId;
this.useAdminBridge = useAdminBridge;
}
public String getId() { return id; }
public String getName() { return name; }
public String getSymbol() { return symbol; }
public String getPermission() { return permission; }
public String getColor() { return color; }
public String getFormat() { return format; }
public boolean isLocalOnly() { return localOnly; }
public String getDiscordWebhook() { return discordWebhook; }
public String getDiscordChannelId() { return discordChannelId; }
public String getTelegramChatId() { return telegramChatId; }
public int getTelegramThreadId() { return telegramThreadId; }
public boolean isUseAdminBridge() { return useAdminBridge; }
/** Prüft ob der Kanal eine Permission erfordert. */
public boolean hasPermission() {
return permission != null && !permission.isEmpty();
}
/** Gibt das formatierte Kanalprefix zurück, z.B. §a[G] */
public String getFormattedTag() {
return net.md_5.bungee.api.ChatColor.translateAlternateColorCodes('&',
color + "[" + symbol + "]");
}
@Override
public String toString() {
return "ChatChannel{id=" + id + ", name=" + name + "}";
}
}

View File

@@ -0,0 +1,496 @@
package net.viper.status.modules.chat;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
/**
* Lädt und verwaltet die chat.yml Konfiguration.
*
* Fix #8: Rate-Limit-Werte aus anti-spam werden nicht mehr durch nachfolgende
* Berechnungen überschrieben. Der rate-limit.chat-Block hat jetzt Vorrang.
* Die Reihenfolge ist: erst rate-limit.chat einlesen, dann ggf. durch anti-spam
* als Fallback ergänzen, nicht umgekehrt.
*/
public class ChatConfig {
private final Plugin plugin;
private Configuration config;
private final Map<String, ChatChannel> channels = new LinkedHashMap<>();
private String defaultChannel;
private String helpopFormat, helpopPermission, helpopConfirm, helpopDiscordWebhook, helpopTelegramChatId;
private int helpopCooldown;
private String broadcastFormat, broadcastPermission;
private boolean pmEnabled;
private String pmFormatSender, pmFormatReceiver, pmFormatSpy, pmSpyPermission, pmRateLimitMessage;
private boolean pmRateLimitEnabled;
private long pmRateLimitWindowMs;
private int pmRateLimitMaxActions;
private long pmRateLimitBlockMs;
private int defaultMuteDuration;
private String mutedMessage;
private boolean emojiEnabled, emojiBedrockSupport;
private final Map<String, String> emojiMappings = new LinkedHashMap<>();
private boolean discordEnabled;
private String discordBotToken, discordGuildId, discordFromFormat, discordAdminChannelId, discordEmbedColor;
private int discordPollInterval;
private boolean telegramEnabled;
private String telegramBotToken, telegramFromFormat, telegramAdminChatId;
private int telegramPollInterval, telegramChatTopicId, telegramAdminTopicId;
private boolean linkingEnabled;
private String linkDiscordMessage, linkTelegramMessage, linkSuccessDiscord, linkSuccessTelegram;
private String linkBotSuccessDiscord, linkBotSuccessTelegram, linkedDiscordFormat, linkedTelegramFormat;
private int telegramAdminThreadId;
private String adminBypassPermission, adminNotifyPermission;
private boolean chatlogEnabled;
private int chatlogRetentionDays;
private final Map<String, String> serverColors = new LinkedHashMap<>();
private final Map<String, String> serverDisplayNames = new LinkedHashMap<>();
private String serverColorDefault;
private boolean reportsEnabled, reportWebhookEnabled;
private String reportConfirm, reportPermission, reportClosePermission, reportViewPermission;
private String reportDiscordWebhook, reportTelegramChatId;
private int reportCooldown;
private ChatFilter.ChatFilterConfig filterConfig = new ChatFilter.ChatFilterConfig();
private boolean mentionsEnabled, mentionsAllowToggle;
private String mentionsHighlightColor, mentionsSound, mentionsNotifyPrefix;
private int historyMaxLines, historyDefaultLines;
private boolean joinLeaveEnabled, vanishShowToAdmins;
private String joinFormat, leaveFormat, vanishJoinFormat, vanishLeaveFormat;
private String joinLeaveDiscordWebhook, joinLeaveTelegramChatId;
private int joinLeaveTelegramThreadId;
public ChatConfig(Plugin plugin) { this.plugin = plugin; }
public void load() {
File file = new File(plugin.getDataFolder(), "chat.yml");
if (!file.exists()) {
plugin.getDataFolder().mkdirs();
InputStream in = plugin.getResourceAsStream("chat.yml");
if (in != null) {
try { Files.copy(in, file.toPath()); }
catch (IOException e) { plugin.getLogger().severe("[ChatModule] Konnte chat.yml nicht erstellen: " + e.getMessage()); }
} else {
plugin.getLogger().warning("[ChatModule] chat.yml nicht in JAR, erstelle leere Datei.");
try { file.createNewFile(); } catch (IOException ignored) {}
}
}
try { config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(file); }
catch (IOException e) {
plugin.getLogger().severe("[ChatModule] Fehler beim Laden der chat.yml: " + e.getMessage());
config = new Configuration();
}
parseConfig();
plugin.getLogger().info("[ChatModule] " + channels.size() + " Kanäle geladen.");
}
private void parseConfig() {
defaultChannel = config.getString("default-channel", "global");
// --- Kanäle ---
channels.clear();
Configuration chSection = config.getSection("channels");
if (chSection != null) {
for (String id : chSection.getKeys()) {
Configuration ch = chSection.getSection(id);
if (ch == null) continue;
channels.put(id.toLowerCase(), new ChatChannel(
id.toLowerCase(),
ch.getString("name", id),
ch.getString("symbol", id.substring(0, 1).toUpperCase()),
ch.getString("permission", ""),
ch.getString("color", "&f"),
ch.getString("format", "&8[&7{server}&8] {prefix}&r{player}{suffix}&8: &f{message}"),
ch.getBoolean("local-only", false),
ch.getString("discord-webhook", ""),
ch.getString("discord-channel-id", ""),
ch.getString("telegram-chat-id", ""),
ch.getInt("telegram-thread-id", 0),
ch.getBoolean("use-admin-bridge", false)
));
}
}
if (!channels.containsKey("global")) {
channels.put("global", new ChatChannel("global", "Global", "G", "", "&a",
"&8[&a{server}&8] {prefix}&r{player}{suffix}&8: &f{message}", false, "", "", "", 0, false));
}
// --- HelpOp ---
Configuration ho = config.getSection("helpop");
if (ho != null) {
helpopFormat = ho.getString("format", "&8[&eHELPOP&8] &f{player}&8@&7{server}&8: &e{message}");
helpopPermission = ho.getString("receive-permission", "chat.helpop.receive");
helpopCooldown = ho.getInt("cooldown", 30);
helpopConfirm = ho.getString("confirm-message", "&aHilferuf gesendet!");
helpopDiscordWebhook = ho.getString("discord-webhook", "");
helpopTelegramChatId = ho.getString("telegram-chat-id", "");
} else {
helpopFormat = "&8[&eHELPOP&8] &f{player}&8@&7{server}&8: &e{message}";
helpopPermission = "chat.helpop.receive"; helpopCooldown = 30;
helpopConfirm = "&aHilferuf gesendet!"; helpopDiscordWebhook = ""; helpopTelegramChatId = "";
}
// --- Broadcast ---
Configuration bc = config.getSection("broadcast");
broadcastFormat = bc != null ? bc.getString("format", "&c[&6Broadcast&c] &e{message}") : "&c[&6Broadcast&c] &e{message}";
broadcastPermission = bc != null ? bc.getString("permission", "chat.broadcast") : "chat.broadcast";
// --- Private Messages ---
Configuration pm = config.getSection("private-messages");
pmEnabled = pm == null || pm.getBoolean("enabled", true);
pmFormatSender = pm != null ? pm.getString("format-sender", "&8[&7Du &8→ &b{player}&8] &f{message}") : "&8[&7Du &8→ &b{player}&8] &f{message}";
pmFormatReceiver = pm != null ? pm.getString("format-receiver", "&8[&b{player} &8→ &7Dir&8] &f{message}") : "&8[&b{player} &8→ &7Dir&8] &f{message}";
pmFormatSpy = pm != null ? pm.getString("format-social-spy","&8[&dSPY &7{sender} &8→ &7{receiver}&8] &f{message}") : "&8[&dSPY &7{sender} &8→ &7{receiver}&8] &f{message}";
pmSpyPermission = pm != null ? pm.getString("social-spy-permission", "chat.socialspy") : "chat.socialspy";
// --- Mute ---
Configuration mu = config.getSection("mute");
defaultMuteDuration = mu != null ? mu.getInt("default-duration-minutes", 60) : 60;
mutedMessage = mu != null ? mu.getString("muted-message", "&cDu bist stummgeschaltet. Noch: &f{time}") : "&cDu bist stummgeschaltet. Noch: &f{time}";
// --- Emoji ---
Configuration em = config.getSection("emoji");
if (em != null) {
emojiEnabled = em.getBoolean("enabled", true);
emojiBedrockSupport = em.getBoolean("bedrock-support", true);
emojiMappings.clear();
Configuration map = em.getSection("mappings");
if (map != null) { for (String key : map.getKeys()) emojiMappings.put(key, map.getString(key, key)); }
} else { emojiEnabled = true; emojiBedrockSupport = true; }
// --- Discord ---
Configuration dc = config.getSection("discord");
if (dc != null) {
discordEnabled = dc.getBoolean("enabled", false);
discordBotToken = dc.getString("bot-token", "");
discordGuildId = dc.getString("guild-id", "");
discordPollInterval = dc.getInt("poll-interval", 3);
discordFromFormat = dc.getString("from-discord-format", "&9[Discord] &b{user}&8: &f{message}");
discordAdminChannelId = dc.getString("admin-channel-id", "");
discordEmbedColor = dc.getString("embed-color", "5865F2");
} else { discordEnabled = false; discordBotToken = ""; discordGuildId = ""; discordPollInterval = 3; discordFromFormat = "&9[Discord] &b{user}&8: &f{message}"; discordAdminChannelId = ""; discordEmbedColor = "5865F2"; }
// --- Telegram ---
Configuration tg = config.getSection("telegram");
if (tg != null) {
telegramEnabled = tg.getBoolean("enabled", false);
telegramBotToken = tg.getString("bot-token", "");
telegramPollInterval = tg.getInt("poll-interval", 3);
telegramFromFormat = tg.getString("from-telegram-format", "&3[Telegram] &b{user}&8: &f{message}");
telegramAdminChatId = tg.getString("admin-chat-id", "");
telegramChatTopicId = tg.getInt("chat-topic-id", 0);
telegramAdminTopicId = tg.getInt("admin-topic-id", 0);
} else { telegramEnabled = false; telegramBotToken = ""; telegramPollInterval = 3; telegramFromFormat = "&3[Telegram] &b{user}&8: &f{message}"; telegramAdminChatId = ""; telegramChatTopicId = 0; telegramAdminTopicId = 0; }
// --- Account-Linking ---
Configuration al = config.getSection("account-linking");
linkingEnabled = al == null || al.getBoolean("enabled", true);
linkDiscordMessage = al != null ? al.getString("discord-link-message", "&aCode: &f{token}") : "&aCode: &f{token}";
linkTelegramMessage = al != null ? al.getString("telegram-link-message", "&aCode: &f{token}") : "&aCode: &f{token}";
linkSuccessDiscord = al != null ? al.getString("success-discord", "&aDiscord verknüpft!") : "&aDiscord verknüpft!";
linkSuccessTelegram = al != null ? al.getString("success-telegram", "&aTelegram verknüpft!") : "&aTelegram verknüpft!";
linkBotSuccessDiscord = al != null ? al.getString("bot-success-discord", "✅ Verknüpft: {player}") : "✅ Verknüpft: {player}";
linkBotSuccessTelegram = al != null ? al.getString("bot-success-telegram", "✅ Verknüpft: {player}") : "✅ Verknüpft: {player}";
linkedDiscordFormat = al != null ? al.getString("linked-discord-format", "&9[&bDiscord&9] &f{player} &8(&7{user}&8)&8: &f{message}") : "&9[&bDiscord&9] &f{player} &8(&7{user}&8)&8: &f{message}";
linkedTelegramFormat = al != null ? al.getString("linked-telegram-format", "&3[&bTelegram&3] &f{player} &8(&7{user}&8)&8: &f{message}") : "&3[&bTelegram&3] &f{player} &8(&7{user}&8)&8: &f{message}";
// --- Chat-Filter ---
filterConfig = new ChatFilter.ChatFilterConfig();
Configuration cf = config.getSection("chat-filter");
if (cf != null) {
Configuration spam = cf.getSection("anti-spam");
if (spam != null) {
filterConfig.antiSpamEnabled = spam.getBoolean("enabled", true);
filterConfig.spamCooldownMs = spam.getInt("cooldown-ms", 1500);
filterConfig.spamMaxMessages = spam.getInt("max-messages", 3);
filterConfig.spamMessage = spam.getString("message", "&cNicht so schnell!");
// FIX #8: Fallback-Werte aus anti-spam werden NUR gesetzt wenn rate-limit.chat nicht
// konfiguriert ist. Wir setzen die Werte hier als Vorbelegung und überschreiben sie
// unten mit dem rate-limit.chat-Block wenn vorhanden.
filterConfig.globalRateLimitWindowMs = Math.max(500L, filterConfig.spamCooldownMs);
filterConfig.globalRateLimitMaxActions = Math.max(1, filterConfig.spamMaxMessages);
filterConfig.globalRateLimitBlockMs = Math.max(2000L, filterConfig.spamCooldownMs * 4L);
}
Configuration dup = cf.getSection("duplicate-check");
if (dup != null) {
filterConfig.duplicateCheckEnabled = dup.getBoolean("enabled", true);
filterConfig.duplicateMessage = dup.getString("message", "&cKeine identischen Nachrichten.");
}
Configuration bl = cf.getSection("blacklist");
if (bl != null) {
filterConfig.blacklistEnabled = bl.getBoolean("enabled", true);
filterConfig.blacklistWords.clear();
loadFilterWords(filterConfig.blacklistWords);
try {
java.util.List<?> wordList = bl.getList("words");
if (wordList != null) {
for (Object o : wordList) {
if (o != null && !o.toString().trim().isEmpty()) {
String w = o.toString().trim();
if (!filterConfig.blacklistWords.contains(w)) filterConfig.blacklistWords.add(w);
}
}
}
} catch (Exception ignored) {}
}
Configuration caps = cf.getSection("caps-filter");
if (caps != null) {
filterConfig.capsFilterEnabled = caps.getBoolean("enabled", true);
filterConfig.capsMinLength = caps.getInt("min-length", 6);
filterConfig.capsMaxPercent = caps.getInt("max-percent", 70);
}
Configuration antiAd = cf.getSection("anti-ad");
if (antiAd != null) {
filterConfig.antiAdEnabled = antiAd.getBoolean("enabled", true);
filterConfig.antiAdMessage = antiAd.getString("message", "&cWerbung ist nicht erlaubt!");
java.util.List<?> wl = antiAd.getList("whitelist");
if (wl != null) { filterConfig.antiAdWhitelist.clear(); for (Object o : wl) if (o != null) filterConfig.antiAdWhitelist.add(o.toString()); }
java.util.List<?> tlds = antiAd.getList("blocked-tlds");
if (tlds != null) { filterConfig.antiAdBlockedTlds.clear(); for (Object o : tlds) if (o != null) filterConfig.antiAdBlockedTlds.add(o.toString()); }
}
}
// --- Rate-Limit (FIX #8: dieser Block setzt die endgültigen Werte, hat Vorrang) ---
pmRateLimitEnabled = true;
pmRateLimitWindowMs = 5000L;
pmRateLimitMaxActions = 4;
pmRateLimitBlockMs = 10000L;
pmRateLimitMessage = "&cDu sendest zu viele private Nachrichten. Bitte warte kurz.";
Configuration rl = config.getSection("rate-limit");
if (rl != null) {
Configuration rlChat = rl.getSection("chat");
if (rlChat != null) {
// FIX #8: rate-limit.chat überschreibt die anti-spam-Fallbacks vollständig
filterConfig.globalRateLimitEnabled = rlChat.getBoolean("enabled", true);
filterConfig.globalRateLimitWindowMs = rlChat.getLong("window-ms", filterConfig.globalRateLimitWindowMs);
filterConfig.globalRateLimitMaxActions = rlChat.getInt("max-actions", filterConfig.globalRateLimitMaxActions);
filterConfig.globalRateLimitBlockMs = rlChat.getLong("block-ms", filterConfig.globalRateLimitBlockMs);
filterConfig.spamMessage = rlChat.getString("message", filterConfig.spamMessage);
}
Configuration rlPm = rl.getSection("private-messages");
if (rlPm != null) {
pmRateLimitEnabled = rlPm.getBoolean("enabled", pmRateLimitEnabled);
pmRateLimitWindowMs = rlPm.getLong("window-ms", pmRateLimitWindowMs);
pmRateLimitMaxActions = rlPm.getInt("max-actions", pmRateLimitMaxActions);
pmRateLimitBlockMs = rlPm.getLong("block-ms", pmRateLimitBlockMs);
pmRateLimitMessage = rlPm.getString("message", pmRateLimitMessage);
}
}
// --- Mentions ---
Configuration mn = config.getSection("mentions");
mentionsEnabled = mn == null || mn.getBoolean("enabled", true);
mentionsHighlightColor = mn != null ? mn.getString("highlight-color", "&e&l") : "&e&l";
mentionsSound = mn != null ? mn.getString("sound", "ENTITY_EXPERIENCE_ORB_PICKUP") : "ENTITY_EXPERIENCE_ORB_PICKUP";
mentionsAllowToggle = mn == null || mn.getBoolean("allow-toggle", true);
mentionsNotifyPrefix = mn != null ? mn.getString("notify-prefix", "&e&l[Mention] &r") : "&e&l[Mention] &r";
// --- Chat-History ---
Configuration ch = config.getSection("chat-history");
historyMaxLines = ch != null ? ch.getInt("max-lines", 50) : 50;
historyDefaultLines = ch != null ? ch.getInt("default-lines", 10) : 10;
// --- Admin ---
Configuration adm = config.getSection("admin");
adminBypassPermission = adm != null ? adm.getString("bypass-permission", "chat.admin.bypass") : "chat.admin.bypass";
adminNotifyPermission = adm != null ? adm.getString("notify-permission", "chat.admin.notify") : "chat.admin.notify";
// --- Server-Farben ---
serverColors.clear(); serverDisplayNames.clear();
Configuration sc = config.getSection("server-colors");
if (sc != null) {
serverColorDefault = sc.getString("default", "&7");
for (String key : sc.getKeys()) {
if (key.equals("default")) continue;
Configuration sub = sc.getSection(key);
if (sub != null) {
serverColors.put(key.toLowerCase(), sub.getString("color", "&7"));
String display = sub.getString("display", "");
if (!display.isEmpty()) serverDisplayNames.put(key.toLowerCase(), display);
} else {
serverColors.put(key.toLowerCase(), sc.getString(key, "&7"));
}
}
} else { serverColorDefault = "&7"; }
// --- Chatlog ---
Configuration cl = config.getSection("chatlog");
chatlogEnabled = cl == null || cl.getBoolean("enabled", true);
int raw = cl != null ? cl.getInt("retention-days", 7) : 7;
chatlogRetentionDays = (raw == 14) ? 14 : 7;
// --- Reports ---
Configuration rp = config.getSection("reports");
if (rp != null) {
reportsEnabled = rp.getBoolean("enabled", true);
reportWebhookEnabled = rp.getBoolean("webhook-enabled", false);
reportConfirm = rp.getString("confirm-message", "&aDein Report &8({id}) &awurde eingereicht. Danke!");
reportPermission = rp.getString("report-permission", "");
reportClosePermission = rp.getString("close-permission", "chat.admin.bypass");
reportViewPermission = rp.getString("view-permission", "chat.admin.bypass");
reportCooldown = rp.getInt("cooldown", 60);
reportDiscordWebhook = rp.getString("discord-webhook", "");
reportTelegramChatId = rp.getString("telegram-chat-id", "");
} else {
reportsEnabled = true; reportWebhookEnabled = false;
reportConfirm = "&aDein Report &8({id}) &awurde eingereicht. Danke!";
reportPermission = ""; reportClosePermission = "chat.admin.bypass"; reportViewPermission = "chat.admin.bypass";
reportCooldown = 60; reportDiscordWebhook = ""; reportTelegramChatId = "";
}
// --- Join / Leave ---
Configuration jl = config.getSection("join-leave");
if (jl != null) {
joinLeaveEnabled = jl.getBoolean("enabled", true);
joinFormat = jl.getString("join-format", "&8[&a+&8] {prefix}&a{player}&r &7hat das Netzwerk betreten.");
leaveFormat = jl.getString("leave-format", "&8[&c-&8] {prefix}&c{player}&r &7hat das Netzwerk verlassen.");
vanishShowToAdmins = jl.getBoolean("vanish-show-to-admins", true);
vanishJoinFormat = jl.getString("vanish-join-format", "&8[&7+&8] &8{player} &7hat das Netzwerk betreten. &8(Vanish)");
vanishLeaveFormat = jl.getString("vanish-leave-format", "&8[&7-&8] &8{player} &7hat das Netzwerk verlassen. &8(Vanish)");
joinLeaveDiscordWebhook = jl.getString("discord-webhook", "");
joinLeaveTelegramChatId = jl.getString("telegram-chat-id", "");
joinLeaveTelegramThreadId = jl.getInt("telegram-thread-id", 0);
} else {
joinLeaveEnabled = true;
joinFormat = "&8[&a+&8] {prefix}&a{player}&r &7hat das Netzwerk betreten.";
leaveFormat = "&8[&c-&8] {prefix}&c{player}&r &7hat das Netzwerk verlassen.";
vanishShowToAdmins = true;
vanishJoinFormat = "&8[&7+&8] &8{player} &7hat das Netzwerk betreten. &8(Vanish)";
vanishLeaveFormat = "&8[&7-&8] &8{player} &7hat das Netzwerk verlassen. &8(Vanish)";
joinLeaveDiscordWebhook = ""; joinLeaveTelegramChatId = ""; joinLeaveTelegramThreadId = 0;
}
}
private void loadFilterWords(java.util.List<String> target) {
File filterFile = new File(plugin.getDataFolder(), "filter.yml");
if (!filterFile.exists()) {
try {
plugin.getDataFolder().mkdirs();
try (java.io.FileWriter fw = new java.io.FileWriter(filterFile)) {
fw.write("# StatusAPI - Wort-Blacklist\n# words:\n# - beispielwort\nwords:\n");
}
plugin.getLogger().info("[ChatModule] filter.yml erstellt.");
} catch (IOException e) { plugin.getLogger().warning("[ChatModule] Konnte filter.yml nicht erstellen: " + e.getMessage()); }
return;
}
try {
Configuration fc = ConfigurationProvider.getProvider(YamlConfiguration.class).load(filterFile);
java.util.List<?> words = fc.getList("words");
if (words != null) {
for (Object o : words) {
if (o != null && !o.toString().trim().isEmpty()) target.add(o.toString().trim().toLowerCase());
}
}
} catch (Exception e) { plugin.getLogger().warning("[ChatModule] Fehler beim Laden der filter.yml: " + e.getMessage()); }
}
// ===== Getter =====
public Map<String, ChatChannel> getChannels() { return Collections.unmodifiableMap(channels); }
public ChatChannel getChannel(String id) { return channels.get(id == null ? defaultChannel : id.toLowerCase()); }
public ChatChannel getDefaultChannel() { return channels.getOrDefault(defaultChannel, channels.values().iterator().next()); }
public String getDefaultChannelId() { return defaultChannel; }
public String getHelpopFormat() { return helpopFormat; }
public String getHelpopPermission() { return helpopPermission; }
public int getHelpopCooldown() { return helpopCooldown; }
public String getHelpopConfirm() { return helpopConfirm; }
public String getHelpopDiscordWebhook() { return helpopDiscordWebhook; }
public String getHelpopTelegramChatId() { return helpopTelegramChatId; }
public String getBroadcastFormat() { return broadcastFormat; }
public String getBroadcastPermission() { return broadcastPermission; }
public boolean isPmEnabled() { return pmEnabled; }
public String getPmFormatSender() { return pmFormatSender; }
public String getPmFormatReceiver() { return pmFormatReceiver; }
public String getPmFormatSpy() { return pmFormatSpy; }
public String getPmSpyPermission() { return pmSpyPermission; }
public boolean isPmRateLimitEnabled() { return pmRateLimitEnabled; }
public long getPmRateLimitWindowMs() { return pmRateLimitWindowMs; }
public int getPmRateLimitMaxActions() { return pmRateLimitMaxActions; }
public long getPmRateLimitBlockMs() { return pmRateLimitBlockMs; }
public String getPmRateLimitMessage() { return pmRateLimitMessage; }
public int getDefaultMuteDuration() { return defaultMuteDuration; }
public String getMutedMessage() { return mutedMessage; }
public boolean isEmojiEnabled() { return emojiEnabled; }
public boolean isEmojiBedrockSupport() { return emojiBedrockSupport; }
public Map<String, String> getEmojiMappings() { return Collections.unmodifiableMap(emojiMappings); }
public boolean isDiscordEnabled() { return discordEnabled; }
public String getDiscordBotToken() { return discordBotToken; }
public String getDiscordGuildId() { return discordGuildId; }
public int getDiscordPollInterval() { return discordPollInterval; }
public String getDiscordFromFormat() { return discordFromFormat; }
public String getDiscordAdminChannelId() { return discordAdminChannelId; }
public String getDiscordEmbedColor() { return discordEmbedColor; }
public boolean isTelegramEnabled() { return telegramEnabled; }
public String getTelegramBotToken() { return telegramBotToken; }
public int getTelegramPollInterval() { return telegramPollInterval; }
public String getTelegramFromFormat() { return telegramFromFormat; }
public String getTelegramAdminChatId() { return telegramAdminChatId; }
public int getTelegramChatTopicId() { return telegramChatTopicId; }
public int getTelegramAdminTopicId() { return telegramAdminTopicId; }
public boolean isLinkingEnabled() { return linkingEnabled; }
public String getLinkDiscordMessage() { return linkDiscordMessage; }
public String getLinkTelegramMessage() { return linkTelegramMessage; }
public String getLinkSuccessDiscord() { return linkSuccessDiscord; }
public String getLinkSuccessTelegram() { return linkSuccessTelegram; }
public String getLinkBotSuccessDiscord() { return linkBotSuccessDiscord; }
public String getLinkBotSuccessTelegram() { return linkBotSuccessTelegram; }
public String getLinkedDiscordFormat() { return linkedDiscordFormat; }
public String getLinkedTelegramFormat() { return linkedTelegramFormat; }
public String getAdminBypassPermission() { return adminBypassPermission; }
public String getAdminNotifyPermission() { return adminNotifyPermission; }
public String getServerColor(String serverName) { if (serverName == null) return serverColorDefault; String c = serverColors.get(serverName.toLowerCase()); return c != null ? c : serverColorDefault; }
public Map<String, String> getServerColors() { return Collections.unmodifiableMap(serverColors); }
public String getServerColorDefault() { return serverColorDefault; }
public String getServerDisplay(String serverName) { if (serverName == null) return ""; String d = serverDisplayNames.get(serverName.toLowerCase()); return d != null ? d : serverName; }
public boolean isChatlogEnabled() { return chatlogEnabled; }
public int getChatlogRetentionDays() { return chatlogRetentionDays; }
public boolean isReportsEnabled() { return reportsEnabled; }
public String getReportConfirm() { return reportConfirm; }
public String getReportPermission() { return reportPermission; }
public String getReportClosePermission() { return reportClosePermission; }
public String getReportViewPermission() { return reportViewPermission; }
public int getReportCooldown() { return reportCooldown; }
public String getReportDiscordWebhook() { return reportDiscordWebhook; }
public String getReportTelegramChatId() { return reportTelegramChatId; }
public boolean isReportWebhookEnabled() { return reportWebhookEnabled; }
public ChatFilter.ChatFilterConfig getFilterConfig() { return filterConfig; }
public boolean isMentionsEnabled() { return mentionsEnabled; }
public String getMentionsHighlightColor() { return mentionsHighlightColor; }
public String getMentionsSound() { return mentionsSound; }
public boolean isMentionsAllowToggle() { return mentionsAllowToggle; }
public String getMentionsNotifyPrefix() { return mentionsNotifyPrefix; }
public int getHistoryMaxLines() { return historyMaxLines; }
public int getHistoryDefaultLines() { return historyDefaultLines; }
public boolean isJoinLeaveEnabled() { return joinLeaveEnabled; }
public String getJoinFormat() { return joinFormat; }
public String getLeaveFormat() { return leaveFormat; }
public boolean isVanishShowToAdmins() { return vanishShowToAdmins; }
public String getVanishJoinFormat() { return vanishJoinFormat; }
public String getVanishLeaveFormat() { return vanishLeaveFormat; }
public String getJoinLeaveDiscordWebhook() { return joinLeaveDiscordWebhook; }
public String getJoinLeaveTelegramChatId() { return joinLeaveTelegramChatId; }
public int getJoinLeaveTelegramThreadId() { return joinLeaveTelegramThreadId; }
}

View File

@@ -0,0 +1,331 @@
package net.viper.status.modules.chat;
import net.viper.status.ratelimit.GlobalRateLimitFramework;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;
/**
* Chat-Filter: Anti-Spam, Caps-Filter, Wort-Blacklist, Farbcode-Filter.
*
* Reihenfolge der Prüfungen in processChat():
* 1. Spam-Cooldown (zu schnell geschrieben?)
* 2. Gleiche Nachricht wiederholt?
* 3. Zu viele Großbuchstaben?
* 4. Verbotene Wörter → ersetzen durch ****
* 5. Farbcodes (& Codes) → nur mit Permission erlaubt
*/
public class ChatFilter {
private final ChatFilterConfig cfg;
private final GlobalRateLimitFramework rateLimiter = GlobalRateLimitFramework.getInstance();
// UUID → letzte Nachricht (für Duplikat-Check)
private final Map<UUID, String> lastMessageText = new ConcurrentHashMap<>();
// Kompilierte Regex-Pattern für Blacklist-Wörter
private final List<Pattern> blacklistPatterns = new ArrayList<>();
public ChatFilter(ChatFilterConfig cfg) {
this.cfg = cfg;
compilePatterns();
}
private void compilePatterns() {
blacklistPatterns.clear();
for (String word : cfg.blacklistWords) {
// Case-insensitiv, ganzes Wort oder Teilwort je nach Config
blacklistPatterns.add(Pattern.compile(
"(?i)" + Pattern.quote(word)));
}
}
// ===== Ergebnis-Klasse =====
public enum FilterResult {
ALLOWED, // Nachricht darf durch
BLOCKED, // Nachricht blockiert (Spam/Flood)
MODIFIED // Nachricht wurde verändert (Wörter ersetzt / Caps reduziert)
}
public static class FilterResponse {
public final FilterResult result;
public final String message; // ggf. modifizierte Nachricht
public final String denyReason; // Nachricht an den Spieler wenn BLOCKED
FilterResponse(FilterResult result, String message, String denyReason) {
this.result = result;
this.message = message;
this.denyReason = denyReason;
}
}
// ===== Haupt-Filtermethode =====
/**
* Wendet alle aktiven Filter auf eine Nachricht an.
*
* @param uuid UUID des sendenden Spielers
* @param message Originalnachricht
* @param isAdmin true → Farbcodes und Caps-Filter überspringen
* @param hasColorPerm true → &-Farbcodes erlaubt
* @param hasFormatPerm true → &l, &o etc. erlaubt
* @return FilterResponse mit Ergebnis und ggf. modifizierter Nachricht
*/
public FilterResponse filter(UUID uuid, String message, boolean isAdmin,
boolean hasColorPerm, boolean hasFormatPerm) {
// ── 1. Spam-Cooldown ──
if (cfg.antiSpamEnabled && !isAdmin) {
if (cfg.globalRateLimitEnabled) {
GlobalRateLimitFramework.Result rl = rateLimiter.check(
"chat.message",
uuid.toString(),
new GlobalRateLimitFramework.Rule(
true,
cfg.globalRateLimitWindowMs,
cfg.globalRateLimitMaxActions,
cfg.globalRateLimitBlockMs
)
);
if (rl.isBlocked()) {
return new FilterResponse(FilterResult.BLOCKED, message, cfg.spamMessage);
}
}
}
// ── 2. Duplikat-Check ──
if (cfg.duplicateCheckEnabled && !isAdmin) {
String lastText = lastMessageText.get(uuid);
if (message.equalsIgnoreCase(lastText)) {
return new FilterResponse(FilterResult.BLOCKED, message, cfg.duplicateMessage);
}
lastMessageText.put(uuid, message);
}
String result = message;
boolean modified = false;
// ── 3. Blacklist ──
if (cfg.blacklistEnabled) {
String filtered = applyBlacklist(result);
if (!filtered.equals(result)) {
result = filtered;
modified = true;
}
}
// ── 4. Caps-Filter ──
if (cfg.capsFilterEnabled && !isAdmin) {
String capped = applyCapsFilter(result);
if (!capped.equals(result)) {
result = capped;
modified = true;
}
}
// ── 5. Farbcodes filtern (nur wenn keine Permission) ──
if (!isAdmin) {
String colorFiltered = applyColorFilter(result, hasColorPerm, hasFormatPerm);
if (!colorFiltered.equals(result)) {
result = colorFiltered;
modified = true;
}
}
// ── 6. Anti-Werbung ──
if (cfg.antiAdEnabled && !isAdmin) {
if (containsAdvertisement(result)) {
return new FilterResponse(FilterResult.BLOCKED, result, cfg.antiAdMessage);
}
}
return new FilterResponse(
modified ? FilterResult.MODIFIED : FilterResult.ALLOWED,
result,
null
);
}
// ===== Einzelne Filter =====
private String applyBlacklist(String message) {
String result = message;
for (Pattern p : blacklistPatterns) {
result = p.matcher(result).replaceAll(buildStars(p.pattern()
.replace("(?i)", "").replace("\\Q", "").replace("\\E", "").length()));
}
return result;
}
private String applyCapsFilter(String message) {
// Zähle Großbuchstaben
int total = 0, upper = 0;
for (char c : message.toCharArray()) {
if (Character.isLetter(c)) { total++; if (Character.isUpperCase(c)) upper++; }
}
if (total < cfg.capsMinLength) return message; // Kurze Nachrichten ignorieren
double ratio = total > 0 ? (double) upper / total : 0;
if (ratio < cfg.capsMaxPercent / 100.0) return message;
// Zu viele Caps → alles lowercase
return message.toLowerCase();
}
/**
* Entfernt &-Farbcodes je nach Permission.
* hasColorPerm → &0-&9, &a-&f erlaubt
* hasFormatPerm → &l, &o, &n, &m, &k erlaubt
* Beide false → alle &-Codes entfernen
*/
private String applyColorFilter(String message, boolean hasColorPerm, boolean hasFormatPerm) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < message.length(); i++) {
char c = message.charAt(i);
if (c == '&' && i + 1 < message.length()) {
char next = Character.toLowerCase(message.charAt(i + 1));
boolean isColor = (next >= '0' && next <= '9') || (next >= 'a' && next <= 'f');
boolean isFormat = "lonmkr".indexOf(next) >= 0;
boolean isHex = next == '#';
if (isColor && hasColorPerm) { sb.append(c); continue; }
if (isFormat && hasFormatPerm) { sb.append(c); continue; }
if (isHex && hasColorPerm) { sb.append(c); continue; }
// Kein Recht → & und nächstes Zeichen überspringen
if (isColor || isFormat) { i++; continue; }
// Hex: &# + 6 Zeichen überspringen (i zeigt auf &, +1 = #, +2..+7 = RRGGBB)
if (isHex && i + 7 <= message.length()) { i += 7; continue; }
}
sb.append(c);
}
return sb.toString();
}
// ===== Anti-Werbung =====
// Vorkompilierte Patterns (einmalig beim Classload)
private static final Pattern PATTERN_IP =
Pattern.compile("\\b(\\d{1,3}[.,]){3}\\d{1,3}(:\\d{1,5})?\\b");
private static final Pattern PATTERN_DOMAIN_GENERIC =
Pattern.compile("(?i)\\b[a-z0-9-]{2,63}\\.[a-z]{2,10}(?:[/:\\d]\\S*)?\\b");
private static final Pattern PATTERN_URL_PREFIX =
Pattern.compile("(?i)(https?://|www\\.)\\S+");
/**
* Prüft ob die Nachricht Werbung enthält (IP, URL, fremde Domain).
* Domains auf der Whitelist werden ignoriert.
*
* Erkennt:
* - http:// / https:// / www. Prefixe
* - IPv4-Adressen (auch mit Port)
* - Domain-Namen mit konfigurierten TLDs (z.B. .net, .de, .com)
* - Verschleierungsversuche mit Leerzeichen um Punkte ("play . server . net")
*/
private boolean containsAdvertisement(String message) {
// Normalisierung: "play . server . net" → "play.server.net"
String normalized = message.replaceAll("\\s*\\.\\s*", ".");
// 1. Explizite URL-Prefixe
if (PATTERN_URL_PREFIX.matcher(normalized).find()) {
return !allMatchesWhitelisted(normalized, PATTERN_URL_PREFIX);
}
// 2. IP-Adressen (werden nie whitelisted)
if (PATTERN_IP.matcher(normalized).find()) {
return true;
}
// 3. Domains mit bekannten TLDs
if (!cfg.antiAdBlockedTlds.isEmpty()) {
java.util.regex.Matcher m = PATTERN_DOMAIN_GENERIC.matcher(normalized);
while (m.find()) {
String match = m.group();
String tld = extractTld(match);
if (cfg.antiAdBlockedTlds.contains(tld.toLowerCase())) {
if (!isOnWhitelist(match)) return true;
}
}
}
return false;
}
/** true wenn ALLE Treffer des Patterns auf der Whitelist stehen. */
private boolean allMatchesWhitelisted(String message, Pattern pattern) {
java.util.regex.Matcher m = pattern.matcher(message);
while (m.find()) {
if (!isOnWhitelist(m.group())) return false;
}
return true;
}
private boolean isOnWhitelist(String match) {
String lower = match.toLowerCase();
for (String entry : cfg.antiAdWhitelist) {
if (lower.contains(entry.toLowerCase())) return true;
}
return false;
}
private static String extractTld(String domain) {
String clean = domain.split("[/:]")[0];
int dot = clean.lastIndexOf('.');
return dot >= 0 ? clean.substring(dot + 1) : "";
}
private static String buildStars(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Math.max(length, 4); i++) sb.append('*');
return sb.toString();
}
// ===== Cleanup beim Logout =====
public void cleanup(UUID uuid) {
lastMessageText.remove(uuid);
rateLimiter.clearActor(uuid.toString());
}
// ===== Konfigurationsklasse =====
public static class ChatFilterConfig {
// Anti-Spam
public boolean antiSpamEnabled = true;
public long spamCooldownMs = 1500; // Legacy-Feld fuer Kompatibilitaet
public int spamMaxMessages = 3; // Legacy-Feld fuer Kompatibilitaet
public String spamMessage = "&cBitte nicht so schnell schreiben!";
// Globales Rate-Limit-Framework
public boolean globalRateLimitEnabled = true;
public long globalRateLimitWindowMs = 2500;
public int globalRateLimitMaxActions = 3;
public long globalRateLimitBlockMs = 6000;
// Duplikat
public boolean duplicateCheckEnabled = true;
public String duplicateMessage = "&cBitte keine identischen Nachrichten senden.";
// Blacklist
public boolean blacklistEnabled = true;
public List<String> blacklistWords = new ArrayList<>();
// Caps
public boolean capsFilterEnabled = true;
public int capsMinLength = 6; // Mindestlänge für Caps-Check
public int capsMaxPercent = 70; // Max. % Großbuchstaben
// Anti-Werbung
public boolean antiAdEnabled = true;
public String antiAdMessage = "&cWerbung ist in diesem Chat nicht erlaubt!";
// Domains/Substrings die NICHT geblockt werden (z.B. eigene Serveradresse)
public List<String> antiAdWhitelist = new ArrayList<>();
// TLDs die als Werbung gewertet werden (leer = alle TLDs prüfen)
public List<String> antiAdBlockedTlds = new ArrayList<>(Arrays.asList(
"net", "com", "de", "org", "gg", "io", "eu", "tv", "xyz",
"info", "me", "cc", "co", "app", "online", "site", "fun"
));
}
}

View File

@@ -0,0 +1,152 @@
package net.viper.status.modules.chat;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
/**
* Protokolliert alle Chat-Nachrichten in tagesweise rotierende Logdateien.
*
* Verzeichnis: plugins/StatusAPI/chatlogs/chatlog_YYYY-MM-DD.log
* Format: [HH:mm:ss] [MSG-XXXXXX] [SERVER] [CHANNEL] Spieler: Nachricht
*
* Alte Logs werden beim Start und täglich automatisch bereinigt.
* Die Aufbewahrungsdauer ist in der chat.yml konfigurierbar (7 oder 14 Tage).
*/
public class ChatLogger {
private final File logDir;
private final Logger logger;
private final int retentionDays;
private final AtomicInteger counter = new AtomicInteger(0);
private static final SimpleDateFormat DATE_FMT = new SimpleDateFormat("yyyy-MM-dd");
private static final SimpleDateFormat TIME_FMT = new SimpleDateFormat("HH:mm:ss");
public ChatLogger(File dataFolder, Logger logger, int retentionDays) {
this.logDir = new File(dataFolder, "chatlogs");
this.logger = logger;
this.retentionDays = Math.max(1, retentionDays);
this.logDir.mkdirs();
cleanup();
}
// ===== Nachrichten-ID =====
/**
* Generiert eine eindeutige Nachrichten-ID (z.B. MSG-A3F2B1).
* Kombiniert Zeitstempel + inkrementellen Zähler für Eindeutigkeit.
*/
public String generateMessageId() {
int seq = counter.incrementAndGet();
long ts = System.currentTimeMillis();
int hash = (int)(ts ^ (ts >>> 32)) ^ (seq * 0x9E3779B9);
return "MSG-" + String.format("%06X", hash & 0xFFFFFF);
}
// ===== Logging =====
/**
* Loggt eine Nachricht und gibt die generierte Nachrichten-ID zurück.
*
* @param msgId Vorher generierte ID (aus generateMessageId())
* @param server Servername des Absenders
* @param channel Kanal-ID
* @param player Spielername
* @param message Nachrichtentext (Rohtext, ohne Farbcodes)
*/
public void log(String msgId, String server, String channel, String player, String message) {
String date = DATE_FMT.format(new Date());
String time = TIME_FMT.format(new Date());
// Minecraft-Farbcodes aus dem Log entfernen
String cleanMsg = stripColor(message);
String line = "[" + time + "] [" + msgId + "] [" + server + "] [" + channel + "] "
+ player + ": " + cleanMsg;
File logFile = new File(logDir, "chatlog_" + date + ".log");
try (BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(logFile, true), "UTF-8"))) {
bw.write(line);
bw.newLine();
} catch (IOException e) {
logger.warning("[ChatLogger] Fehler beim Schreiben: " + e.getMessage());
}
}
// ===== Cleanup =====
/**
* Löscht Log-Dateien, die älter als retentionDays Tage sind.
* Wird beim Start und kann manuell aufgerufen werden.
*/
public void cleanup() {
if (!logDir.exists()) return;
long cutoff = System.currentTimeMillis() - ((long) retentionDays * 24L * 60L * 60L * 1000L);
File[] files = logDir.listFiles((dir, name) ->
name.startsWith("chatlog_") && name.endsWith(".log"));
if (files == null) return;
for (File f : files) {
if (f.lastModified() < cutoff) {
if (f.delete()) {
logger.info("[ChatLogger] Altes Log gelöscht: " + f.getName());
}
}
}
}
// ===== Hilfsmethoden =====
/** Entfernt §-Farbcodes aus dem Text. */
private static String stripColor(String input) {
if (input == null) return "";
return input.replaceAll("(?i)§[0-9A-FK-OR]", "")
.replaceAll("(?i)&[0-9A-FK-OR]", "");
}
public int getRetentionDays() { return retentionDays; }
public File getLogDir() { return logDir; }
/**
* Liest die letzten `maxLines` Zeilen aus dem heutigen Chatlog.
* Wenn ein Spielername angegeben ist, werden nur seine Zeilen zurückgegeben.
*
* @param playerFilter Spielername (case-insensitiv) oder null für alle
* @param maxLines Maximale Anzahl zurückgegebener Zeilen
* @return Liste der Logzeilen (älteste zuerst)
*/
public List<String> readLastLines(String playerFilter, int maxLines) {
String date = DATE_FMT.format(new Date());
File logFile = new File(logDir, "chatlog_" + date + ".log");
if (!logFile.exists()) return Collections.emptyList();
List<String> allLines = new ArrayList<>();
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(logFile), "UTF-8"))) {
String line;
while ((line = br.readLine()) != null) {
if (line.trim().isEmpty()) continue;
// Spieler-Filter: Format ist [...] [...] [...] [...] Spieler: Nachricht
if (playerFilter != null) {
// Spielername steht nach dem 4. [...]-Block
int lastBracket = line.indexOf("] ", line.lastIndexOf("["));
if (lastBracket >= 0) {
String rest = line.substring(lastBracket + 2);
String name = rest.contains(":") ? rest.substring(0, rest.indexOf(":")).trim() : "";
if (!name.equalsIgnoreCase(playerFilter)) continue;
}
}
allLines.add(line);
}
} catch (IOException e) {
logger.warning("[ChatLogger] Fehler beim Lesen: " + e.getMessage());
}
// Letzte maxLines zurückgeben
if (allLines.size() <= maxLines) return allLines;
return allLines.subList(allLines.size() - maxLines, allLines.size());
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,53 @@
package net.viper.status.modules.chat;
import java.util.Map;
/**
* Ersetzt Emoji-Shortcuts (:smile:, :heart:, …) durch Unicode-Zeichen.
*
* Bedrock-Spieler (Geyser) unterstützen Unicode-Emojis ebenfalls,
* da sie als reguläre UTF-8 Zeichen in TextComponents übertragen werden.
*/
public class EmojiParser {
private final Map<String, String> mappings;
private final boolean enabled;
public EmojiParser(Map<String, String> mappings, boolean enabled) {
this.mappings = mappings;
this.enabled = enabled;
}
/**
* Konvertiert alle bekannten Emoji-Shortcuts in der Nachricht zu Unicode.
* Nicht erkannte Shortcuts bleiben unverändert.
*
* @param message Die Originalnachricht des Spielers
* @return Nachricht mit ersetzten Emojis
*/
public String parse(String message) {
if (!enabled || message == null || message.isEmpty()) return message;
String result = message;
for (Map.Entry<String, String> entry : mappings.entrySet()) {
result = result.replace(entry.getKey(), entry.getValue());
}
return result;
}
/**
* Gibt eine lesbare Liste aller Emojis zurück (für /emoji list).
*/
public String buildEmojiList() {
if (mappings.isEmpty()) return "&cKeine Emojis konfiguriert.";
StringBuilder sb = new StringBuilder();
sb.append("&eVerfügbare Emojis:\n");
int i = 0;
for (Map.Entry<String, String> entry : mappings.entrySet()) {
sb.append("&7").append(entry.getKey()).append(" &f→ ").append(entry.getValue());
if (i < mappings.size() - 1) sb.append(" ");
i++;
}
return sb.toString();
}
}

View File

@@ -0,0 +1,124 @@
package net.viper.status.modules.chat;
import java.io.*;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
/**
* Verwaltet Mutes von Spielern.
* Speichert: UUID → Ablaufzeitpunkt (Unix-Sekunden, 0 = permanent)
*
* Admins/OPs mit dem Bypass-Permission können nicht gemutet werden.
*/
public class MuteManager {
private final File file;
private final Logger logger;
// UUID → Ablaufzeitpunkt (0 = permanent)
private final ConcurrentHashMap<UUID, Long> mutes = new ConcurrentHashMap<>();
public MuteManager(File dataFolder, Logger logger) {
this.file = new File(dataFolder, "chat_mutes.dat");
this.logger = logger;
}
// ===== Mute-Logik =====
/**
* Mutet einen Spieler für durationMinutes Minuten.
* durationMinutes = 0 → permanent
*/
public void mute(UUID uuid, int durationMinutes) {
long expiry = (durationMinutes <= 0)
? 0L
: (System.currentTimeMillis() / 1000L) + ((long) durationMinutes * 60);
mutes.put(uuid, expiry);
save();
}
/** Hebt den Mute auf. */
public void unmute(UUID uuid) {
mutes.remove(uuid);
save();
}
/** Prüft ob ein Spieler aktuell gemutet ist. */
public boolean isMuted(UUID uuid) {
Long expiry = mutes.get(uuid);
if (expiry == null) return false;
if (expiry == 0L) return true; // permanent
if (System.currentTimeMillis() / 1000L >= expiry) {
// Abgelaufen → entfernen
mutes.remove(uuid);
save();
return false;
}
return true;
}
/**
* Gibt die verbleibende Zeit als lesbaren String zurück.
* Gibt "permanent" zurück bei dauerhaftem Mute.
*/
public String getRemainingTime(UUID uuid) {
Long expiry = mutes.get(uuid);
if (expiry == null) return "0";
if (expiry == 0L) return "permanent";
long remaining = expiry - (System.currentTimeMillis() / 1000L);
if (remaining <= 0) return "0";
long hours = remaining / 3600;
long minutes = (remaining % 3600) / 60;
long seconds = remaining % 60;
if (hours > 0) return hours + "h " + minutes + "m";
if (minutes > 0) return minutes + "m " + seconds + "s";
return seconds + "s";
}
// ===== Persistenz =====
public void save() {
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))) {
long now = System.currentTimeMillis() / 1000L;
for (Map.Entry<UUID, Long> e : mutes.entrySet()) {
// Nur aktive Mutes speichern
if (e.getValue() == 0L || e.getValue() > now) {
bw.write(e.getKey() + "|" + e.getValue());
bw.newLine();
}
}
} catch (IOException e) {
logger.warning("[ChatModule] Fehler beim Speichern der Mutes: " + e.getMessage());
}
}
public void load() {
mutes.clear();
if (!file.exists()) return;
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
String line;
long now = System.currentTimeMillis() / 1000L;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) continue;
String[] parts = line.split("\\|");
if (parts.length < 2) continue;
try {
UUID uuid = UUID.fromString(parts[0]);
long expiry = Long.parseLong(parts[1]);
// Nur laden wenn noch aktiv
if (expiry == 0L || expiry > now) {
mutes.put(uuid, expiry);
}
} catch (Exception ignored) {}
}
} catch (IOException e) {
logger.warning("[ChatModule] Fehler beim Laden der Mutes: " + e.getMessage());
}
}
}

View File

@@ -0,0 +1,163 @@
package net.viper.status.modules.chat;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.viper.status.ratelimit.GlobalRateLimitFramework;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Verwaltet private Nachrichten (/msg, /r) und Social-Spy.
*/
public class PrivateMsgManager {
private final BlockManager blockManager;
private final GlobalRateLimitFramework rateLimiter = GlobalRateLimitFramework.getInstance();
// UUID → letzte PM-Gesprächspartner UUID (für /r)
private final Map<UUID, UUID> lastPartner = new ConcurrentHashMap<>();
// UUIDs die Social-Spy aktiviert haben
private final java.util.Set<UUID> spyEnabled =
java.util.Collections.newSetFromMap(new ConcurrentHashMap<>());
public PrivateMsgManager(BlockManager blockManager) {
this.blockManager = blockManager;
}
/**
* Sendet eine private Nachricht von `sender` an `receiver`.
*
* @param sender Der sendende Spieler
* @param receiver Der empfangende Spieler
* @param message Die Nachricht
* @param config Chat-Konfiguration (Formate)
* @param bypassPermission Permission für Admin-Bypass (kann nicht geblockt werden)
* @return true wenn erfolgreich gesendet
*/
public boolean send(ProxiedPlayer sender, ProxiedPlayer receiver,
String message, ChatConfig config, String bypassPermission) {
// Selbst anschreiben verhindern
if (sender.getUniqueId().equals(receiver.getUniqueId())) {
sender.sendMessage(color("&cDu kannst dir nicht selbst schreiben."));
return false;
}
// Admin-Bypass: Wenn Sender Admin ist, kann er nicht geblockt werden
boolean senderIsAdmin = sender.hasPermission(bypassPermission);
// Block-Check (nur wenn Sender kein Admin)
if (!senderIsAdmin) {
if (!blockManager.canReceive(sender.getUniqueId(), receiver.getUniqueId())) {
sender.sendMessage(color("&cDieser Spieler hat dich blockiert oder du hast ihn blockiert."));
return false;
}
if (config.isPmRateLimitEnabled()) {
GlobalRateLimitFramework.Result result = rateLimiter.check(
"chat.pm",
sender.getUniqueId().toString(),
new GlobalRateLimitFramework.Rule(
true,
config.getPmRateLimitWindowMs(),
config.getPmRateLimitMaxActions(),
config.getPmRateLimitBlockMs()
)
);
if (result.isBlocked()) {
sender.sendMessage(color(config.getPmRateLimitMessage()));
return false;
}
}
}
// Formatierung
String toSender = format(config.getPmFormatSender(), sender.getName(), receiver.getName(), message, true);
String toReceiver = format(config.getPmFormatReceiver(), sender.getName(), receiver.getName(), message, false);
sender.sendMessage(color(toSender));
receiver.sendMessage(color(toReceiver));
// Letzte Partner speichern (für /r)
lastPartner.put(sender.getUniqueId(), receiver.getUniqueId());
lastPartner.put(receiver.getUniqueId(), sender.getUniqueId());
// Social Spy
String spyMsg = format(config.getPmFormatSpy(), sender.getName(), receiver.getName(), message, true);
broadcastSpy(spyMsg, config.getPmSpyPermission(), sender.getUniqueId(), receiver.getUniqueId());
return true;
}
/**
* Antwort-Funktion (/r).
* Sucht den letzten Gesprächspartner des Senders.
*/
public void reply(ProxiedPlayer sender, String message, ChatConfig config, String bypassPermission) {
UUID partnerUuid = lastPartner.get(sender.getUniqueId());
if (partnerUuid == null) {
sender.sendMessage(color("&cDu hast noch keine Nachricht erhalten."));
return;
}
ProxiedPlayer partner = ProxyServer.getInstance().getPlayer(partnerUuid);
if (partner == null || !partner.isConnected()) {
sender.sendMessage(color("&cDieser Spieler ist nicht mehr online."));
return;
}
send(sender, partner, message, config, bypassPermission);
}
/** Social-Spy umschalten. */
public boolean toggleSpy(UUID uuid) {
if (spyEnabled.contains(uuid)) {
spyEnabled.remove(uuid);
return false;
} else {
spyEnabled.add(uuid);
return true;
}
}
private void broadcastSpy(String formatted, String spyPermission, UUID... exclude) {
java.util.Set<UUID> excl = new java.util.HashSet<>(java.util.Arrays.asList(exclude));
for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) {
if (excl.contains(p.getUniqueId())) continue;
// Spy muss entweder via Permission aktiv oder manuell aktiviert haben
boolean hasPerm = p.hasPermission(spyPermission);
boolean hasToggle= spyEnabled.contains(p.getUniqueId());
if (hasPerm || hasToggle) {
p.sendMessage(color(formatted));
}
}
}
/**
* Formatiert eine PM-Nachricht.
* {sender} → Name des Absenders
* {receiver} → Name des Empfängers
* {player} → Gesprächspartner aus Sicht des jeweiligen Empfängers:
* Beim Sender: der Empfänger (an wen schreibt er?)
* Beim Empfänger: der Sender (von wem kommt es?)
*
* @param viewerIsSender true wenn der aktuelle Betrachter der Absender ist
*/
private String format(String template, String sender, String receiver,
String message, boolean viewerIsSender) {
String partner = viewerIsSender ? receiver : sender;
return template
.replace("{sender}", sender)
.replace("{receiver}", receiver)
.replace("{player}", partner) // Gesprächspartner aus Sicht des Betrachters
.replace("{message}", message);
}
private TextComponent color(String text) {
return new TextComponent(ChatColor.translateAlternateColorCodes('&', text));
}
}

View File

@@ -0,0 +1,227 @@
package net.viper.status.modules.chat;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
/**
* Verwaltet Spieler-Reports (/report).
*
* Reports werden mit einer eindeutigen ID (z.B. RPT-0001) gespeichert und
* bleiben offen, bis ein Admin sie explizit mit /reportclose <ID> schließt.
*
* Online-Admins werden sofort benachrichtigt.
* Offline-Admins erhalten eine verzögerte Benachrichtigung beim nächsten Login
* (gesteuert von außen via getPendingNotificationFor()).
*
* Speicherformat (chat_reports.dat):
* id|reporter|reporterUUID|reported|server|messageContext|reason|timestamp|closed|closedBy
*/
public class ReportManager {
private final File file;
private final Logger logger;
/** Alle Reports (offen und geschlossen). */
private final ConcurrentHashMap<String, ChatReport> reports = new ConcurrentHashMap<>();
/** Zähler für Report-IDs. Wird beim Laden synchronisiert. */
private final AtomicInteger idCounter = new AtomicInteger(0);
private static final SimpleDateFormat DATE_FMT = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
// ===== Report-Datenklasse =====
public static class ChatReport {
public String id;
public String reporterName;
public UUID reporterUUID;
public String reportedName;
public String server;
public String messageContext; // letzte bekannte Chatnachricht des Gemeldeten
public String reason;
public long timestamp;
public boolean closed;
public String closedBy; // Name des schließenden Admins (oder leer)
public String getFormattedTime() {
return DATE_FMT.format(new Date(timestamp));
}
}
// ===== Konstruktor =====
public ReportManager(File dataFolder, Logger logger) {
this.file = new File(dataFolder, "chat_reports.dat");
this.logger = logger;
}
// ===== Report-Logik =====
/**
* Erstellt einen neuen Report.
*
* @param reporterName Name des meldenden Spielers
* @param reporterUUID UUID des meldenden Spielers
* @param reportedName Name des gemeldeten Spielers
* @param server Server, auf dem sich der Reporter befand
* @param messageContext Letzte bekannte Nachricht des Gemeldeten (für Kontext)
* @param reason Freitext-Begründung
* @return die neue Report-ID (z.B. RPT-0001)
*/
public String createReport(String reporterName, UUID reporterUUID,
String reportedName, String server,
String messageContext, String reason) {
String id = String.format("RPT-%04d", idCounter.incrementAndGet());
ChatReport report = new ChatReport();
report.id = id;
report.reporterName = reporterName;
report.reporterUUID = reporterUUID;
report.reportedName = reportedName;
report.server = server;
report.messageContext = messageContext != null ? messageContext : "";
report.reason = reason;
report.timestamp = System.currentTimeMillis();
report.closed = false;
report.closedBy = "";
reports.put(id, report);
save();
return id;
}
/**
* Schließt einen Report.
*
* @param id Report-ID (z.B. RPT-0001, case-insensitiv)
* @param adminName Name des Admins, der den Report schließt
* @return true wenn erfolgreich geschlossen, false wenn nicht gefunden / bereits geschlossen
*/
public boolean closeReport(String id, String adminName) {
ChatReport report = getReport(id);
if (report == null || report.closed) return false;
report.closed = true;
report.closedBy = adminName;
save();
return true;
}
/** Gibt einen Report nach ID zurück (case-insensitiv). */
public ChatReport getReport(String id) {
if (id == null) return null;
return reports.get(id.toUpperCase());
}
/** Gibt alle offenen Reports chronologisch (älteste zuerst) zurück. */
public List<ChatReport> getOpenReports() {
List<ChatReport> list = new ArrayList<>();
for (ChatReport r : reports.values()) {
if (!r.closed) list.add(r);
}
list.sort(Comparator.comparingLong(r -> r.timestamp));
return list;
}
/** Gibt alle Reports chronologisch zurück (auch geschlossene). */
public List<ChatReport> getAllReports() {
List<ChatReport> list = new ArrayList<>(reports.values());
list.sort(Comparator.comparingLong(r -> r.timestamp));
return list;
}
/** Anzahl offener Reports. */
public int getOpenCount() {
int count = 0;
for (ChatReport r : reports.values()) if (!r.closed) count++;
return count;
}
// ===== Persistenz =====
public void save() {
try (BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))) {
for (ChatReport r : reports.values()) {
bw.write(
esc(r.id) + "|" +
esc(r.reporterName) + "|" +
r.reporterUUID + "|" +
esc(r.reportedName) + "|" +
esc(r.server) + "|" +
esc(r.messageContext) + "|" +
esc(r.reason) + "|" +
r.timestamp + "|" +
r.closed + "|" +
esc(r.closedBy != null ? r.closedBy : "")
);
bw.newLine();
}
} catch (IOException e) {
logger.warning("[ChatModule] Fehler beim Speichern der Reports: " + e.getMessage());
}
}
public void load() {
reports.clear();
if (!file.exists()) return;
int maxNum = 0;
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) continue;
String[] p = line.split("\\|", -1);
if (p.length < 10) continue;
try {
ChatReport r = new ChatReport();
r.id = unesc(p[0]);
r.reporterName = unesc(p[1]);
r.reporterUUID = UUID.fromString(p[2]);
r.reportedName = unesc(p[3]);
r.server = unesc(p[4]);
r.messageContext = unesc(p[5]);
r.reason = unesc(p[6]);
r.timestamp = Long.parseLong(p[7]);
r.closed = Boolean.parseBoolean(p[8]);
r.closedBy = unesc(p[9]);
reports.put(r.id.toUpperCase(), r);
// Zähler auf höchste bekannte Nummer synchronisieren
if (r.id.toUpperCase().startsWith("RPT-")) {
try {
int num = Integer.parseInt(r.id.substring(4));
if (num > maxNum) maxNum = num;
} catch (NumberFormatException ignored) {}
}
} catch (Exception ignored) {}
}
} catch (IOException e) {
logger.warning("[ChatModule] Fehler beim Laden der Reports: " + e.getMessage());
}
idCounter.set(maxNum);
}
// ===== Escape-Helfer (Pipe-Zeichen und Zeilenumbrüche escapen) =====
private static String esc(String s) {
if (s == null) return "";
return s.replace("\\", "\\\\")
.replace("|", "\\p")
.replace("\n", "\\n")
.replace("\r", "");
}
private static String unesc(String s) {
if (s == null) return "";
return s.replace("\\n", "\n")
.replace("\\p", "|")
.replace("\\\\", "\\");
}
}

View File

@@ -0,0 +1,71 @@
package net.viper.status.modules.chat;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import java.util.Collections;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* Zentrale Schnittstelle zwischen dem VanishModule und dem ChatModule.
*
* Das VanishModule (oder jedes andere Modul) ruft {@link #setVanished} auf
* um Spieler als unsichtbar zu markieren. Das ChatModule prüft via
* {@link #isVanished} bevor es Join-/Leave-Nachrichten sendet oder
* Privat-Nachrichten zulässt.
*
* Verwendung im VanishModule:
* VanishProvider.setVanished(player.getUniqueId(), true); // beim Verschwinden
* VanishProvider.setVanished(player.getUniqueId(), false); // beim Erscheinen / Disconnect
*/
public final class VanishProvider {
private VanishProvider() {}
/** Intern verwaltete Menge aller aktuell unsichtbaren Spieler-UUIDs. */
private static final Set<UUID> vanishedPlayers =
Collections.newSetFromMap(new ConcurrentHashMap<>());
// ===== Schreib-API (wird vom VanishModule aufgerufen) =====
/**
* Markiert einen Spieler als sichtbar oder unsichtbar.
*
* @param uuid UUID des Spielers
* @param vanished true = unsichtbar, false = sichtbar
*/
public static void setVanished(UUID uuid, boolean vanished) {
if (vanished) {
vanishedPlayers.add(uuid);
} else {
vanishedPlayers.remove(uuid);
}
}
/**
* Entfernt einen Spieler beim Disconnect aus der Vanish-Liste.
* Sollte vom ChatModule (onDisconnect) aufgerufen werden, damit
* kein toter Eintrag verbleibt.
*/
public static void cleanup(UUID uuid) {
vanishedPlayers.remove(uuid);
}
// ===== Lese-API (wird vom ChatModule aufgerufen) =====
/** @return true wenn der Spieler aktuell als unsichtbar markiert ist. */
public static boolean isVanished(ProxiedPlayer player) {
return player != null && vanishedPlayers.contains(player.getUniqueId());
}
/** @return true wenn der Spieler mit der angegebenen UUID unsichtbar ist. */
public static boolean isVanished(UUID uuid) {
return uuid != null && vanishedPlayers.contains(uuid);
}
/** Snapshot der aktuell unsichtbaren Spieler (für Debugging / Logs). */
public static Set<UUID> getVanishedPlayers() {
return Collections.unmodifiableSet(vanishedPlayers);
}
}

View File

@@ -0,0 +1,323 @@
package net.viper.status.modules.chat.bridge;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.plugin.Plugin;
import net.viper.status.modules.chat.AccountLinkManager;
import net.viper.status.modules.chat.ChatConfig;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;
/**
* Discord-Brücke für bidirektionale Kommunikation.
*
* Fix #12: extractJsonString() behandelt Escape-Sequenzen jetzt korrekt.
* Statt Zeichenvergleich mit dem Vorgänger-Char wird ein expliziter Escape-Flag verwendet.
*/
public class DiscordBridge {
private final Plugin plugin;
private final ChatConfig config;
private final Logger logger;
private AccountLinkManager linkManager;
private final java.util.Map<String, AtomicLong> lastMessageIds = new java.util.concurrent.ConcurrentHashMap<>();
private volatile boolean running = false;
public DiscordBridge(Plugin plugin, ChatConfig config) {
this.plugin = plugin;
this.config = config;
this.logger = plugin.getLogger();
}
public void setLinkManager(AccountLinkManager linkManager) { this.linkManager = linkManager; }
public void start() {
if (!config.isDiscordEnabled()
|| config.getDiscordBotToken().isEmpty()
|| config.getDiscordBotToken().equals("YOUR_BOT_TOKEN_HERE")) {
logger.warning("[ChatModule-Discord] Bot-Token nicht konfiguriert. Discord-Empfang deaktiviert.");
return;
}
running = true;
int interval = Math.max(2, config.getDiscordPollInterval());
plugin.getProxy().getScheduler().schedule(plugin, this::pollAllChannels, interval, interval, TimeUnit.SECONDS);
logger.info("[ChatModule-Discord] Brücke gestartet (Poll-Intervall: " + interval + "s).");
}
public void stop() { running = false; }
// ===== Minecraft → Discord =====
public void sendToDiscord(String webhookUrl, String username, String message, String avatarUrl) {
if (webhookUrl == null || webhookUrl.isEmpty()) return;
plugin.getProxy().getScheduler().runAsync(plugin, () -> {
try {
String payload = "{\"username\":\"" + escapeJson(username) + "\""
+ (avatarUrl != null && !avatarUrl.isEmpty() ? ",\"avatar_url\":\"" + avatarUrl + "\"" : "")
+ ",\"content\":\"" + escapeJson(message) + "\"}";
postJson(webhookUrl, payload, null);
} catch (Exception e) {
logger.warning("[ChatModule-Discord] Webhook-Fehler: " + e.getMessage());
}
});
}
public void sendEmbedToDiscord(String webhookUrl, String title, String description, String colorHex) {
if (webhookUrl == null || webhookUrl.isEmpty()) return;
plugin.getProxy().getScheduler().runAsync(plugin, () -> {
try {
int color = 0x5865F2;
try { color = Integer.parseInt(colorHex.replace("#", ""), 16); } catch (Exception ignored) {}
String payload = "{\"embeds\":[{\"title\":\"" + escapeJson(title) + "\""
+ ",\"description\":\"" + escapeJson(description) + "\""
+ ",\"color\":" + color + "}]}";
postJson(webhookUrl, payload, null);
} catch (Exception e) {
logger.warning("[ChatModule-Discord] Embed-Fehler: " + e.getMessage());
}
});
}
public void sendToChannel(String channelId, String message) {
if (channelId == null || channelId.isEmpty()) return;
if (config.getDiscordBotToken().isEmpty()) return;
plugin.getProxy().getScheduler().runAsync(plugin, () -> {
try {
String url = "https://discord.com/api/v10/channels/" + channelId + "/messages";
postJson(url, "{\"content\":\"" + escapeJson(message) + "\"}", "Bot " + config.getDiscordBotToken());
} catch (Exception e) {
logger.warning("[ChatModule-Discord] Send-to-Channel-Fehler: " + e.getMessage());
}
});
}
// ===== Discord → Minecraft (Polling) =====
private void pollAllChannels() {
if (!running) return;
java.util.Set<String> channelIds = new java.util.LinkedHashSet<>();
for (net.viper.status.modules.chat.ChatChannel ch : config.getChannels().values()) {
if (!ch.getDiscordChannelId().isEmpty()) channelIds.add(ch.getDiscordChannelId());
}
if (!config.getDiscordAdminChannelId().isEmpty()) channelIds.add(config.getDiscordAdminChannelId());
for (String channelId : channelIds) pollChannel(channelId);
}
private void pollChannel(String channelId) {
try {
AtomicLong lastId = lastMessageIds.computeIfAbsent(channelId, k -> new AtomicLong(0L));
if (lastId.get() == 0L) {
String initResp = getJson("https://discord.com/api/v10/channels/" + channelId + "/messages?limit=1",
"Bot " + config.getDiscordBotToken());
if (initResp != null && !initResp.equals("[]") && !initResp.isEmpty()) {
java.util.List<DiscordMessage> initMsgs = parseMessages(initResp);
if (!initMsgs.isEmpty()) lastId.set(initMsgs.get(0).id);
}
return;
}
String url = "https://discord.com/api/v10/channels/" + channelId + "/messages?after=" + lastId.get() + "&limit=10";
String response = getJson(url, "Bot " + config.getDiscordBotToken());
if (response == null || response.equals("[]") || response.isEmpty()) return;
java.util.List<DiscordMessage> messages = parseMessages(response);
messages.sort(java.util.Comparator.comparingLong(m -> m.id));
for (DiscordMessage msg : messages) {
if (msg.id <= lastId.get()) continue;
if (msg.isBot) continue;
if (msg.content.isEmpty()) continue;
lastId.set(msg.id);
if (msg.content.startsWith("!link ")) {
String token = msg.content.substring(6).trim().toUpperCase();
if (linkManager != null) {
AccountLinkManager.LinkedAccount acc = linkManager.redeemDiscord(token, msg.authorId, msg.authorName);
if (acc != null) sendToChannel(channelId, "✅ Verknüpfung erfolgreich! Minecraft-Account: **" + acc.minecraftName + "**");
else sendToChannel(channelId, "❌ Ungültiger oder abgelaufener Token. Bitte `/discordlink` im Spiel erneut ausführen.");
}
continue;
}
String displayName = (linkManager != null)
? linkManager.resolveDiscordName(msg.authorId, msg.authorName) : msg.authorName;
String mcFormat = resolveFormat(channelId);
if (mcFormat == null) continue;
String formatted = ChatColor.translateAlternateColorCodes('&',
mcFormat.replace("{user}", displayName).replace("{message}", msg.content));
ProxyServer.getInstance().getScheduler().runAsync(plugin,
() -> ProxyServer.getInstance().broadcast(new TextComponent(formatted)));
}
} catch (Exception e) {
logger.fine("[ChatModule-Discord] Poll-Fehler für Kanal " + channelId + ": " + e.getMessage());
}
}
private String resolveFormat(String channelId) {
if (channelId.equals(config.getDiscordAdminChannelId())) return config.getDiscordFromFormat();
for (net.viper.status.modules.chat.ChatChannel ch : config.getChannels().values()) {
if (channelId.equals(ch.getDiscordChannelId())) return config.getDiscordFromFormat();
}
return null;
}
// ===== HTTP =====
private void postJson(String urlStr, String payload, String authorization) throws Exception {
HttpURLConnection conn = openConnection(urlStr, "POST", authorization);
byte[] data = payload.getBytes(StandardCharsets.UTF_8);
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) { os.write(data); }
int code = conn.getResponseCode();
if (code >= 400) logger.warning("[ChatModule-Discord] HTTP " + code + ": " + readStream(conn.getErrorStream()));
conn.disconnect();
}
private String getJson(String urlStr, String authorization) throws Exception {
HttpURLConnection conn = openConnection(urlStr, "GET", authorization);
int code = conn.getResponseCode();
if (code != 200) { conn.disconnect(); return null; }
String result = readStream(conn.getInputStream());
conn.disconnect();
return result;
}
private HttpURLConnection openConnection(String urlStr, String method, String authorization) throws Exception {
HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
conn.setRequestMethod(method);
conn.setConnectTimeout(5000);
conn.setReadTimeout(8000);
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("User-Agent", "StatusAPI-ChatModule/1.0");
if (authorization != null && !authorization.isEmpty()) conn.setRequestProperty("Authorization", authorization);
return conn;
}
private String readStream(InputStream in) throws IOException {
if (in == null) return "";
try (BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder(); String line;
while ((line = br.readLine()) != null) sb.append(line);
return sb.toString();
}
}
// ===== JSON Mini-Parser =====
private static class DiscordMessage {
long id;
String authorId = "", authorName = "", content = "";
boolean isBot = false;
}
private java.util.List<DiscordMessage> parseMessages(String json) {
java.util.List<DiscordMessage> result = new java.util.ArrayList<>();
int depth = 0, start = -1;
for (int i = 0; i < json.length(); i++) {
char c = json.charAt(i);
if (c == '{') { if (depth++ == 0) start = i; }
else if (c == '}') {
if (--depth == 0 && start != -1) {
DiscordMessage msg = parseMessage(json.substring(start, i + 1));
if (msg != null) result.add(msg);
start = -1;
}
}
}
return result;
}
private DiscordMessage parseMessage(String obj) {
try {
DiscordMessage msg = new DiscordMessage();
msg.id = Long.parseLong(extractJsonString(obj, "id"));
msg.content = unescapeJson(extractJsonString(obj, "content"));
// Webhook-Nachrichten als Bot markieren (Echo-Loop verhindern)
if (!extractJsonString(obj, "webhook_id").isEmpty()) {
msg.isBot = true;
return msg;
}
int authStart = obj.indexOf("\"author\"");
if (authStart >= 0) {
String authBlock = extractJsonObject(obj, authStart);
msg.authorId = extractJsonString(authBlock, "id");
msg.authorName = unescapeJson(extractJsonString(authBlock, "username"));
msg.isBot = "true".equals(extractJsonString(authBlock, "bot"));
}
return msg;
} catch (Exception e) {
return null;
}
}
/**
* FIX #12: Escape-Sequenzen werden korrekt mit einem Escape-Flag behandelt
* statt den Vorgänger-Char zu vergleichen (der bei '\\' + '"' versagt).
* Gibt immer einen leeren String zurück wenn der Key nicht gefunden wird (nie null).
*/
private String extractJsonString(String json, String key) {
if (json == null || key == null) return "";
String fullKey = "\"" + key + "\"";
int keyIdx = json.indexOf(fullKey);
if (keyIdx < 0) return "";
int colon = json.indexOf(':', keyIdx + fullKey.length());
if (colon < 0) return "";
int valStart = colon + 1;
while (valStart < json.length() && json.charAt(valStart) == ' ') valStart++;
if (valStart >= json.length()) return "";
char first = json.charAt(valStart);
if (first == '"') {
// FIX: Expliziter Escape-Flag statt Vorgänger-Char-Vergleich
int end = valStart + 1;
boolean escaped = false;
while (end < json.length()) {
char ch = json.charAt(end);
if (escaped) {
escaped = false;
} else if (ch == '\\') {
escaped = true;
} else if (ch == '"') {
break;
}
end++;
}
return json.substring(valStart + 1, end);
} else {
int end = valStart;
while (end < json.length() && ",}\n".indexOf(json.charAt(end)) < 0) end++;
return json.substring(valStart, end).trim();
}
}
private String extractJsonObject(String json, int fromIndex) {
int depth = 0, start = -1;
for (int i = fromIndex; i < json.length(); i++) {
char c = json.charAt(i);
if (c == '{') { if (depth++ == 0) start = i; }
else if (c == '}') { if (--depth == 0 && start >= 0) return json.substring(start, i + 1); }
}
return "";
}
private static String escapeJson(String s) {
if (s == null) return "";
return s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t");
}
private static String unescapeJson(String s) {
if (s == null) return "";
return s.replace("\\\"", "\"").replace("\\n", "\n").replace("\\r", "\r").replace("\\\\", "\\");
}
}

View File

@@ -0,0 +1,399 @@
package net.viper.status.modules.chat.bridge;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.plugin.Plugin;
import net.viper.status.modules.chat.AccountLinkManager;
import net.viper.status.modules.chat.ChatConfig;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;
/**
* Telegram-Brücke für bidirektionale Kommunikation.
*
* Minecraft → Telegram: Via Bot API (sendMessage)
* Telegram → Minecraft: Via Long-Polling (getUpdates)
*
* Voraussetzungen:
* - Telegram Bot via @BotFather erstellen
* - Bot-Token in chat.yml eintragen
* - Bot in die gewünschten Gruppen/Kanäle einladen
* - Bot zu Admin machen (für Gruppen-Nachrichten empfangen)
*/
public class TelegramBridge {
private static final String API_BASE = "https://api.telegram.org/bot";
private final Plugin plugin;
private final ChatConfig config;
private final Logger logger;
private AccountLinkManager linkManager; // wird nach dem Start gesetzt
// Letztes verarbeitetes Update-ID (für getUpdates Offset)
private final AtomicLong lastUpdateId = new AtomicLong(0L);
private volatile boolean running = false;
public TelegramBridge(Plugin plugin, ChatConfig config) {
this.plugin = plugin;
this.config = config;
this.logger = plugin.getLogger();
}
/** Setzt den AccountLinkManager muss vor start() aufgerufen werden. */
public void setLinkManager(AccountLinkManager linkManager) {
this.linkManager = linkManager;
}
public void start() {
if (!config.isTelegramEnabled()
|| config.getTelegramBotToken().isEmpty()
|| config.getTelegramBotToken().equals("YOUR_TELEGRAM_BOT_TOKEN")) {
logger.warning("[ChatModule-Telegram] Bot-Token nicht konfiguriert. Telegram-Empfang deaktiviert.");
return;
}
running = true;
int interval = Math.max(2, config.getTelegramPollInterval());
plugin.getProxy().getScheduler().schedule(plugin, this::pollUpdates,
interval, interval, TimeUnit.SECONDS);
logger.info("[ChatModule-Telegram] Brücke gestartet (Poll-Intervall: " + interval + "s).");
}
public void stop() {
running = false;
}
// ===== Minecraft → Telegram =====
/**
* Sendet eine Nachricht an eine Telegram-Chat-ID.
* Unterstützt Themen-Gruppen via message_thread_id.
*/
public void sendToTelegram(String chatId, String message) {
sendToTelegram(chatId, 0, message);
}
public void sendToTelegram(String chatId, int threadId, String message) {
if (chatId == null || chatId.isEmpty()) return;
plugin.getProxy().getScheduler().runAsync(plugin, () -> {
try {
String cleanMessage = ChatColor.stripColor(
ChatColor.translateAlternateColorCodes('&', message));
String url = API_BASE + config.getTelegramBotToken()
+ "/sendMessage?chat_id=" + URLEncoder.encode(chatId, "UTF-8")
+ "&text=" + URLEncoder.encode(cleanMessage, "UTF-8")
+ "&parse_mode=HTML"
+ (threadId > 0 ? "&message_thread_id=" + threadId : "");
getJson(url);
} catch (Exception e) {
logger.warning("[ChatModule-Telegram] Sende-Fehler: " + e.getMessage());
}
});
}
/**
* Sendet eine formatierte HelpOp/Broadcast-Nachricht an Telegram.
* Unterstützt Themen-Gruppen via message_thread_id.
*/
public void sendFormattedToTelegram(String chatId, String header, String content) {
sendFormattedToTelegram(chatId, 0, header, content);
}
public void sendFormattedToTelegram(String chatId, int threadId, String header, String content) {
if (chatId == null || chatId.isEmpty()) return;
String text = "<b>" + escapeHtml(header) + "</b>\n" + escapeHtml(content);
plugin.getProxy().getScheduler().runAsync(plugin, () -> {
try {
String url = API_BASE + config.getTelegramBotToken()
+ "/sendMessage?chat_id=" + URLEncoder.encode(chatId, "UTF-8")
+ "&text=" + URLEncoder.encode(text, "UTF-8")
+ "&parse_mode=HTML"
+ (threadId > 0 ? "&message_thread_id=" + threadId : "");
getJson(url);
} catch (Exception e) {
logger.warning("[ChatModule-Telegram] Format-Sende-Fehler: " + e.getMessage());
}
});
}
// ===== Telegram → Minecraft (Polling) =====
private void pollUpdates() {
if (!running) return;
try {
// Beim ersten Poll: nur den aktuellen Offset holen, keine alten Updates verarbeiten
if (lastUpdateId.get() == 0L) {
String initUrl = API_BASE + config.getTelegramBotToken()
+ "/getUpdates?limit=1&offset=-1";
String initResp = getJson(initUrl);
if (initResp != null && initResp.contains("\"ok\":true")) {
java.util.List<TelegramUpdate> initUpdates = parseUpdates(initResp);
if (!initUpdates.isEmpty()) {
lastUpdateId.set(initUpdates.get(initUpdates.size() - 1).updateId);
}
}
return; // Erster Poll nur zum Initialisieren
}
long offset = lastUpdateId.get() + 1;
String url = API_BASE + config.getTelegramBotToken()
+ "/getUpdates?timeout=2&limit=10"
+ (offset > 0 ? "&offset=" + offset : "");
String response = getJson(url);
if (response == null || !response.contains("\"ok\":true")) return;
java.util.List<TelegramUpdate> updates = parseUpdates(response);
for (TelegramUpdate update : updates) {
if (update.updateId > lastUpdateId.get()) {
lastUpdateId.set(update.updateId);
}
if (update.text == null || update.text.isEmpty()) continue;
if (update.isBot) continue;
// ── Token-Einlösung: /link <TOKEN> ──
if (update.text.startsWith("/link ") || update.text.startsWith("/link@")) {
String[] parts = update.text.split("\\s+", 2);
if (parts.length == 2 && linkManager != null) {
String token = parts[1].trim().toUpperCase();
AccountLinkManager.LinkedAccount acc =
linkManager.redeemTelegram(token, update.fromId, update.fromName);
if (acc != null) {
sendToTelegram(update.chatId, update.threadId,
"✅ Verknüpfung erfolgreich! Minecraft-Account: <b>"
+ escapeHtml(acc.minecraftName) + "</b>");
} else {
sendToTelegram(update.chatId, update.threadId,
"❌ Ungültiger oder abgelaufener Token. Bitte /telegramlink im Spiel erneut ausführen.");
}
}
continue; // Nicht als Chat-Nachricht weiterleiten
}
// Bot-Befehle ignorieren
if (update.text.startsWith("/")) continue;
// ── Account-Name auflösen ──
String displayName = (linkManager != null)
? linkManager.resolveTelegramName(update.fromId, update.fromName)
: update.fromName;
// Welchem Minecraft-Kanal gehört diese Telegram-Chat-ID + Thread?
final boolean isAdminChat = update.chatId.equals(config.getTelegramAdminChatId())
&& (config.getTelegramAdminTopicId() == 0
|| config.getTelegramAdminTopicId() == update.threadId);
// Prüfen ob die Nachricht zu einem konfigurierten Kanal-Thema gehört
final boolean matchesChannel = isAdminChat || matchesTelegramChannel(update);
if (!matchesChannel && !isAdminChat) continue;
final String format = config.getTelegramFromFormat();
final String finalDisplay = displayName;
final String formatted = ChatColor.translateAlternateColorCodes('&',
format.replace("{user}", finalDisplay)
.replace("{message}", update.text));
ProxyServer.getInstance().getScheduler().runAsync(plugin, () -> {
if (isAdminChat) {
for (net.md_5.bungee.api.connection.ProxiedPlayer p :
ProxyServer.getInstance().getPlayers()) {
if (p.hasPermission("chat.admin.bypass")) {
p.sendMessage(new TextComponent(formatted));
}
}
} else {
ProxyServer.getInstance().broadcast(new TextComponent(formatted));
}
});
}
} catch (Exception e) {
logger.fine("[ChatModule-Telegram] Poll-Fehler: " + e.getMessage());
}
}
// ===== HTTP-Hilfsmethoden =====
private String getJson(String urlStr) throws Exception {
HttpURLConnection conn = (HttpURLConnection) new URL(urlStr).openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(6000);
conn.setReadTimeout(10000);
conn.setRequestProperty("User-Agent", "StatusAPI-ChatModule/1.0");
int code = conn.getResponseCode();
String result = readStream(code == 200 ? conn.getInputStream() : conn.getErrorStream());
conn.disconnect();
return result;
}
private String readStream(InputStream in) throws IOException {
if (in == null) return "";
try (BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) sb.append(line);
return sb.toString();
}
}
// ===== JSON Mini-Parser =====
private static class TelegramUpdate {
long updateId;
String chatId = "";
String fromId = ""; // Telegram User-ID (für Account-Link)
String fromName = "";
String text = "";
boolean isBot = false;
int threadId = 0; // message_thread_id für Themen-Gruppen (0 = kein Thema)
}
private java.util.List<TelegramUpdate> parseUpdates(String json) {
java.util.List<TelegramUpdate> result = new java.util.ArrayList<>();
// Suche nach "result":[...]
int resultStart = json.indexOf("\"result\":[");
if (resultStart < 0) return result;
// Extrahiere alle Update-Objekte
int depth = 0, start = -1;
boolean inResult = false;
for (int i = resultStart + 10; i < json.length(); i++) {
char c = json.charAt(i);
if (c == '[' && !inResult) { inResult = true; continue; }
if (!inResult) continue;
if (c == '{') { if (depth++ == 0) start = i; }
else if (c == '}') {
if (--depth == 0 && start >= 0) {
TelegramUpdate upd = parseUpdate(json.substring(start, i + 1));
if (upd != null) result.add(upd);
start = -1;
}
} else if (c == ']' && depth == 0) break;
}
return result;
}
/** Prüft ob ein Update zu einem konfigurierten Kanal-Thema gehört. */
private boolean matchesTelegramChannel(TelegramUpdate update) {
for (net.viper.status.modules.chat.ChatChannel ch : config.getChannels().values()) {
if (!ch.getTelegramChatId().equals(update.chatId)) continue;
// Thema konfiguriert? → Thread-ID muss übereinstimmen
if (ch.getTelegramThreadId() > 0 && ch.getTelegramThreadId() != update.threadId) continue;
return true;
}
return false;
}
private TelegramUpdate parseUpdate(String obj) {
try {
TelegramUpdate upd = new TelegramUpdate();
upd.updateId = Long.parseLong(extractValue(obj, "update_id"));
// message-Block
int msgIdx = obj.indexOf("\"message\"");
if (msgIdx < 0) return null;
String msgBlock = extractObject(obj, msgIdx);
upd.text = unescapeJson(extractString(msgBlock, "text"));
// message_thread_id (Themen-Gruppen)
String threadIdStr = extractValue(msgBlock, "message_thread_id");
if (!threadIdStr.isEmpty()) {
try { upd.threadId = Integer.parseInt(threadIdStr); } catch (Exception ignored) {}
}
// from-Block (Absender)
int fromIdx = msgBlock.indexOf("\"from\"");
if (fromIdx >= 0) {
String fromBlock = extractObject(msgBlock, fromIdx);
String firstName = unescapeJson(extractString(fromBlock, "first_name"));
String lastName = unescapeJson(extractString(fromBlock, "last_name"));
String username = unescapeJson(extractString(fromBlock, "username"));
upd.fromId = extractValue(fromBlock, "id");
upd.fromName = !username.isEmpty() ? "@" + username
: (firstName + (lastName.isEmpty() ? "" : " " + lastName)).trim();
String botFlag = extractValue(fromBlock, "is_bot");
upd.isBot = "true".equals(botFlag);
}
// chat-Block (Chat-ID)
int chatIdx = msgBlock.indexOf("\"chat\"");
if (chatIdx >= 0) {
String chatBlock = extractObject(msgBlock, chatIdx);
upd.chatId = extractValue(chatBlock, "id");
}
return upd;
} catch (Exception e) {
return null;
}
}
private String extractValue(String json, String key) {
String fullKey = "\"" + key + "\"";
int idx = json.indexOf(fullKey);
if (idx < 0) return "";
int colon = json.indexOf(':', idx + fullKey.length());
if (colon < 0) return "";
int valStart = colon + 1;
while (valStart < json.length() && json.charAt(valStart) == ' ') valStart++;
if (valStart >= json.length()) return "";
char first = json.charAt(valStart);
if (first == '"') {
return extractString(json.substring(valStart - 1 - key.length()), key);
}
int end = valStart;
while (end < json.length() && ",}\n".indexOf(json.charAt(end)) < 0) end++;
return json.substring(valStart, end).trim();
}
private String extractString(String json, String key) {
String fullKey = "\"" + key + "\":\"";
int idx = json.indexOf(fullKey);
if (idx < 0) return "";
int start = idx + fullKey.length();
int end = start;
while (end < json.length()) {
if (json.charAt(end) == '"' && json.charAt(end - 1) != '\\') break;
end++;
}
return json.substring(start, end);
}
private String extractObject(String json, int fromIndex) {
int depth = 0, start = -1;
for (int i = fromIndex; i < json.length(); i++) {
char c = json.charAt(i);
if (c == '{') { if (depth++ == 0) start = i; }
else if (c == '}') { if (--depth == 0 && start >= 0) return json.substring(start, i + 1); }
}
return "";
}
private static String unescapeJson(String s) {
if (s == null) return "";
return s.replace("\\\"", "\"").replace("\\n", "\n")
.replace("\\r", "\r").replace("\\\\", "\\");
}
private static String escapeHtml(String s) {
if (s == null) return "";
return s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;");
}
}

View File

@@ -0,0 +1,245 @@
package net.viper.status.modules.commandblocker;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.ChatEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.event.EventHandler;
import net.viper.status.StatusAPI;
import net.viper.status.module.Module;
import net.viper.status.ratelimit.GlobalRateLimitFramework;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import org.yaml.snakeyaml.Yaml;
@SuppressWarnings({"unchecked", "rawtypes"})
public class CommandBlockerModule implements Module, Listener {
private StatusAPI plugin;
private boolean enabled = true; // Standardmäßig aktiv
private String bypassPermission = "commandblocker.bypass"; // Standard Permission
private File file;
private Set<String> blocked = new HashSet<>();
private final GlobalRateLimitFramework rateLimiter = GlobalRateLimitFramework.getInstance();
private boolean commandRateLimitEnabled = true;
private long commandRateLimitWindowMs = 3000L;
private int commandRateLimitMaxActions = 8;
private long commandRateLimitBlockMs = 6000L;
private String commandRateLimitMessage = "&cZu viele Befehle in kurzer Zeit. Bitte warte kurz.";
@Override
public String getName() {
return "CommandBlockerModule";
}
@Override
public void onEnable(Plugin plugin) {
if (!(plugin instanceof StatusAPI)) return; // Sicherheit
this.plugin = (StatusAPI) plugin;
// Datei laden
file = new File(this.plugin.getDataFolder(), "blocked-commands.yml");
loadFile();
// Listener registrieren
ProxyServer.getInstance().getPluginManager().registerListener(this.plugin, this);
// /cb Befehl registrieren
ProxyServer.getInstance().getPluginManager().registerCommand(this.plugin,
new net.md_5.bungee.api.plugin.Command("cb", "commandblocker.admin") {
@Override
public void execute(CommandSender sender, String[] args) {
handleCommand(sender, args);
}
});
this.plugin.getLogger().info("[CommandBlocker] aktiviert (" + blocked.size() + " Commands).");
}
@Override
public void onDisable(Plugin plugin) {
blocked.clear();
}
@EventHandler
public void onCommand(ChatEvent event) {
if (!enabled || !event.isCommand()) return;
if (!(event.getSender() instanceof ProxiedPlayer)) return;
ProxiedPlayer player = (ProxiedPlayer) event.getSender();
if (player.hasPermission(bypassPermission)) return;
String msg = event.getMessage();
if (msg == null || msg.length() <= 1) return;
if (commandRateLimitEnabled) {
GlobalRateLimitFramework.Result result = rateLimiter.check(
"chat.command",
player.getUniqueId().toString(),
new GlobalRateLimitFramework.Rule(
true,
commandRateLimitWindowMs,
commandRateLimitMaxActions,
commandRateLimitBlockMs
)
);
if (result.isBlocked()) {
event.setCancelled(true);
player.sendMessage(ChatColor.translateAlternateColorCodes('&', commandRateLimitMessage));
return;
}
}
String cmd = msg.substring(1).toLowerCase(Locale.ROOT);
String base = cmd.split(" ")[0];
if (blocked.contains(base)) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "Dieser Befehl ist auf diesem Netzwerk blockiert.");
}
}
private void handleCommand(CommandSender sender, String[] args) {
if (args == null || args.length == 0) {
sender.sendMessage(ChatColor.YELLOW + "/cb add <command>");
sender.sendMessage(ChatColor.YELLOW + "/cb remove <command>");
sender.sendMessage(ChatColor.YELLOW + "/cb list");
sender.sendMessage(ChatColor.YELLOW + "/cb reload");
return;
}
String action = args[0].toLowerCase();
switch (action) {
case "add":
if (args.length < 2) break;
blocked.add(args[1].toLowerCase());
saveFile();
sender.sendMessage(ChatColor.GREEN + "Command blockiert: " + args[1]);
break;
case "remove":
if (args.length < 2) break;
blocked.remove(args[1].toLowerCase());
saveFile();
sender.sendMessage(ChatColor.GREEN + "Command freigegeben: " + args[1]);
break;
case "list":
sender.sendMessage(ChatColor.GOLD + "Blockierte Commands:");
for (String c : blocked) {
sender.sendMessage(ChatColor.RED + "- " + c);
}
break;
case "reload":
loadFile();
sender.sendMessage(ChatColor.GREEN + "CommandBlocker neu geladen.");
break;
default:
sender.sendMessage(ChatColor.RED + "Unbekannter Unterbefehl.");
break;
}
}
private void loadFile() {
try {
if (!file.exists()) {
File parent = file.getParentFile();
if (parent != null && !parent.exists()) parent.mkdirs();
file.createNewFile();
saveFile();
}
Yaml yaml = new Yaml();
Map<String, Object> data = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
data = yaml.loadAs(fis, Map.class);
} finally {
if (fis != null) try { fis.close(); } catch (IOException ignored) {}
}
blocked.clear();
if (data != null && data.containsKey("blocked")) {
Object obj = data.get("blocked");
if (obj instanceof List) {
List list = (List) obj;
for (Object o : list) {
if (o != null) blocked.add(String.valueOf(o).toLowerCase());
}
}
}
if (data != null && data.containsKey("rate-limit")) {
Object rlObj = data.get("rate-limit");
if (rlObj instanceof Map) {
Map rl = (Map) rlObj;
commandRateLimitEnabled = parseBoolean(rl.get("enabled"), commandRateLimitEnabled);
commandRateLimitWindowMs = parseLong(rl.get("window-ms"), commandRateLimitWindowMs);
commandRateLimitMaxActions = (int) parseLong(rl.get("max-actions"), commandRateLimitMaxActions);
commandRateLimitBlockMs = parseLong(rl.get("block-ms"), commandRateLimitBlockMs);
Object msgObj = rl.get("message");
if (msgObj != null) {
commandRateLimitMessage = String.valueOf(msgObj);
}
}
}
} catch (Exception e) {
if (plugin != null) plugin.getLogger().severe("[CommandBlocker] Fehler beim Laden: " + e.getMessage());
else System.err.println("[CommandBlocker] Fehler beim Laden: " + e.getMessage());
}
}
private void saveFile() {
try {
Yaml yaml = new Yaml();
Map<String, Object> out = new LinkedHashMap<>();
out.put("blocked", new ArrayList<>(blocked));
Map<String, Object> rl = new LinkedHashMap<>();
rl.put("enabled", commandRateLimitEnabled);
rl.put("window-ms", commandRateLimitWindowMs);
rl.put("max-actions", commandRateLimitMaxActions);
rl.put("block-ms", commandRateLimitBlockMs);
rl.put("message", commandRateLimitMessage);
out.put("rate-limit", rl);
FileWriter fw = null;
try {
fw = new FileWriter(file);
yaml.dump(out, fw);
} finally {
if (fw != null) try { fw.close(); } catch (IOException ignored) {}
}
} catch (IOException e) {
if (plugin != null) plugin.getLogger().severe("[CommandBlocker] Fehler beim Speichern: " + e.getMessage());
else System.err.println("[CommandBlocker] Fehler beim Speichern: " + e.getMessage());
}
}
private boolean parseBoolean(Object obj, boolean fallback) {
if (obj == null) return fallback;
return Boolean.parseBoolean(String.valueOf(obj));
}
private long parseLong(Object obj, long fallback) {
if (obj == null) return fallback;
try {
return Long.parseLong(String.valueOf(obj));
} catch (Exception ignored) {
return fallback;
}
}
}

View File

@@ -0,0 +1,242 @@
package net.viper.status.modules.customcommands;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.ChatEvent;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin; // Import für das Interface Argument
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import net.md_5.bungee.event.EventHandler;
import net.viper.status.StatusAPI;
import net.viper.status.module.Module;
public class CustomCommandModule implements Module, Listener {
private StatusAPI plugin;
private Configuration config;
private Command chatCommand;
public CustomCommandModule() {
// Leerer Konstruktor
}
@Override
public String getName() {
return "CustomCommandModule";
}
@Override
public void onEnable(Plugin plugin) {
// Hier casten wir 'Plugin' zu 'StatusAPI', da wir wissen, dass es das ist
this.plugin = (StatusAPI) plugin;
this.plugin.getLogger().info("Lade CustomCommandModule...");
reloadConfig();
if (this.config == null) {
this.config = new Configuration();
this.plugin.getLogger().warning("customcommands.yml konnte nicht geladen werden. Verwende leere Konfiguration.");
}
// /bcmds Reload Befehl registrieren
this.plugin.getProxy().getPluginManager().registerCommand(this.plugin, new Command("bcmds") {
@Override
public void execute(CommandSender sender, String[] args) {
if (!sender.hasPermission("statusapi.bcmds")) {
sender.sendMessage(new TextComponent(ChatColor.RED + "You don't have permission."));
} else {
reloadConfig();
sender.sendMessage(new TextComponent(ChatColor.GREEN + "Config reloaded."));
}
}
});
// /chat Befehl registrieren (falls aktiviert)
if (config.getBoolean("chat-command", true)) {
chatCommand = new Command("chat") {
@Override
public void execute(CommandSender sender, String[] args) {
if (sender instanceof ProxiedPlayer) {
ProxiedPlayer player = (ProxiedPlayer) sender;
if (player.getServer() == null) {
player.sendMessage(new TextComponent(ChatColor.RED + "Konnte deinen Server nicht ermitteln. Bitte versuche es erneut."));
return;
}
String msg = String.join(" ", args);
if (msg.trim().isEmpty()) {
player.sendMessage(new TextComponent(ChatColor.RED + "Bitte gib eine Nachricht an."));
return;
}
ChatEvent e = new ChatEvent(player, player.getServer(), msg);
ProxyServer.getInstance().getPluginManager().callEvent(e);
if (!e.isCancelled()) {
if (!e.isCommand() || !ProxyServer.getInstance().getPluginManager().dispatchCommand(sender, msg.substring(1))) {
player.chat(msg);
}
}
} else {
String msg = String.join(" ", args);
if(msg.startsWith("/")) {
ProxyServer.getInstance().getPluginManager().dispatchCommand(sender, msg.substring(1));
} else {
sender.sendMessage(new TextComponent("Console cannot send chat messages via /chat usually."));
}
}
}
};
this.plugin.getProxy().getPluginManager().registerCommand(this.plugin, chatCommand);
}
this.plugin.getProxy().getPluginManager().registerListener(this.plugin, this);
}
@Override
public void onDisable(Plugin plugin) {
// Optional: Cleanup logic, falls nötig.
// Wir nutzen hier das übergebene 'plugin' Argument (oder this.plugin, ist egal)
// Listener und Commands werden automatisch entfernt, wenn das Plugin stoppt.
}
public void reloadConfig() {
try {
if (!this.plugin.getDataFolder().exists()) {
this.plugin.getDataFolder().mkdirs();
}
File file = new File(this.plugin.getDataFolder(), "customcommands.yml");
if (!file.exists()) {
// Kopieren aus Resources
InputStream in = this.plugin.getResourceAsStream("customcommands.yml");
if (in == null) {
this.plugin.getLogger().warning("customcommands.yml nicht in JAR gefunden. Erstelle leere Datei.");
file.createNewFile();
} else {
Files.copy(in, file.toPath(), new CopyOption[0]);
in.close();
}
}
this.config = ConfigurationProvider.getProvider(YamlConfiguration.class).load(file);
} catch (IOException e) {
e.printStackTrace();
this.plugin.getLogger().severe("Konnte customcommands.yml nicht laden!");
}
}
@EventHandler(priority = 64)
public void onCommand(ChatEvent e) {
if (!e.isCommand()) return;
if (!(e.getSender() instanceof ProxiedPlayer)) return;
final ProxiedPlayer player = (ProxiedPlayer) e.getSender();
String[] split = e.getMessage().split(" ");
String label = split[0].substring(1);
final List<String> args = new ArrayList<>(Arrays.asList(split));
args.remove(0);
Configuration cmds = config.getSection("commands");
if (cmds == null) return;
Configuration section = null;
String foundKey = null;
for (String key : cmds.getKeys()) {
Configuration cmdSection = cmds.getSection(key);
if (key.equalsIgnoreCase(label)) {
section = cmdSection;
foundKey = key;
break;
}
for (String alias : cmdSection.getStringList("aliases")) {
if (alias.equalsIgnoreCase(label)) {
section = cmdSection;
foundKey = key;
break;
}
}
if (section != null) break;
}
if (section == null) return;
String type = section.getString("type", "line");
String sendertype = section.getString("sender", "default");
String permission = section.getString("permission", "");
final List<String> commands = section.getStringList("commands");
if (!permission.isEmpty() && !player.hasPermission(permission)) {
player.sendMessage(new TextComponent(ChatColor.RED + "You don't have permission."));
e.setCancelled(true);
return;
}
e.setCancelled(true);
final CommandSender target;
if (sendertype.equals("default")) {
target = player;
} else if (sendertype.equals("admin")) {
target = new ForwardSender(player, true);
} else if (sendertype.equals("console")) {
target = ProxyServer.getInstance().getConsole();
} else {
ProxiedPlayer targetPlayer = ProxyServer.getInstance().getPlayer(sendertype);
if (targetPlayer == null || !targetPlayer.isConnected()) {
player.sendMessage(new TextComponent(ChatColor.RED + "Player " + sendertype + " is not online."));
return;
}
target = targetPlayer;
}
String argsString = args.size() >= 1 ? String.join(" ", args) : "";
final String finalArgs = argsString;
final String senderName = player.getName();
if (type.equals("random")) {
int randomIndex = new Random().nextInt(commands.size());
String rawCommand = commands.get(randomIndex);
executeCommand(target, rawCommand, finalArgs, senderName);
} else if (type.equals("line")) {
ProxyServer.getInstance().getScheduler().runAsync(this.plugin, new Runnable() {
@Override
public void run() {
for (String rawCommand : commands) {
executeCommand(target, rawCommand, finalArgs, senderName);
try {
Thread.sleep(100L);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
});
} else {
this.plugin.getLogger().warning("Unknown type '" + type + "' for command " + foundKey);
}
}
private void executeCommand(CommandSender sender, String rawCommand, String args, String playerName) {
String parsed = rawCommand
.replace("%args%", args)
.replace("%sender%", playerName);
String commandToDispatch = parsed.startsWith("/") ? parsed.substring(1) : parsed;
ProxyServer.getInstance().getPluginManager().dispatchCommand(sender, commandToDispatch);
}
}

View File

@@ -0,0 +1,118 @@
package net.viper.status.modules.customcommands;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Collection;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.connection.Connection;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.connection.Connection.Unsafe;
public class ForwardSender implements CommandSender, Connection {
private ProxiedPlayer target;
private Boolean admin;
public ForwardSender(ProxiedPlayer sender, Boolean admin) {
this.target = sender;
this.admin = admin;
}
public ProxiedPlayer target() {
return this.target;
}
@Override
public String getName() {
return this.target.getName();
}
@Override
public void sendMessage(String message) {
this.target.sendMessage(message);
}
@Override
public void sendMessages(String... messages) {
this.target.sendMessages(messages);
}
@Override
public void sendMessage(BaseComponent... message) {
this.target.sendMessage(message);
}
@Override
public void sendMessage(BaseComponent message) {
this.target.sendMessage(message);
}
@Override
public Collection<String> getGroups() {
return this.target.getGroups();
}
@Override
public void addGroups(String... groups) {
this.target.addGroups(groups);
}
@Override
public void removeGroups(String... groups) {
this.target.removeGroups(groups);
}
@Override
public boolean hasPermission(String permission) {
return this.admin ? true : this.target.hasPermission(permission);
}
@Override
public void setPermission(String permission, boolean value) {
this.target.setPermission(permission, value);
}
@Override
public Collection<String> getPermissions() {
Collection<String> perms = new java.util.ArrayList<>(this.target.getPermissions());
if (this.admin) {
perms.add("*");
}
return perms;
}
@Override
public InetSocketAddress getAddress() {
return this.target.getAddress();
}
@Override
public SocketAddress getSocketAddress() {
return this.target.getSocketAddress();
}
@Override
public void disconnect(String reason) {
this.target.disconnect(reason);
}
@Override
public void disconnect(BaseComponent... reason) {
this.target.disconnect(reason);
}
@Override
public void disconnect(BaseComponent reason) {
this.target.disconnect(reason);
}
@Override
public boolean isConnected() {
return this.target.isConnected();
}
@Override
public Unsafe unsafe() {
return this.target.unsafe();
}
}

View File

@@ -0,0 +1,134 @@
package net.viper.status.modules.economy;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.Plugin;
import java.util.UUID;
/**
* /ecoadmin <give|take|set|check> <Spieler> [Betrag]
* Admin-Verwaltung des Economy-Systems (auch für Offline-Spieler).
*
* Berechtigung: economy.admin
*/
public class EcoAdminCommand extends Command {
private final Plugin plugin;
private final EconomyManager manager;
public EcoAdminCommand(Plugin plugin, EconomyManager manager) {
super("ecoadmin", "economy.admin", "ecomod", "moneyadmin");
this.plugin = plugin;
this.manager = manager;
}
@Override
public void execute(CommandSender sender, String[] args) {
if (!sender.hasPermission("economy.admin")) {
sender.sendMessage(new TextComponent(c("&cKeine Berechtigung.")));
return;
}
if (args.length < 2) {
sendHelp(sender);
return;
}
String action = args[0].toLowerCase();
String targetName = args[1];
plugin.getProxy().getScheduler().runAsync(plugin, () -> {
UUID targetUUID = manager.resolveUUID(targetName);
if (targetUUID == null) {
sender.sendMessage(new TextComponent(c("&cSpieler &e" + targetName + " &cnicht gefunden.")));
return;
}
switch (action) {
case "check": {
double bal = manager.getBalance(targetUUID);
sender.sendMessage(new TextComponent(c("&7Kontostand von &e" + targetName
+ "&7: &a" + formatAmount(bal) + " $")));
break;
}
case "give": {
if (args.length < 3) { sendHelp(sender); return; }
double amount = parseAmount(args[2]);
if (amount <= 0) { sender.sendMessage(new TextComponent(c("&cUngültiger Betrag."))); return; }
manager.deposit(targetUUID, amount);
double newBal = manager.getBalance(targetUUID);
sender.sendMessage(new TextComponent(c("&a+ " + formatAmount(amount)
+ " $ &7an &e" + targetName + " &7→ Neues Guthaben: &a" + formatAmount(newBal) + " $")));
notifyPlayer(targetUUID, c("&7Admin hat dir &a+" + formatAmount(amount)
+ " $ &7gegeben. Guthaben: &a" + formatAmount(newBal) + " $"));
break;
}
case "take": {
if (args.length < 3) { sendHelp(sender); return; }
double amount = parseAmount(args[2]);
if (amount <= 0) { sender.sendMessage(new TextComponent(c("&cUngültiger Betrag."))); return; }
boolean ok = manager.withdraw(targetUUID, amount);
if (!ok) {
sender.sendMessage(new TextComponent(c("&cNicht genug Guthaben bei &e" + targetName + "&c.")));
return;
}
double newBal = manager.getBalance(targetUUID);
sender.sendMessage(new TextComponent(c("&c- " + formatAmount(amount)
+ " $ &7von &e" + targetName + " &7→ Neues Guthaben: &a" + formatAmount(newBal) + " $")));
notifyPlayer(targetUUID, c("&7Admin hat dir &c-" + formatAmount(amount)
+ " $ &7abgezogen. Guthaben: &a" + formatAmount(newBal) + " $"));
break;
}
case "set": {
if (args.length < 3) { sendHelp(sender); return; }
double amount = parseAmount(args[2]);
if (amount < 0) { sender.sendMessage(new TextComponent(c("&cBetrag darf nicht negativ sein."))); return; }
manager.setBalance(targetUUID, amount);
sender.sendMessage(new TextComponent(c("&7Guthaben von &e" + targetName
+ " &7gesetzt auf &a" + formatAmount(amount) + " $")));
notifyPlayer(targetUUID, c("&7Dein Guthaben wurde auf &a" + formatAmount(amount) + " $ &7gesetzt."));
break;
}
default:
sendHelp(sender);
}
});
}
private void notifyPlayer(UUID uuid, String message) {
ProxiedPlayer target = plugin.getProxy().getPlayer(uuid);
if (target != null) {
target.sendMessage(new TextComponent(message));
}
}
private void sendHelp(CommandSender sender) {
sender.sendMessage(new TextComponent(c("&e/ecoadmin check <Spieler>")));
sender.sendMessage(new TextComponent(c("&e/ecoadmin give <Spieler> <Betrag>")));
sender.sendMessage(new TextComponent(c("&e/ecoadmin take <Spieler> <Betrag>")));
sender.sendMessage(new TextComponent(c("&e/ecoadmin set <Spieler> <Betrag>")));
}
private static double parseAmount(String s) {
try { return Double.parseDouble(s.replace(",", ".")); }
catch (NumberFormatException e) { return -1; }
}
private static String formatAmount(double amount) {
return String.format("%,.2f", amount);
}
private static String c(String msg) {
return ChatColor.translateAlternateColorCodes('&', msg);
}
}

View File

@@ -0,0 +1,183 @@
package net.viper.status.modules.economy;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import net.md_5.bungee.api.plugin.Plugin;
import java.sql.*;
import java.util.UUID;
import java.util.logging.Logger;
/**
* Verwaltet die MySQL-Verbindung (HikariCP) und die Tabelle bc_accounts.
* Wird vom EconomyModule gehalten und an den EconomyManager weitergegeben.
*/
public class EconomyDatabase {
private static final String TABLE = "bc_accounts";
private final Logger log;
private HikariDataSource dataSource;
public EconomyDatabase(Plugin plugin, String host, int port, String database, String user, String password) {
this.log = plugin.getLogger();
HikariConfig cfg = new HikariConfig();
cfg.setJdbcUrl("jdbc:mysql://" + host + ":" + port + "/" + database
+ "?useSSL=false&autoReconnect=true&characterEncoding=UTF-8&useUnicode=true");
cfg.setUsername(user);
cfg.setPassword(password);
cfg.setMaximumPoolSize(5);
cfg.setMinimumIdle(1);
cfg.setConnectionTimeout(10_000);
cfg.setIdleTimeout(600_000);
cfg.setMaxLifetime(1_800_000);
cfg.setPoolName("StatusAPI-Economy");
cfg.addDataSourceProperty("cachePrepStmts", "true");
cfg.addDataSourceProperty("prepStmtCacheSize", "250");
cfg.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
try {
dataSource = new HikariDataSource(cfg);
} catch (Exception e) {
log.severe("[Economy] MySQL-Verbindung fehlgeschlagen: " + e.getMessage());
log.severe("[Economy] Bitte Zugangsdaten in verify.properties prüfen!");
return;
}
// Tabelle anlegen falls nicht vorhanden (kompatibel mit SurvivalPlus)
try (Connection con = dataSource.getConnection();
PreparedStatement ps = con.prepareStatement(
"CREATE TABLE IF NOT EXISTS `" + TABLE + "` (" +
" `player_name` VARCHAR(36) NOT NULL," +
" `balance` VARCHAR(255) NOT NULL DEFAULT '0'," +
" PRIMARY KEY (`player_name`)" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;")) {
ps.executeUpdate();
} catch (SQLException e) {
log.severe("[Economy] Tabellen-Setup (bc_accounts) fehlgeschlagen: " + e.getMessage());
}
// bc_player_names Tabelle anlegen
try (Connection con = dataSource.getConnection();
PreparedStatement ps = con.prepareStatement(
"CREATE TABLE IF NOT EXISTS `bc_player_names` (" +
" `uuid` VARCHAR(36) NOT NULL PRIMARY KEY," +
" `name` VARCHAR(16) NOT NULL," +
" `updated` BIGINT NOT NULL" +
") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;")) {
ps.executeUpdate();
log.info("[Economy] MySQL verbunden Tabellen bereit.");
} catch (SQLException e) {
log.severe("[Economy] Tabellen-Setup (bc_player_names) fehlgeschlagen: " + e.getMessage());
}
}
public boolean isConnected() {
return dataSource != null && !dataSource.isClosed();
}
public void close() {
if (dataSource != null && !dataSource.isClosed()) {
dataSource.close();
}
}
/**
* Sucht UUID in CMI_users nutzt eine separate DB-Verbindung falls
* economy.cmi.database konfiguriert ist, sonst dieselbe DB.
*/
public java.util.UUID findUUIDByName(String name) {
if (!isConnected()) return null;
try (Connection con = dataSource.getConnection();
PreparedStatement ps = con.prepareStatement(
"SELECT `player_uuid` FROM `CMI_users` WHERE `username` = ? LIMIT 1")) {
ps.setString(1, name);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
String uuidStr = rs.getString("player_uuid");
if (uuidStr != null && !uuidStr.isEmpty()) {
return java.util.UUID.fromString(uuidStr);
}
}
}
} catch (SQLException | IllegalArgumentException e) {
// CMI_users nicht in dieser DB kein Problem, bc_player_names ist der Primär-Lookup
}
return null;
}
/** Speichert den Spielernamen in einer eigenen Lookup-Tabelle. */
public void saveNameMapping(java.util.UUID uuid, String name) {
if (!isConnected()) return;
try (Connection con = dataSource.getConnection();
PreparedStatement ps = con.prepareStatement(
"INSERT INTO `bc_player_names` (`uuid`, `name`, `updated`) VALUES (?, ?, ?) " +
"ON DUPLICATE KEY UPDATE `name` = VALUES(`name`), `updated` = VALUES(`updated`)")) {
ps.setString(1, uuid.toString());
ps.setString(2, name);
ps.setLong(3, System.currentTimeMillis());
ps.executeUpdate();
} catch (SQLException e) {
log.warning("[Economy] Name-Mapping fehlgeschlagen: " + e.getMessage());
}
}
/** UUID-Lookup über bc_player_names (eigene Tabelle). */
public java.util.UUID findUUIDByNameOwn(String name) {
if (!isConnected()) return null;
try (Connection con = dataSource.getConnection();
PreparedStatement ps = con.prepareStatement(
"SELECT `uuid` FROM `bc_player_names` WHERE `name` = ? LIMIT 1")) {
ps.setString(1, name);
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return java.util.UUID.fromString(rs.getString("uuid"));
}
}
} catch (SQLException | IllegalArgumentException e) {
// Tabelle noch nicht vorhanden
}
return null;
}
/** Kombinierter UUID-Lookup: erst eigene Tabelle, dann CMI_users. */
public java.util.UUID resolveUUID(String name) {
java.util.UUID uuid = findUUIDByNameOwn(name);
if (uuid != null) return uuid;
return findUUIDByName(name);
}
/** Lädt den Kontostand direkt aus der DB. Gibt -1 zurück wenn kein Eintrag. */
public double load(UUID uuid) {
if (!isConnected()) return -1;
try (Connection con = dataSource.getConnection();
PreparedStatement ps = con.prepareStatement(
"SELECT `balance` FROM `" + TABLE + "` WHERE `player_name` = ?")) {
ps.setString(1, uuid.toString());
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
return Double.parseDouble(rs.getString("balance"));
}
}
} catch (SQLException | NumberFormatException e) {
log.warning("[Economy] Load fehlgeschlagen für " + uuid + ": " + e.getMessage());
}
return -1;
}
/** Schreibt einen Kontostand in die DB (INSERT oder UPDATE). */
public void save(UUID uuid, double balance) {
if (!isConnected()) return;
try (Connection con = dataSource.getConnection();
PreparedStatement ps = con.prepareStatement(
"INSERT INTO `" + TABLE + "` (`player_name`, `balance`) VALUES (?, ?) " +
"ON DUPLICATE KEY UPDATE `balance` = VALUES(`balance`)")) {
ps.setString(1, uuid.toString());
ps.setString(2, String.valueOf(balance));
ps.executeUpdate();
} catch (SQLException e) {
log.warning("[Economy] Save fehlgeschlagen für " + uuid + ": " + e.getMessage());
}
}
}

View File

@@ -0,0 +1,33 @@
package net.viper.status.modules.economy;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.event.EventHandler;
public class EconomyListener implements Listener {
private final Plugin plugin;
private final EconomyManager manager;
public EconomyListener(Plugin plugin, EconomyManager manager) {
this.plugin = plugin;
this.manager = manager;
}
/**
* Beim ersten Login: Konto anlegen falls noch nicht vorhanden.
* Kein Caching alle weiteren Zugriffe gehen direkt in die DB.
*/
@EventHandler
public void onLogin(PostLoginEvent event) {
ProxiedPlayer player = event.getPlayer();
plugin.getProxy().getScheduler().runAsync(plugin, () -> {
// Namen für Offline-Lookup speichern
manager.saveNameMapping(player.getUniqueId(), player.getName());
// Konto anlegen falls neu
manager.getBalance(player.getUniqueId());
});
}
}

View File

@@ -0,0 +1,109 @@
package net.viper.status.modules.economy;
import net.md_5.bungee.api.plugin.Plugin;
import java.util.UUID;
/**
* Kein Cache jeder Zugriff geht direkt in die Datenbank.
* Damit ist der Kontostand immer aktuell, egal von welchem Server
* er zuletzt geändert wurde (SurvivalPlus, CMI, etc.).
*/
public class EconomyManager {
private final Plugin plugin;
private final EconomyDatabase db;
private final double startBalance;
public EconomyManager(Plugin plugin, EconomyDatabase db, double startBalance) {
this.plugin = plugin;
this.db = db;
this.startBalance = startBalance;
}
public void saveNameMapping(UUID uuid, String name) {
db.saveNameMapping(uuid, name);
}
public UUID resolveUUID(String name) {
// 1. Online-Spieler auf dem Proxy (case-insensitive)
for (net.md_5.bungee.api.connection.ProxiedPlayer p : plugin.getProxy().getPlayers()) {
if (p.getName().equalsIgnoreCase(name)) return p.getUniqueId();
}
// 2. Eigene bc_player_names Tabelle
UUID uuid = db.findUUIDByNameOwn(name);
if (uuid != null) return uuid;
// 3. CMI_users Fallback
uuid = db.findUUIDByName(name);
if (uuid != null) return uuid;
// 4. Mojang API als letzter Ausweg
return lookupMojang(name);
}
/** UUID via Mojang API holen (nur wenn alle lokalen Lookups fehlschlagen). */
private UUID lookupMojang(String name) {
try {
java.net.URL url = new java.net.URL("https://api.mojang.com/users/profiles/minecraft/" + name);
java.net.HttpURLConnection con = (java.net.HttpURLConnection) url.openConnection();
con.setConnectTimeout(3000);
con.setReadTimeout(3000);
con.setRequestMethod("GET");
if (con.getResponseCode() != 200) return null;
java.io.BufferedReader br = new java.io.BufferedReader(
new java.io.InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) sb.append(line);
br.close();
String json = sb.toString();
int idIdx = json.indexOf("\"id\":\"");
if (idIdx < 0) return null;
String raw = json.substring(idIdx + 6, idIdx + 38);
String formatted = raw.replaceFirst(
"(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5");
UUID uuid = UUID.fromString(formatted);
// Für künftige Lookups speichern
db.saveNameMapping(uuid, name);
plugin.getLogger().info("[Economy] Mojang-Lookup: " + name + "" + uuid);
return uuid;
} catch (Exception e) {
plugin.getLogger().warning("[Economy] Mojang-Lookup fehlgeschlagen für " + name + ": " + e.getMessage());
return null;
}
}
public double getBalance(UUID uuid) {
double bal = db.load(uuid);
if (bal < 0) {
// Neuer Spieler Startkonto anlegen
db.save(uuid, startBalance);
return startBalance;
}
return bal;
}
public void setBalance(UUID uuid, double amount) {
db.save(uuid, Math.max(0.0, amount));
}
public boolean deposit(UUID uuid, double amount) {
if (amount <= 0) return false;
double current = db.load(uuid);
if (current < 0) current = startBalance;
db.save(uuid, current + amount);
return true;
}
public boolean withdraw(UUID uuid, double amount) {
if (amount <= 0) return false;
double current = db.load(uuid);
if (current < 0) current = 0;
if (current < amount) return false;
db.save(uuid, current - amount);
return true;
}
public boolean hasAccount(UUID uuid) {
return db.load(uuid) >= 0;
}
}

View File

@@ -0,0 +1,95 @@
package net.viper.status.modules.economy;
import net.md_5.bungee.api.plugin.Plugin;
import net.viper.status.StatusAPI;
import net.viper.status.module.Module;
import java.util.Properties;
/**
* EconomyModule serverübergreifendes Geldkonto über MySQL (bc_accounts).
*
* Konfiguration in verify.properties:
* economy.mysql.host=localhost
* economy.mysql.port=3306
* economy.mysql.database=survivalplus
* economy.mysql.username=root
* economy.mysql.password=
* economy.start-balance=500.0
*
* Das Modul registriert sich im Modul-System der StatusAPI und hält
* EconomyDatabase + EconomyManager, die von SurvivalPlus und allen
* anderen Servern über die gemeinsame bc_accounts-Tabelle genutzt werden.
*/
public class EconomyModule implements Module {
private EconomyDatabase database;
private EconomyManager manager;
@Override
public String getName() {
return "EconomyModule";
}
@Override
public void onEnable(Plugin plugin) {
// Konfiguration aus verify.properties laden
Properties props = ((StatusAPI) plugin).getVerifyProperties();
String host = getProp(props, "economy.mysql.host", "localhost");
int port = getInt (props, "economy.mysql.port", 3306);
String database = getProp(props, "economy.mysql.database", "survivalplus");
String user = getProp(props, "economy.mysql.username", "root");
String password = getProp(props, "economy.mysql.password", "");
double startBal = getDbl (props, "economy.start-balance", 500.0);
this.database = new EconomyDatabase(plugin, host, port, database, user, password);
if (!this.database.isConnected()) {
plugin.getLogger().severe("[Economy] Modul wird NICHT aktiviert keine DB-Verbindung.");
return;
}
this.manager = new EconomyManager(plugin, this.database, startBal);
// Listener registrieren (Login → load, Disconnect → save)
plugin.getProxy().getPluginManager().registerListener(plugin, new EconomyListener(plugin, manager));
plugin.getProxy().getPluginManager().registerCommand(plugin, new PayCommand(plugin, manager));
plugin.getProxy().getPluginManager().registerCommand(plugin, new EcoAdminCommand(plugin, manager));
plugin.getLogger().info("[Economy] EconomyModule aktiviert (start-balance: " + startBal + ").");
}
@Override
public void onDisable(Plugin plugin) {
if (database != null) {
database.close();
plugin.getLogger().info("[Economy] MySQL-Verbindung geschlossen.");
}
}
/** Gibt den EconomyManager zurück (für andere Module oder HTTP-Endpoints). */
public EconomyManager getManager() {
return manager;
}
// ----------------------------------------------------------------
// Hilfsmethoden
// ----------------------------------------------------------------
private static String getProp(Properties p, String key, String def) {
if (p == null) return def;
String v = p.getProperty(key, def);
return (v == null || v.trim().isEmpty()) ? def : v.trim();
}
private static int getInt(Properties p, String key, int def) {
try { return Integer.parseInt(getProp(p, key, String.valueOf(def))); }
catch (NumberFormatException e) { return def; }
}
private static double getDbl(Properties p, String key, double def) {
try { return Double.parseDouble(getProp(p, key, String.valueOf(def))); }
catch (NumberFormatException e) { return def; }
}
}

View File

@@ -0,0 +1,102 @@
package net.viper.status.modules.economy;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.Plugin;
import java.util.UUID;
/**
* /pay <Spieler> <Betrag>
* Überweist Geld an einen anderen Spieler (auch offline).
*/
public class PayCommand extends Command {
private final Plugin plugin;
private final EconomyManager manager;
public PayCommand(Plugin plugin, EconomyManager manager) {
super("pay", null);
this.plugin = plugin;
this.manager = manager;
}
@Override
public void execute(CommandSender sender, String[] args) {
if (!(sender instanceof ProxiedPlayer)) {
sender.sendMessage(new TextComponent(c("&cNur Spieler können diesen Befehl nutzen.")));
return;
}
if (args.length < 2) {
sender.sendMessage(new TextComponent(c("&eVerwendung: &f/pay <Spieler> <Betrag>")));
return;
}
ProxiedPlayer payer = (ProxiedPlayer) sender;
String targetName = args[0];
double amount;
try {
amount = Double.parseDouble(args[1].replace(",", "."));
} catch (NumberFormatException e) {
sender.sendMessage(new TextComponent(c("&cUngültiger Betrag.")));
return;
}
if (amount <= 0) {
sender.sendMessage(new TextComponent(c("&cDer Betrag muss größer als 0 sein.")));
return;
}
if (targetName.equalsIgnoreCase(payer.getName())) {
sender.sendMessage(new TextComponent(c("&cDu kannst dir nicht selbst Geld überweisen.")));
return;
}
plugin.getProxy().getScheduler().runAsync(plugin, () -> {
UUID targetUUID = manager.resolveUUID(targetName);
if (targetUUID == null) {
payer.sendMessage(new TextComponent(c("&cSpieler &e" + targetName + " &cnicht gefunden.")));
return;
}
double payerBalance = manager.getBalance(payer.getUniqueId());
if (payerBalance < amount) {
payer.sendMessage(new TextComponent(c("&cNicht genug Guthaben. Dein Kontostand: &e"
+ formatAmount(payerBalance) + " $")));
return;
}
manager.withdraw(payer.getUniqueId(), amount);
manager.deposit(targetUUID, amount);
payer.sendMessage(new TextComponent(c("&aErfolgreich &e" + formatAmount(amount)
+ " $ &aan &e" + targetName + " &aüberwiesen.")));
payer.sendMessage(new TextComponent(c("&7Dein neues Guthaben: &e"
+ formatAmount(manager.getBalance(payer.getUniqueId())) + " $")));
// Online-Benachrichtigung an Empfänger
ProxiedPlayer target = plugin.getProxy().getPlayer(targetUUID);
if (target != null) {
target.sendMessage(new TextComponent(c("&a" + payer.getName()
+ " hat dir &e" + formatAmount(amount) + " $ &aüberwiesen.")));
target.sendMessage(new TextComponent(c("&7Dein neues Guthaben: &e"
+ formatAmount(manager.getBalance(targetUUID)) + " $")));
}
});
}
private static String formatAmount(double amount) {
return String.format("%,.2f", amount);
}
private static String c(String msg) {
return ChatColor.translateAlternateColorCodes('&', msg);
}
}

View File

@@ -0,0 +1,336 @@
package net.viper.status.modules.forum;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.event.EventHandler;
import net.viper.status.module.Module;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
/**
* ForumBridgeModule: Verbindet das WP Business Forum mit dem Minecraft-Server.
*
* Fix #13: extractJsonString() gibt jetzt immer einen leeren String statt null zurück.
* Alle Aufrufer müssen nicht mehr auf null prüfen, was NullPointerExceptions verhindert.
*/
public class ForumBridgeModule implements Module, Listener {
private Plugin plugin;
private ForumNotifStorage storage;
private boolean enabled = true;
private String wpBaseUrl = "";
private String apiSecret = "";
private int loginDelaySeconds = 3;
@Override
public String getName() { return "ForumBridgeModule"; }
@Override
public void onEnable(Plugin plugin) {
this.plugin = plugin;
loadConfig(plugin);
if (!enabled) { plugin.getLogger().info("ForumBridgeModule ist deaktiviert."); return; }
storage = new ForumNotifStorage(plugin.getDataFolder(), plugin.getLogger());
storage.load();
plugin.getProxy().getPluginManager().registerListener(plugin, this);
ProxyServer.getInstance().getPluginManager().registerCommand(plugin, new ForumLinkCommand());
ProxyServer.getInstance().getPluginManager().registerCommand(plugin, new ForumCommand());
plugin.getProxy().getScheduler().schedule(plugin, () -> {
try { storage.save(); } catch (Exception e) { plugin.getLogger().warning("ForumBridge Auto-Save Fehler: " + e.getMessage()); }
}, 10, 10, TimeUnit.MINUTES);
plugin.getProxy().getScheduler().schedule(plugin, () -> storage.purgeOld(30), 1, 24, TimeUnit.HOURS);
plugin.getLogger().info("ForumBridgeModule aktiviert.");
}
@Override
public void onDisable(Plugin plugin) {
if (storage != null) { storage.save(); plugin.getLogger().info("Forum-Benachrichtigungen gespeichert."); }
}
private void loadConfig(Plugin plugin) {
try {
Properties props = new Properties();
File configFile = new File(plugin.getDataFolder(), "verify.properties");
if (configFile.exists()) {
try (FileInputStream fis = new FileInputStream(configFile)) { props.load(fis); }
}
this.enabled = !"false".equalsIgnoreCase(props.getProperty("forum.enabled", "true"));
this.wpBaseUrl = props.getProperty("forum.wp_url", props.getProperty("wp_verify_url", ""));
this.apiSecret = props.getProperty("forum.api_secret", "");
this.loginDelaySeconds = parseInt(props.getProperty("forum.login_delay_seconds", "3"), 3);
} catch (Exception e) {
plugin.getLogger().warning("Fehler beim Laden der ForumBridge-Config: " + e.getMessage());
}
}
private int parseInt(String s, int def) { try { return Integer.parseInt(s); } catch (Exception e) { return def; } }
// ===== HTTP HANDLER =====
public String handleNotify(String body, String apiKeyHeader) {
if (!apiSecret.isEmpty() && !apiSecret.equals(apiKeyHeader)) {
return "{\"success\":false,\"error\":\"unauthorized\"}";
}
// FIX #13: extractJsonString gibt "" statt null → kein NullPointerException möglich
String playerUuid = extractJsonString(body, "player_uuid");
String type = extractJsonString(body, "type");
String title = extractJsonString(body, "title");
String author = extractJsonString(body, "author");
String url = extractJsonString(body, "url");
if (playerUuid.isEmpty()) return "{\"success\":false,\"error\":\"missing_player_uuid\"}";
java.util.UUID uuid;
try { uuid = java.util.UUID.fromString(playerUuid); }
catch (Exception e) { return "{\"success\":false,\"error\":\"invalid_uuid\"}"; }
if ("thread".equalsIgnoreCase(type) && title.toLowerCase().contains("umfrage")) type = "poll";
if (type.isEmpty()) type = "reply";
// Alle Werte sind garantiert nicht null (extractJsonString gibt "" zurück)
ForumNotification notification = new ForumNotification(uuid, type, title, author, url);
ProxiedPlayer online = ProxyServer.getInstance().getPlayer(uuid);
if (online != null && online.isConnected()) {
deliverNotification(online, notification);
notification.setDelivered(true);
return "{\"success\":true,\"delivered\":true}";
}
storage.add(notification);
return "{\"success\":true,\"delivered\":false}";
}
public String handleUnlink(String body, String apiKeyHeader) {
if (!apiSecret.isEmpty() && !apiSecret.equals(apiKeyHeader)) return "{\"success\":false,\"error\":\"unauthorized\"}";
return "{\"success\":true}";
}
public String handleStatus() {
String version = "unknown";
try { if (plugin.getDescription() != null) version = plugin.getDescription().getVersion(); } catch (Exception ignored) {}
return "{\"success\":true,\"module\":\"ForumBridgeModule\",\"version\":\"" + version + "\"}";
}
// ===== NOTIFICATION =====
private void deliverNotification(ProxiedPlayer player, ForumNotification notif) {
String color = notif.getTypeColor();
String label = notif.getTypeLabel();
player.sendMessage(new TextComponent("§8§m "));
player.sendMessage(new TextComponent("§6§l✉ Forum §8» " + color + label));
if (!notif.getTitle().isEmpty()) player.sendMessage(new TextComponent("§7 " + notif.getTitle()));
if (!notif.getAuthor().isEmpty()) player.sendMessage(new TextComponent("§7 von §f" + notif.getAuthor()));
if (!notif.getUrl().isEmpty()) {
TextComponent link = new TextComponent("§a ➜ Im Forum ansehen");
link.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, notif.getUrl()));
link.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT,
new ComponentBuilder("§7Klicke um den Beitrag im Forum zu öffnen").create()));
player.sendMessage(link);
}
player.sendMessage(new TextComponent("§8§m "));
}
private void deliverPending(ProxiedPlayer player) {
List<ForumNotification> pending = storage.getPending(player.getUniqueId());
if (pending.isEmpty()) return;
int count = pending.size();
if (count > 3) {
player.sendMessage(new TextComponent("§8§m "));
player.sendMessage(new TextComponent("§6§l✉ Forum §8» §fDu hast §e" + count + " §fneue Benachrichtigungen!"));
player.sendMessage(new TextComponent("§7 Tippe §e/forum §7um sie anzuzeigen."));
player.sendMessage(new TextComponent("§8§m "));
} else {
for (ForumNotification n : pending) deliverNotification(player, n);
}
storage.markAllDelivered(player.getUniqueId());
storage.clearDelivered(player.getUniqueId());
}
@EventHandler
public void onJoin(PostLoginEvent e) {
ProxiedPlayer player = e.getPlayer();
plugin.getProxy().getScheduler().schedule(plugin, () -> {
if (player.isConnected()) deliverPending(player);
}, loginDelaySeconds, TimeUnit.SECONDS);
}
// ===== COMMANDS =====
private class ForumLinkCommand extends Command {
public ForumLinkCommand() { super("forumlink", null, "fl"); }
@Override
public void execute(CommandSender sender, String[] args) {
if (!(sender instanceof ProxiedPlayer)) { sender.sendMessage(new TextComponent("§cNur Spieler können diesen Befehl benutzen.")); return; }
ProxiedPlayer p = (ProxiedPlayer) sender;
if (args.length != 1) {
p.sendMessage(new TextComponent("§eBenutzung: §f/forumlink <token>"));
p.sendMessage(new TextComponent("§7Den Token erhältst du in deinem Forum-Profil unter §fMinecraft-Verknüpfung§7."));
return;
}
String token = args[0].trim().toUpperCase();
if (wpBaseUrl.isEmpty()) { p.sendMessage(new TextComponent("§cForum-Verknüpfung ist nicht konfiguriert.")); return; }
p.sendMessage(new TextComponent("§7Überprüfe Token..."));
plugin.getProxy().getScheduler().runAsync(plugin, () -> {
try {
String endpoint = wpBaseUrl + "/wp-json/mc-bridge/v1/verify-link";
String payload = "{\"token\":\"" + escapeJson(token) + "\","
+ "\"mc_uuid\":\"" + p.getUniqueId() + "\","
+ "\"mc_name\":\"" + escapeJson(p.getName()) + "\"}";
HttpURLConnection conn = (HttpURLConnection) new URL(endpoint).openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setConnectTimeout(5000);
conn.setReadTimeout(7000);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
if (!apiSecret.isEmpty()) conn.setRequestProperty("X-Api-Key", apiSecret);
Charset utf8 = Charset.forName("UTF-8");
try (OutputStream os = conn.getOutputStream()) { os.write(payload.getBytes(utf8)); }
int code = conn.getResponseCode();
String resp = code >= 200 && code < 300
? streamToString(conn.getInputStream(), utf8)
: streamToString(conn.getErrorStream(), utf8);
if (resp != null && resp.contains("\"success\":true")) {
String displayName = extractJsonString(resp, "display_name");
String username = extractJsonString(resp, "username");
String show = !displayName.isEmpty() ? displayName : username;
p.sendMessage(new TextComponent("§8§m "));
p.sendMessage(new TextComponent("§a§l✓ §fForum-Account erfolgreich verknüpft!"));
if (!show.isEmpty()) p.sendMessage(new TextComponent("§7 Forum-User: §f" + show));
p.sendMessage(new TextComponent("§7 Du erhältst jetzt Ingame-Benachrichtigungen."));
p.sendMessage(new TextComponent("§8§m "));
} else {
String error = extractJsonString(resp, "error");
String message = extractJsonString(resp, "message");
if ("token_expired".equals(error)) p.sendMessage(new TextComponent("§c✗ Der Token ist abgelaufen."));
else if ("uuid_already_linked".equals(error)) p.sendMessage(new TextComponent("§c✗ " + (!message.isEmpty() ? message : "Diese UUID ist bereits verknüpft.")));
else if ("invalid_token".equals(error)) p.sendMessage(new TextComponent("§c✗ Ungültiger Token."));
else p.sendMessage(new TextComponent("§c✗ Verknüpfung fehlgeschlagen: " + (!error.isEmpty() ? error : "Unbekannter Fehler")));
}
} catch (Exception ex) {
p.sendMessage(new TextComponent("§c✗ Fehler bei der Verbindung zum Forum."));
plugin.getLogger().warning("ForumLink Fehler: " + ex.getMessage());
}
});
}
}
private class ForumCommand extends Command {
public ForumCommand() { super("forum"); }
@Override
public void execute(CommandSender sender, String[] args) {
if (!(sender instanceof ProxiedPlayer)) { sender.sendMessage(new TextComponent("§cNur Spieler können diesen Befehl benutzen.")); return; }
ProxiedPlayer p = (ProxiedPlayer) sender;
List<ForumNotification> pending = storage.getPending(p.getUniqueId());
if (pending.isEmpty()) {
p.sendMessage(new TextComponent("§7Keine neuen Forum-Benachrichtigungen."));
if (!wpBaseUrl.isEmpty()) {
TextComponent link = new TextComponent("§a➜ Forum öffnen");
link.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, wpBaseUrl));
link.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("§7Klicke um das Forum zu öffnen").create()));
p.sendMessage(link);
}
return;
}
p.sendMessage(new TextComponent("§8§m "));
p.sendMessage(new TextComponent("§6§l✉ Forum-Benachrichtigungen §8(§f" + pending.size() + "§8)"));
p.sendMessage(new TextComponent(""));
int shown = 0;
for (ForumNotification n : pending) {
if (shown >= 10) { p.sendMessage(new TextComponent("§7 ... und " + (pending.size() - 10) + " weitere")); break; }
String color = n.getTypeColor();
TextComponent line = new TextComponent(color + "" + n.getTypeLabel() + "§7: ");
TextComponent detail = new TextComponent(!n.getTitle().isEmpty() ? "§f" + n.getTitle() : "§fvon " + n.getAuthor());
if (!n.getUrl().isEmpty()) {
detail.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, n.getUrl()));
detail.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("§7Klicke zum Öffnen").create()));
}
line.addExtra(detail);
p.sendMessage(line);
shown++;
}
p.sendMessage(new TextComponent(""));
p.sendMessage(new TextComponent("§8§m "));
storage.markAllDelivered(p.getUniqueId());
storage.clearDelivered(p.getUniqueId());
}
}
// ===== HELPER =====
public ForumNotifStorage getStorage() { return storage; }
/**
* FIX #13: Gibt immer einen leeren String zurück, niemals null.
* Verhindert NullPointerExceptions in allen Aufrufern.
*/
private static String extractJsonString(String json, String key) {
if (json == null || key == null) return "";
String search = "\"" + key + "\"";
int idx = json.indexOf(search);
if (idx < 0) return "";
int colon = json.indexOf(':', idx + search.length());
if (colon < 0) return "";
int i = colon + 1;
while (i < json.length() && Character.isWhitespace(json.charAt(i))) i++;
if (i >= json.length()) return "";
char c = json.charAt(i);
if (c == '"') {
i++;
StringBuilder sb = new StringBuilder();
boolean escape = false;
while (i < json.length()) {
char ch = json.charAt(i++);
if (escape) { sb.append(ch); escape = false; }
else { if (ch == '\\') escape = true; else if (ch == '"') break; else sb.append(ch); }
}
return sb.toString();
}
return "";
}
private static String escapeJson(String s) {
if (s == null) return "";
return s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r");
}
private static String streamToString(InputStream in, Charset charset) throws IOException {
if (in == null) return "";
try (BufferedReader br = new BufferedReader(new InputStreamReader(in, charset))) {
StringBuilder sb = new StringBuilder(); String line;
while ((line = br.readLine()) != null) sb.append(line);
return sb.toString();
}
}
}

View File

@@ -0,0 +1,127 @@
package net.viper.status.modules.forum;
import java.io.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Logger;
/**
* Speichert ausstehende Forum-Benachrichtigungen (Datei-basiert).
* Benachrichtigungen die nicht sofort zugestellt werden konnten (Spieler offline)
* werden hier gespeichert und beim nächsten Login zugestellt.
*/
public class ForumNotifStorage {
private final File file;
private final Logger logger;
// UUID -> Liste ausstehender Notifications
private final ConcurrentHashMap<UUID, CopyOnWriteArrayList<ForumNotification>> pending = new ConcurrentHashMap<>();
public ForumNotifStorage(File pluginFolder, Logger logger) {
if (!pluginFolder.exists()) pluginFolder.mkdirs();
this.file = new File(pluginFolder, "forum_notifications.dat");
this.logger = logger;
}
/**
* Fügt eine Benachrichtigung hinzu.
*/
public void add(ForumNotification notification) {
pending.computeIfAbsent(notification.getPlayerUuid(), k -> new CopyOnWriteArrayList<>())
.add(notification);
}
/**
* Gibt alle ausstehenden (nicht zugestellten) Benachrichtigungen eines Spielers zurück.
*/
public List<ForumNotification> getPending(UUID playerUuid) {
CopyOnWriteArrayList<ForumNotification> list = pending.get(playerUuid);
if (list == null) return Collections.emptyList();
List<ForumNotification> result = new ArrayList<>();
for (ForumNotification n : list) {
if (!n.isDelivered()) result.add(n);
}
return result;
}
/**
* Anzahl ausstehender Benachrichtigungen.
*/
public int getPendingCount(UUID playerUuid) {
CopyOnWriteArrayList<ForumNotification> list = pending.get(playerUuid);
if (list == null) return 0;
int count = 0;
for (ForumNotification n : list) {
if (!n.isDelivered()) count++;
}
return count;
}
/**
* Markiert alle Benachrichtigungen eines Spielers als zugestellt und entfernt sie.
*/
public void clearDelivered(UUID playerUuid) {
CopyOnWriteArrayList<ForumNotification> list = pending.get(playerUuid);
if (list == null) return;
list.removeIf(ForumNotification::isDelivered);
if (list.isEmpty()) pending.remove(playerUuid);
}
/**
* Markiert alle als zugestellt.
*/
public void markAllDelivered(UUID playerUuid) {
CopyOnWriteArrayList<ForumNotification> list = pending.get(playerUuid);
if (list == null) return;
for (ForumNotification n : list) {
n.setDelivered(true);
}
}
/**
* Entfernt Benachrichtigungen die älter als maxDays Tage sind.
*/
public void purgeOld(int maxDays) {
long cutoff = System.currentTimeMillis() - ((long) maxDays * 24 * 60 * 60 * 1000);
for (Map.Entry<UUID, CopyOnWriteArrayList<ForumNotification>> entry : pending.entrySet()) {
entry.getValue().removeIf(n -> n.getTimestamp() < cutoff);
if (entry.getValue().isEmpty()) pending.remove(entry.getKey());
}
}
// ===== Datei-Operationen =====
public void save() {
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))) {
for (CopyOnWriteArrayList<ForumNotification> list : pending.values()) {
for (ForumNotification n : list) {
if (!n.isDelivered()) {
bw.write(n.toLine());
bw.newLine();
}
}
}
bw.flush();
} catch (IOException e) {
logger.warning("Fehler beim Speichern der Forum-Benachrichtigungen: " + e.getMessage());
}
}
public void load() {
if (!file.exists()) return;
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"))) {
String line;
while ((line = br.readLine()) != null) {
ForumNotification n = ForumNotification.fromLine(line);
if (n != null && !n.isDelivered()) {
pending.computeIfAbsent(n.getPlayerUuid(), k -> new CopyOnWriteArrayList<>())
.add(n);
}
}
} catch (IOException e) {
logger.warning("Fehler beim Laden der Forum-Benachrichtigungen: " + e.getMessage());
}
}
}

View File

@@ -0,0 +1,114 @@
package net.viper.status.modules.forum;
import java.util.UUID;
/**
* Eine einzelne Forum-Benachrichtigung.
*/
public class ForumNotification {
private final UUID playerUuid;
private final String type; // reply, mention, message
private final String title;
private final String author;
private final String url;
private final long timestamp;
private boolean delivered;
public ForumNotification(UUID playerUuid, String type, String title, String author, String url) {
this.playerUuid = playerUuid;
this.type = type != null ? type : "reply";
this.title = title != null ? title : "";
this.author = author != null ? author : "Unbekannt";
this.url = url != null ? url : "";
this.timestamp = System.currentTimeMillis();
this.delivered = false;
}
/** Interner Konstruktor für Deserialisierung */
ForumNotification(UUID playerUuid, String type, String title, String author, String url, long timestamp, boolean delivered) {
this.playerUuid = playerUuid;
this.type = type;
this.title = title;
this.author = author;
this.url = url;
this.timestamp = timestamp;
this.delivered = delivered;
}
// --- Getter ---
public UUID getPlayerUuid() { return playerUuid; }
public String getType() { return type; }
public String getTitle() { return title; }
public String getAuthor() { return author; }
public String getUrl() { return url; }
public long getTimestamp() { return timestamp; }
public boolean isDelivered() { return delivered; }
public void setDelivered(boolean d) { this.delivered = d; }
/**
* Deutsches Label für den Benachrichtigungstyp.
*/
public String getTypeLabel() {
switch (type) {
case "reply": return "Neue Antwort";
case "mention": return "Erwähnung";
case "message": return "Neue PN";
case "thread": return "Neuer Thread";
case "poll": return "Neue Umfrage";
case "answer": return "Antwort auf deinen Thread";
default: return "Benachrichtigung";
}
}
/**
* Farbcode (Minecraft) je nach Typ.
*/
public String getTypeColor() {
switch (type) {
case "reply": return "§b"; // Aqua
case "mention": return "§e"; // Gelb
case "message": return "§d"; // Rosa
case "thread": return "§a"; // Grün
case "poll": return "§3"; // Dunkel-Aqua
case "answer": return "§2"; // Dunkel-Grün
default: return "§f"; // Weiß
}
}
/**
* Serialisierung für Datei-Speicherung.
* Format: uuid|type|title|author|url|timestamp|delivered
*/
public String toLine() {
return playerUuid.toString() + "|"
+ type + "|"
+ title.replace("|", "_") + "|"
+ author.replace("|", "_") + "|"
+ url.replace("|", "_") + "|"
+ timestamp + "|"
+ (delivered ? "1" : "0");
}
/**
* Deserialisierung aus einer Zeile.
*/
public static ForumNotification fromLine(String line) {
if (line == null || line.trim().isEmpty()) return null;
String[] parts = line.split("\\|", -1);
if (parts.length < 7) return null;
try {
UUID uuid = UUID.fromString(parts[0]);
String type = parts[1];
String title = parts[2];
String author = parts[3];
String url = parts[4];
long timestamp = Long.parseLong(parts[5]);
boolean delivered = "1".equals(parts[6]);
return new ForumNotification(uuid, type, title, author, url, timestamp, delivered);
} catch (Exception e) {
return null;
}
}
}

View File

@@ -0,0 +1,851 @@
package net.viper.status.modules.network;
import com.sun.management.OperatingSystemMXBean;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.api.scheduler.ScheduledTask;
import net.viper.status.module.Module;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.lang.management.ManagementFactory;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* Liefert erweiterte Proxy- und Systeminformationen für API und Ingame-Debug.
*/
public class NetworkInfoModule implements Module {
private static final String CONFIG_FILE_NAME = "network-guard.properties";
private Plugin plugin;
private long startedAtMillis;
private boolean enabled = true;
private boolean commandEnabled = true;
private boolean includePlayerNames = false;
private boolean webhookEnabled = false;
private String webhookUrl = "";
private String webhookUsername = "StatusAPI";
private String webhookThumbnailUrl = "";
private boolean webhookNotifyStartStop = true;
private String webhookEmbedMode = "detailed";
private int webhookCheckSeconds = 30;
private int alertMemoryPercent = 90;
private int alertPlayerPercent = 95;
private int alertCooldownSeconds = 300;
private boolean alertTpsEnabled = true;
private double alertTpsThreshold = 18.0D;
private boolean attackNotificationsEnabled = true;
private String attackApiKey = "";
private String attackDefaultSource = "Viper-Network";
private long lastMemoryAlertAt = 0L;
private long lastPlayerAlertAt = 0L;
private long lastTpsAlertAt = 0L;
private volatile double currentProxyTps = 20.0D;
private long lastTpsSampleAtMs = 0L;
private ScheduledTask alertTask;
private ScheduledTask tpsSamplerTask;
@Override
public String getName() {
return "NetworkInfoModule";
}
@Override
public void onEnable(Plugin plugin) {
this.plugin = plugin;
this.startedAtMillis = System.currentTimeMillis();
ensureModuleConfigExists();
loadConfig();
if (!enabled) {
return;
}
if (commandEnabled) {
ProxyServer.getInstance().getPluginManager().registerCommand(plugin, new NetInfoCommand());
}
tpsSamplerTask = ProxyServer.getInstance().getScheduler().schedule(plugin, this::sampleProxyTps, 1, 1, TimeUnit.SECONDS);
if (webhookEnabled && !webhookUrl.isEmpty()) {
if (webhookNotifyStartStop) {
boolean delivered = sendLifecycleStartNotification();
if (!delivered) {
plugin.getLogger().warning("[NetworkInfoModule] Start-Webhook konnte nicht direkt zugestellt werden. Wiederhole in 10 Sekunden.");
ProxyServer.getInstance().getScheduler().schedule(plugin, () -> {
boolean retryDelivered = sendLifecycleStartNotification();
if (!retryDelivered) {
plugin.getLogger().warning("[NetworkInfoModule] Start-Webhook auch beim zweiten Versuch fehlgeschlagen.");
}
}, 10L, TimeUnit.SECONDS);
}
}
int interval = Math.max(10, webhookCheckSeconds);
alertTask = ProxyServer.getInstance().getScheduler().schedule(plugin, this::evaluateAndSendAlerts, interval, interval, TimeUnit.SECONDS);
}
}
@Override
public void onDisable(Plugin plugin) {
if (alertTask != null) {
alertTask.cancel();
alertTask = null;
}
if (tpsSamplerTask != null) {
tpsSamplerTask.cancel();
tpsSamplerTask = null;
}
if (enabled && webhookEnabled && webhookNotifyStartStop && webhookUrl != null && !webhookUrl.isEmpty()) {
boolean delivered = sendLifecycleStopNotification();
if (!delivered) {
plugin.getLogger().warning("[NetworkInfoModule] Stop-Webhook konnte nicht zugestellt werden.");
}
}
}
private boolean sendLifecycleStartNotification() {
if (isCompactEmbedMode()) {
return sendWebhookEmbed(
webhookUrl,
"✅ NetworkInfo gestartet",
"Proxy: **" + ProxyServer.getInstance().getName() + "**\nÜberwachung und Webhook-Alerts sind jetzt aktiv.",
0x2ECC71,
null,
false
);
}
StringBuilder fields = new StringBuilder();
appendEmbedField(fields, "Proxy", ProxyServer.getInstance().getName(), true);
appendEmbedField(fields, "Modus", "Detailed", true);
appendEmbedField(fields, "Check-Intervall", Math.max(10, webhookCheckSeconds) + "s", true);
return sendWebhookEmbed(
webhookUrl,
"✅ NetworkInfo gestartet",
"Überwachung und Webhook-Alerts sind jetzt aktiv.",
0x2ECC71,
fields.toString(),
false
);
}
private boolean sendLifecycleStopNotification() {
if (isCompactEmbedMode()) {
return sendWebhookEmbed(
webhookUrl,
"🛑 NetworkInfo gestoppt",
"Die NetworkInfo-Überwachung wurde gestoppt.\nKeine weiteren Auto-Alerts bis zum nächsten Start.",
0xE74C3C,
null,
false
);
}
StringBuilder fields = new StringBuilder();
appendEmbedField(fields, "Proxy", ProxyServer.getInstance().getName(), true);
appendEmbedField(fields, "Modus", "Detailed", true);
appendEmbedField(fields, "Status", "Monitoring pausiert", false);
return sendWebhookEmbed(
webhookUrl,
"🛑 NetworkInfo gestoppt",
"Die NetworkInfo-Überwachung wurde gestoppt.",
0xE74C3C,
fields.toString(),
false
);
}
public boolean isEnabled() {
return enabled;
}
public boolean isAttackNotificationsEnabled() {
return enabled && attackNotificationsEnabled;
}
public boolean isAttackApiKeyValid(String providedKey) {
if (attackApiKey == null || attackApiKey.isEmpty()) {
return true;
}
return providedKey != null && attackApiKey.equals(providedKey.trim());
}
public boolean sendAttackNotification(String eventType,
Integer connectionsPerSecond,
Integer blockedIps,
Long blockedConnections,
String source) {
if (!isAttackNotificationsEnabled()) {
return false;
}
String usedSource = (source == null || source.trim().isEmpty()) ? attackDefaultSource : source.trim();
String type = eventType == null ? "detected" : eventType.trim().toLowerCase(Locale.ROOT);
String title;
String shortText;
int color;
if ("stopped".equals(type) || "mitigated".equals(type)) {
title = "✅ Attack Stopped";
shortText = "Traffic hat sich normalisiert.";
color = 0x2ECC71;
} else {
title = "🚨 Attack Detected";
shortText = "Ungewöhnlich hoher Verbindungs-Traffic erkannt.";
color = 0xE74C3C;
}
StringBuilder fields = new StringBuilder();
appendEmbedField(fields, "Source", usedSource, true);
appendEmbedField(fields, "Event", type.toUpperCase(Locale.ROOT), true);
if (connectionsPerSecond != null && connectionsPerSecond >= 0) {
appendEmbedField(fields, "Connections / Second", String.valueOf(connectionsPerSecond), true);
}
if (blockedIps != null && blockedIps >= 0) {
appendEmbedField(fields, "Blocked IPs", String.valueOf(blockedIps), true);
}
if (blockedConnections != null && blockedConnections >= 0L) {
appendEmbedField(fields, "Blocked Connections", String.valueOf(blockedConnections), true);
}
sendWebhookAttackEmbed(webhookUrl, title, shortText, color, fields.toString());
return true;
}
public Map<String, Object> buildSnapshot() {
Map<String, Object> out = new LinkedHashMap<String, Object>();
long now = System.currentTimeMillis();
long uptimeMs = Math.max(0L, now - startedAtMillis);
Runtime rt = Runtime.getRuntime();
long maxMemory = rt.maxMemory();
long totalMemory = rt.totalMemory();
long freeMemory = rt.freeMemory();
long usedMemory = totalMemory - freeMemory;
Map<String, Object> memory = new LinkedHashMap<String, Object>();
memory.put("used_mb", bytesToMb(usedMemory));
memory.put("free_mb", bytesToMb(freeMemory));
memory.put("total_mb", bytesToMb(totalMemory));
memory.put("max_mb", bytesToMb(maxMemory));
memory.put("usage_percent", percent(usedMemory, Math.max(1L, maxMemory)));
int onlinePlayers = ProxyServer.getInstance().getPlayers().size();
int maxPlayers = ProxyServer.getInstance().getConfig().getPlayerLimit();
// getPlayerLimit() liefert -1 wenn kein globales Limit gesetzt ist.
// In diesem Fall den Listener-Wert (angezeigte Max-Spielerzahl im Server-Ping) nutzen.
if (maxPlayers <= 0) {
try {
java.util.Iterator<net.md_5.bungee.api.config.ListenerInfo> listenerIt =
ProxyServer.getInstance().getConfig().getListeners().iterator();
if (listenerIt.hasNext()) {
int listenerMax = listenerIt.next().getMaxPlayers();
if (listenerMax > 0) {
maxPlayers = listenerMax;
}
}
} catch (Exception ignored) {}
}
Map<String, Object> ping = buildPingSummary(ProxyServer.getInstance().getPlayers());
Map<String, Object> players = new LinkedHashMap<String, Object>();
players.put("online", onlinePlayers);
players.put("max", maxPlayers);
players.put("occupancy_percent", percent(onlinePlayers, Math.max(1, maxPlayers)));
players.put("bedrock_online", countBedrockPlayers());
players.put("ping", ping);
List<Map<String, Object>> backend = buildBackendDistribution();
Map<String, Object> system = new LinkedHashMap<String, Object>();
system.put("java_version", System.getProperty("java.version"));
system.put("java_vendor", System.getProperty("java.vendor"));
system.put("os_name", System.getProperty("os.name"));
system.put("os_arch", System.getProperty("os.arch"));
system.put("available_processors", Runtime.getRuntime().availableProcessors());
system.put("system_load_percent", getSystemLoadPercent());
system.put("proxy_tps", roundDouble(currentProxyTps, 2));
out.put("enabled", true);
out.put("timestamp_unix", now / 1000L);
out.put("uptime_seconds", uptimeMs / 1000L);
out.put("uptime_human", formatDuration(uptimeMs));
out.put("players", players);
out.put("backend_servers", backend);
out.put("memory", memory);
out.put("system", system);
out.put("features", buildFeatureSummary());
if (includePlayerNames) {
List<String> names = new ArrayList<String>();
for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) {
names.add(p.getName());
}
out.put("player_names", names);
}
return out;
}
private Map<String, Object> buildPingSummary(Collection<ProxiedPlayer> players) {
Map<String, Object> ping = new LinkedHashMap<String, Object>();
if (players.isEmpty()) {
ping.put("avg_ms", 0);
ping.put("min_ms", 0);
ping.put("max_ms", 0);
return ping;
}
long sum = 0L;
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (ProxiedPlayer p : players) {
int ms = Math.max(0, p.getPing());
sum += ms;
if (ms < min) min = ms;
if (ms > max) max = ms;
}
ping.put("avg_ms", Math.round((double) sum / (double) players.size()));
ping.put("min_ms", min == Integer.MAX_VALUE ? 0 : min);
ping.put("max_ms", max == Integer.MIN_VALUE ? 0 : max);
return ping;
}
private List<Map<String, Object>> buildBackendDistribution() {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (Map.Entry<String, ServerInfo> entry : ProxyServer.getInstance().getServers().entrySet()) {
ServerInfo info = entry.getValue();
Map<String, Object> row = new LinkedHashMap<String, Object>();
row.put("name", entry.getKey());
row.put("online_players", info.getPlayers().size());
row.put("address", String.valueOf(info.getAddress()));
list.add(row);
}
return list;
}
private Map<String, Object> buildFeatureSummary() {
Map<String, Object> features = new LinkedHashMap<String, Object>();
features.put("luckperms", ProxyServer.getInstance().getPluginManager().getPlugin("LuckPerms") != null);
features.put("floodgate", isFloodgateAvailable());
return features;
}
private boolean isFloodgateAvailable() {
try {
Class.forName("org.geysermc.floodgate.api.FloodgateApi");
return true;
} catch (Throwable ignored) {
return false;
}
}
private int countBedrockPlayers() {
try {
Class<?> apiClass = Class.forName("org.geysermc.floodgate.api.FloodgateApi");
Object api = apiClass.getMethod("getInstance").invoke(null);
int count = 0;
for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) {
Boolean isBedrock = (Boolean) api.getClass().getMethod("isBedrockPlayer", UUID.class).invoke(api, p.getUniqueId());
if (Boolean.TRUE.equals(isBedrock)) {
count++;
}
}
return count;
} catch (Throwable ignored) {
return 0;
}
}
private Integer getSystemLoadPercent() {
try {
java.lang.management.OperatingSystemMXBean bean = ManagementFactory.getOperatingSystemMXBean();
if (bean instanceof OperatingSystemMXBean) {
double load = ((OperatingSystemMXBean) bean).getSystemCpuLoad();
if (load >= 0D) {
return (int) Math.round(load * 100D);
}
}
} catch (Throwable ignored) {
}
return null;
}
private int bytesToMb(long bytes) {
return (int) (bytes / (1024L * 1024L));
}
private int percent(long value, long max) {
if (max <= 0L) return 0;
return (int) Math.min(100L, Math.round((value * 100.0D) / max));
}
private String formatDuration(long ms) {
long totalSeconds = ms / 1000L;
long days = totalSeconds / 86400L;
long hours = (totalSeconds % 86400L) / 3600L;
long minutes = (totalSeconds % 3600L) / 60L;
long seconds = totalSeconds % 60L;
return String.format(Locale.ROOT, "%dd %02dh %02dm %02ds", days, hours, minutes, seconds);
}
private void loadConfig() {
File file = new File(plugin.getDataFolder(), CONFIG_FILE_NAME);
if (!file.exists()) {
enabled = true;
commandEnabled = true;
includePlayerNames = false;
webhookEnabled = false;
webhookUrl = "";
webhookUsername = "StatusAPI";
webhookThumbnailUrl = "";
webhookNotifyStartStop = true;
webhookEmbedMode = "detailed";
webhookCheckSeconds = 30;
alertMemoryPercent = 90;
alertPlayerPercent = 95;
alertCooldownSeconds = 300;
alertTpsEnabled = true;
alertTpsThreshold = 18.0D;
attackNotificationsEnabled = true;
attackApiKey = "";
attackDefaultSource = "BetterBungee";
return;
}
Properties props = new Properties();
try (FileInputStream in = new FileInputStream(file)) {
props.load(new InputStreamReader(in, StandardCharsets.UTF_8));
enabled = Boolean.parseBoolean(props.getProperty("networkinfo.enabled", "true"));
commandEnabled = Boolean.parseBoolean(props.getProperty("networkinfo.command.enabled", "true"));
includePlayerNames = Boolean.parseBoolean(props.getProperty("networkinfo.include_player_names", "false"));
webhookEnabled = Boolean.parseBoolean(props.getProperty("networkinfo.webhook.enabled", "false"));
webhookUrl = props.getProperty("networkinfo.webhook.url", "").trim();
webhookUsername = props.getProperty("networkinfo.webhook.username", "StatusAPI").trim();
webhookThumbnailUrl = props.getProperty("networkinfo.webhook.thumbnail_url", "").trim();
webhookNotifyStartStop = Boolean.parseBoolean(props.getProperty("networkinfo.webhook.notify_start_stop", "true"));
webhookEmbedMode = props.getProperty("networkinfo.webhook.embed_mode", "detailed").trim();
webhookCheckSeconds = parseInt(props.getProperty("networkinfo.webhook.check_seconds", "30"), 30);
alertMemoryPercent = parseInt(props.getProperty("networkinfo.alert.memory_percent", "90"), 90);
alertPlayerPercent = parseInt(props.getProperty("networkinfo.alert.player_percent", "95"), 95);
alertCooldownSeconds = parseInt(props.getProperty("networkinfo.alert.cooldown_seconds", "300"), 300);
alertTpsEnabled = Boolean.parseBoolean(props.getProperty("networkinfo.alert.tps_enabled", "true"));
alertTpsThreshold = parseDouble(props.getProperty("networkinfo.alert.tps_threshold", "18.0"), 18.0D);
attackNotificationsEnabled = Boolean.parseBoolean(props.getProperty("networkinfo.attack.enabled", "true"));
attackApiKey = props.getProperty("networkinfo.attack.api_key", "").trim();
attackDefaultSource = props.getProperty("networkinfo.attack.source", "BetterBungee").trim();
} catch (Exception e) {
plugin.getLogger().warning("[NetworkInfoModule] Fehler beim Laden von " + CONFIG_FILE_NAME + ": " + e.getMessage());
enabled = true;
commandEnabled = true;
includePlayerNames = false;
webhookEnabled = false;
webhookUrl = "";
webhookUsername = "StatusAPI";
webhookThumbnailUrl = "";
webhookNotifyStartStop = true;
webhookEmbedMode = "detailed";
webhookCheckSeconds = 30;
alertMemoryPercent = 90;
alertPlayerPercent = 95;
alertCooldownSeconds = 300;
alertTpsEnabled = true;
alertTpsThreshold = 18.0D;
attackNotificationsEnabled = true;
attackApiKey = "";
attackDefaultSource = "BetterBungee";
}
}
private void ensureModuleConfigExists() {
File target = new File(plugin.getDataFolder(), CONFIG_FILE_NAME);
if (target.exists()) {
return;
}
if (!plugin.getDataFolder().exists()) {
plugin.getDataFolder().mkdirs();
}
try (InputStream in = plugin.getResourceAsStream(CONFIG_FILE_NAME);
OutputStream out = new FileOutputStream(target)) {
if (in == null) {
plugin.getLogger().warning("[NetworkInfoModule] Standarddatei " + CONFIG_FILE_NAME + " nicht im JAR gefunden.");
return;
}
byte[] buffer = new byte[4096];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
} catch (Exception e) {
plugin.getLogger().warning("[NetworkInfoModule] Konnte " + CONFIG_FILE_NAME + " nicht erstellen: " + e.getMessage());
}
}
private void evaluateAndSendAlerts() {
if (!enabled || !webhookEnabled || webhookUrl == null || webhookUrl.isEmpty()) {
return;
}
long now = System.currentTimeMillis();
Map<String, Object> snapshot = buildSnapshot();
@SuppressWarnings("unchecked")
Map<String, Object> memory = (Map<String, Object>) snapshot.get("memory");
@SuppressWarnings("unchecked")
Map<String, Object> players = (Map<String, Object>) snapshot.get("players");
int memoryPercent = toInt(memory.get("usage_percent"));
int playerPercent = toInt(players.get("occupancy_percent"));
double proxyTps = currentProxyTps;
if (memoryPercent >= Math.max(1, alertMemoryPercent) && canSend(lastMemoryAlertAt, now)) {
lastMemoryAlertAt = now;
if (isCompactEmbedMode()) {
sendWebhookEmbed(
webhookUrl,
"⚠️ Hohe RAM-Auslastung",
"Aktuell: **" + memoryPercent + "%**\nVerbrauch: **" + memory.get("used_mb") + " MB / " + memory.get("max_mb") + " MB**\nSchwelle: **" + alertMemoryPercent + "%**",
0xF39C12
);
} else {
StringBuilder fields = new StringBuilder();
appendEmbedField(fields, "RAM-Nutzung", memoryPercent + "%", true);
appendEmbedField(fields, "Schwelle", alertMemoryPercent + "%", true);
appendEmbedField(fields, "Verbrauch", memory.get("used_mb") + " MB / " + memory.get("max_mb") + " MB", false);
sendWebhookEmbed(
webhookUrl,
"⚠️ Hohe RAM-Auslastung",
"Ein Schwellwert wurde überschritten.",
0xF39C12,
fields.toString()
);
}
}
if (playerPercent >= Math.max(1, alertPlayerPercent) && canSend(lastPlayerAlertAt, now)) {
lastPlayerAlertAt = now;
if (isCompactEmbedMode()) {
sendWebhookEmbed(
webhookUrl,
"📈 Hohe Spieler-Auslastung",
"Auslastung: **" + playerPercent + "%**\nSpieler: **" + players.get("online") + "/" + players.get("max") + "**\nSchwelle: **" + alertPlayerPercent + "%**",
0x3498DB
);
} else {
StringBuilder fields = new StringBuilder();
appendEmbedField(fields, "Auslastung", playerPercent + "%", true);
appendEmbedField(fields, "Schwelle", alertPlayerPercent + "%", true);
appendEmbedField(fields, "Spieler", players.get("online") + "/" + players.get("max"), true);
sendWebhookEmbed(
webhookUrl,
"📈 Hohe Spieler-Auslastung",
"Die Spielerlast ist aktuell sehr hoch.",
0x3498DB,
fields.toString()
);
}
}
if (alertTpsEnabled && proxyTps > 0D && proxyTps < Math.max(1D, alertTpsThreshold) && canSend(lastTpsAlertAt, now)) {
lastTpsAlertAt = now;
String tpsText = String.format(Locale.ROOT, "%.2f", proxyTps);
String thresholdText = String.format(Locale.ROOT, "%.2f", Math.max(1D, alertTpsThreshold));
if (isCompactEmbedMode()) {
sendWebhookEmbed(
webhookUrl,
"🟥 Niedrige Proxy-TPS",
"Aktuell: **" + tpsText + " TPS**\nSchwelle: **" + thresholdText + " TPS**",
0xE74C3C
);
} else {
StringBuilder fields = new StringBuilder();
appendEmbedField(fields, "Proxy TPS", tpsText, true);
appendEmbedField(fields, "Schwelle", thresholdText, true);
appendEmbedField(fields, "Check-Intervall", Math.max(10, webhookCheckSeconds) + "s", true);
sendWebhookEmbed(
webhookUrl,
"🟥 Niedrige Proxy-TPS",
"Die gemessene Proxy-TPS liegt unter der konfigurierten Schwelle.",
0xE74C3C,
fields.toString()
);
}
}
}
private void sampleProxyTps() {
long now = System.currentTimeMillis();
if (lastTpsSampleAtMs <= 0L) {
lastTpsSampleAtMs = now;
currentProxyTps = 20.0D;
return;
}
long deltaMs = now - lastTpsSampleAtMs;
lastTpsSampleAtMs = now;
if (deltaMs <= 0L) {
return;
}
// 1s Scheduler-Tick sollte etwa 20 TPS entsprechen. Abweichung zeigt Main-Thread-Lag.
double instantTps = (1000.0D / (double) deltaMs) * 20.0D;
instantTps = Math.max(0.1D, Math.min(20.0D, instantTps));
currentProxyTps = (currentProxyTps * 0.7D) + (instantTps * 0.3D);
}
private boolean isCompactEmbedMode() {
return "compact".equalsIgnoreCase(webhookEmbedMode == null ? "" : webhookEmbedMode.trim());
}
private boolean canSend(long lastSentAt, long now) {
long cooldownMs = Math.max(10, alertCooldownSeconds) * 1000L;
return (now - lastSentAt) >= cooldownMs;
}
private int parseInt(String s, int fallback) {
try {
return Integer.parseInt(s == null ? "" : s.trim());
} catch (Exception ignored) {
return fallback;
}
}
private double parseDouble(String s, double fallback) {
try {
return Double.parseDouble(s == null ? "" : s.trim());
} catch (Exception ignored) {
return fallback;
}
}
private int toInt(Object o) {
if (o instanceof Number) {
return ((Number) o).intValue();
}
try {
return Integer.parseInt(String.valueOf(o));
} catch (Exception ignored) {
return 0;
}
}
private double roundDouble(double value, int digits) {
double factor = Math.pow(10D, Math.max(0, digits));
return Math.round(value * factor) / factor;
}
private boolean sendWebhookEmbed(String targetWebhookUrl, String title, String description, int color) {
return sendWebhookEmbed(targetWebhookUrl, title, description, color, null, true);
}
private boolean sendWebhookEmbed(String targetWebhookUrl, String title, String description, int color, String fieldsJson) {
return sendWebhookEmbed(targetWebhookUrl, title, description, color, fieldsJson, true);
}
private boolean sendWebhookEmbed(String targetWebhookUrl, String title, String description, int color, String fieldsJson, boolean async) {
if (targetWebhookUrl == null || targetWebhookUrl.isEmpty()) {
return false;
}
StringBuilder embed = new StringBuilder();
embed.append("{\"username\":\"").append(escapeJson(webhookUsername)).append("\",")
.append("\"embeds\":[{\"title\":\"").append(escapeJson(title)).append("\",")
.append("\"description\":\"").append(escapeJson(description)).append("\",")
.append("\"color\":").append(color).append(",");
if (fieldsJson != null && !fieldsJson.trim().isEmpty()) {
embed.append("\"fields\":[").append(fieldsJson).append("],");
}
embed.append("\"footer\":{\"text\":\"StatusPulse • NetworkInfo\"},")
.append("\"timestamp\":\"").append(Instant.now().toString()).append("\"");
if (webhookThumbnailUrl != null && !webhookThumbnailUrl.isEmpty()) {
embed.append(",\"thumbnail\":{\"url\":\"").append(escapeJson(webhookThumbnailUrl)).append("\"}");
}
embed.append("}]}");
return postWebhookPayload(targetWebhookUrl, embed.toString(), async);
}
private void sendWebhookAttackEmbed(String targetWebhookUrl,
String title,
String description,
int color,
String fieldsJson) {
if (targetWebhookUrl == null || targetWebhookUrl.isEmpty()) {
return;
}
StringBuilder embed = new StringBuilder();
embed.append("{\"username\":\"").append(escapeJson(webhookUsername)).append("\",")
.append("\"embeds\":[{\"title\":\"").append(escapeJson(title)).append("\",")
.append("\"description\":\"").append(escapeJson(description)).append("\",")
.append("\"color\":").append(color).append(",")
.append("\"fields\":[").append(fieldsJson).append("],")
.append("\"footer\":{\"text\":\"StatusPulse • Network Guard\"},")
.append("\"timestamp\":\"").append(Instant.now().toString()).append("\"");
if (webhookThumbnailUrl != null && !webhookThumbnailUrl.isEmpty()) {
embed.append(",\"thumbnail\":{\"url\":\"").append(escapeJson(webhookThumbnailUrl)).append("\"}");
}
embed.append("}]}");
postWebhookPayload(targetWebhookUrl, embed.toString(), true);
}
private void appendEmbedField(StringBuilder out, String name, String value, boolean inline) {
if (value == null || value.trim().isEmpty()) {
return;
}
if (out.length() > 0) {
out.append(",");
}
out.append("{\"name\":\"").append(escapeJson(name)).append("\",")
.append("\"value\":\"").append(escapeJson(value.trim())).append("\",")
.append("\"inline\":").append(inline ? "true" : "false")
.append("}");
}
private boolean postWebhookPayload(String targetWebhookUrl, String payload, boolean async) {
if (async) {
ProxyServer.getInstance().getScheduler().runAsync(plugin, () -> executeWebhookPost(targetWebhookUrl, payload));
return true;
}
return executeWebhookPost(targetWebhookUrl, payload);
}
private boolean executeWebhookPost(String targetWebhookUrl, String payload) {
HttpURLConnection conn = null;
try {
byte[] bytes = payload.getBytes(StandardCharsets.UTF_8);
conn = (HttpURLConnection) new URL(targetWebhookUrl).openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5000);
conn.setReadTimeout(8000);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(bytes.length));
try (OutputStream os = conn.getOutputStream()) {
os.write(bytes);
}
int code = conn.getResponseCode();
if (code >= 200 && code < 300) {
return true;
}
plugin.getLogger().warning("[NetworkInfoModule] Discord Webhook HTTP " + code + ": " + readErrorBody(conn));
return false;
} catch (Exception e) {
plugin.getLogger().warning("[NetworkInfoModule] Discord Webhook Fehler: " + e.getMessage());
return false;
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
private String readErrorBody(HttpURLConnection conn) {
if (conn == null) {
return "";
}
try (InputStream errorStream = conn.getErrorStream()) {
if (errorStream == null) {
return "";
}
byte[] bytes = new byte[1024];
int read = errorStream.read(bytes);
if (read <= 0) {
return "";
}
return new String(bytes, 0, read, StandardCharsets.UTF_8).trim();
} catch (Exception ignored) {
return "";
}
}
private String escapeJson(String s) {
if (s == null) return "";
return s.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r");
}
private class NetInfoCommand extends Command {
NetInfoCommand() {
super("netinfo", "statusapi.netinfo");
}
@Override
public void execute(CommandSender sender, String[] args) {
if (!enabled) {
sender.sendMessage(ChatColor.RED + "NetworkInfoModule ist deaktiviert.");
return;
}
Map<String, Object> snapshot = buildSnapshot();
@SuppressWarnings("unchecked")
Map<String, Object> players = (Map<String, Object>) snapshot.get("players");
@SuppressWarnings("unchecked")
Map<String, Object> memory = (Map<String, Object>) snapshot.get("memory");
@SuppressWarnings("unchecked")
Map<String, Object> system = (Map<String, Object>) snapshot.get("system");
@SuppressWarnings("unchecked")
Map<String, Object> ping = (Map<String, Object>) players.get("ping");
sender.sendMessage(ChatColor.GOLD + "----- StatusAPI NetworkInfo -----");
sender.sendMessage(ChatColor.YELLOW + "Uptime: " + ChatColor.WHITE + snapshot.get("uptime_human"));
sender.sendMessage(ChatColor.YELLOW + "Spieler: " + ChatColor.WHITE + players.get("online") + "/" + players.get("max") + ChatColor.GRAY + " (Bedrock: " + players.get("bedrock_online") + ")");
sender.sendMessage(ChatColor.YELLOW + "Ping: " + ChatColor.WHITE + "avg " + ping.get("avg_ms") + "ms, min " + ping.get("min_ms") + "ms, max " + ping.get("max_ms") + "ms");
sender.sendMessage(ChatColor.YELLOW + "RAM: " + ChatColor.WHITE + memory.get("used_mb") + "MB / " + memory.get("max_mb") + "MB" + ChatColor.GRAY + " (" + memory.get("usage_percent") + "%)");
sender.sendMessage(ChatColor.YELLOW + "Proxy TPS: " + ChatColor.WHITE + system.get("proxy_tps") + ChatColor.GRAY + " (Alert < " + String.format(Locale.ROOT, "%.2f", alertTpsThreshold) + ")");
sender.sendMessage(ChatColor.YELLOW + "Backends: " + ChatColor.WHITE + ((List<?>) snapshot.get("backend_servers")).size());
}
}
}

View File

@@ -0,0 +1,273 @@
package net.viper.status.modules.serverswitcher;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.ComponentBuilder;
import net.md_5.bungee.api.chat.HoverEvent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.TabCompleteEvent;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.event.EventHandler;
import net.viper.status.module.Module;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class ServerSwitcherModule implements Module {
private static final String CONFIG_FILE = "serverswitcher.properties";
private Plugin plugin;
private boolean enabled = true;
private String permission = "serverswitcher.use";
private String commandName = "go";
private List<String> aliases = new ArrayList<>(Arrays.asList("wechsel", "switch"));
private List<String> serverWhitelist = new ArrayList<>();
private String colorHeader = "&8&m---&r &6&lServer-Menue &8&m---";
private String colorEntry = "&7>> &e";
private String colorOnline = "&a";
private String colorOffline = "&c";
private String colorSelf = "&7(Aktuell)";
@Override
public String getName() {
return "ServerSwitcherModule";
}
@Override
public void onEnable(Plugin plugin) {
this.plugin = plugin;
ensureConfigExists();
loadConfig();
if (!enabled) {
plugin.getLogger().info("[ServerSwitcherModule] Deaktiviert.");
return;
}
String[] aliasArray = aliases.toArray(new String[0]);
ProxyServer.getInstance().getPluginManager().registerCommand(plugin,
new GoCommand(commandName, permission, aliasArray));
ProxyServer.getInstance().getPluginManager().registerListener(plugin,
new GoTabListener());
plugin.getLogger().info("[ServerSwitcherModule] Aktiviert. Command: /" + commandName
+ " | Aliases: " + aliases + " | Permission: " + permission);
}
@Override
public void onDisable(Plugin plugin) {
}
private void ensureConfigExists() {
File target = new File(plugin.getDataFolder(), CONFIG_FILE);
if (target.exists()) return;
if (!plugin.getDataFolder().exists()) plugin.getDataFolder().mkdirs();
String defaults =
"# ServerSwitcherModule Konfiguration\n" +
"serverswitcher.enabled=true\n\n" +
"serverswitcher.command=go\n" +
"serverswitcher.aliases=wechsel,switch\n" +
"serverswitcher.permission=serverswitcher.use\n\n" +
"# Optionale Whitelist (leer = alle BungeeCord-Server)\n" +
"# Beispiel: serverswitcher.servers=lobby,citybuild,survival\n" +
"serverswitcher.servers=\n\n" +
"serverswitcher.color.header=&8&m---&r &6&lServer-Menü &8&m---\n" +
"serverswitcher.color.entry=&7>> &e\n" +
"serverswitcher.color.online=&a\n" +
"serverswitcher.color.offline=&c\n" +
"serverswitcher.color.self=&7(Aktuell)\n";
try (OutputStream out = new FileOutputStream(target)) {
out.write(defaults.getBytes(StandardCharsets.UTF_8));
} catch (Exception e) {
plugin.getLogger().warning("[ServerSwitcherModule] Konnte " + CONFIG_FILE + " nicht erstellen: " + e.getMessage());
}
}
private void loadConfig() {
File file = new File(plugin.getDataFolder(), CONFIG_FILE);
if (!file.exists()) return;
Properties props = new Properties();
try (FileInputStream fis = new FileInputStream(file)) {
props.load(new InputStreamReader(fis, StandardCharsets.UTF_8));
} catch (Exception e) {
plugin.getLogger().warning("[ServerSwitcherModule] Fehler beim Laden: " + e.getMessage());
return;
}
enabled = Boolean.parseBoolean(props.getProperty("serverswitcher.enabled", "true"));
commandName = props.getProperty("serverswitcher.command", "go").trim();
permission = props.getProperty("serverswitcher.permission", "serverswitcher.use").trim();
aliases.clear();
for (String a : props.getProperty("serverswitcher.aliases", "wechsel,switch").split(",")) {
String t = a.trim();
if (!t.isEmpty()) aliases.add(t);
}
serverWhitelist.clear();
for (String s : props.getProperty("serverswitcher.servers", "").split(",")) {
String t = s.trim().toLowerCase();
if (!t.isEmpty()) serverWhitelist.add(t);
}
colorHeader = props.getProperty("serverswitcher.color.header", colorHeader);
colorEntry = props.getProperty("serverswitcher.color.entry", colorEntry);
colorOnline = props.getProperty("serverswitcher.color.online", colorOnline);
colorOffline = props.getProperty("serverswitcher.color.offline", colorOffline);
colorSelf = props.getProperty("serverswitcher.color.self", colorSelf);
}
private List<String> getServerList() {
if (!serverWhitelist.isEmpty()) return new ArrayList<>(serverWhitelist);
List<String> list = new ArrayList<>(ProxyServer.getInstance().getServers().keySet());
list.sort(String.CASE_INSENSITIVE_ORDER);
return list;
}
private static String c(String text) {
return ChatColor.translateAlternateColorCodes('&', text);
}
private static String capitalize(String s) {
if (s == null || s.isEmpty()) return s;
return Character.toUpperCase(s.charAt(0)) + s.substring(1);
}
// ── Command ───────────────────────────────────────────────────────────────
private class GoCommand extends Command {
GoCommand(String name, String permission, String[] aliases) {
super(name, permission.isEmpty() ? null : permission, aliases);
}
@Override
public void execute(CommandSender sender, String[] args) {
if (!(sender instanceof ProxiedPlayer)) {
sender.sendMessage(c("&cDieser Befehl ist nur für Spieler verfügbar."));
return;
}
ProxiedPlayer player = (ProxiedPlayer) sender;
if (args.length >= 1) {
String target = args[0].trim();
ServerInfo server = null;
for (Map.Entry<String, ServerInfo> entry : ProxyServer.getInstance().getServers().entrySet()) {
if (entry.getKey().equalsIgnoreCase(target)) {
server = entry.getValue();
break;
}
}
if (server == null) {
player.sendMessage(c("&cServer &e" + args[0] + " &cnicht gefunden."));
return;
}
if (player.getServer() != null
&& player.getServer().getInfo().getName().equalsIgnoreCase(server.getName())) {
player.sendMessage(c("&7Du bist bereits auf &e" + server.getName() + "&7."));
return;
}
player.sendMessage(c("&7Verbinde mit &e" + server.getName() + "&7..."));
player.connect(server);
return;
}
sendServerMenu(player);
}
private void sendServerMenu(ProxiedPlayer player) {
player.sendMessage(c(colorHeader));
for (String serverName : getServerList()) {
ServerInfo info = ProxyServer.getInstance().getServerInfo(serverName);
if (info == null) continue;
boolean isCurrent = player.getServer() != null
&& player.getServer().getInfo().getName().equalsIgnoreCase(serverName);
int count = info.getPlayers().size();
TextComponent line = new TextComponent(c(colorEntry));
TextComponent btn = new TextComponent(c((isCurrent ? colorOffline : colorOnline) + capitalize(serverName)));
if (!isCurrent) {
btn.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND,
"/" + commandName + " " + serverName));
btn.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT,
new ComponentBuilder(c("&7Klicken zum Verbinden\n&7Online: &a" + count + " Spieler")).create()));
}
line.addExtra(btn);
line.addExtra(new TextComponent(c(" &8(&7" + count + " online&8)")));
if (isCurrent) line.addExtra(new TextComponent(c(" " + colorSelf)));
player.sendMessage(line);
}
player.sendMessage(c("&8&m----------------------------"));
player.sendMessage(c("&7Tipp: &e/" + commandName + " <Server> &7für direkten Wechsel"));
}
}
// ── Tab-Completion ─────────────────────────────────────────────────────────
public class GoTabListener implements Listener {
@EventHandler
public void onTabComplete(TabCompleteEvent event) {
String cursor = event.getCursor();
if (cursor == null) return;
String lower = cursor.toLowerCase();
boolean matches = lower.startsWith("/" + commandName.toLowerCase() + " ");
if (!matches) {
for (String alias : aliases) {
if (lower.startsWith("/" + alias.toLowerCase() + " ")) {
matches = true;
break;
}
}
}
if (!matches) return;
if (event.getSender() instanceof ProxiedPlayer) {
ProxiedPlayer p = (ProxiedPlayer) event.getSender();
if (!permission.isEmpty() && !p.hasPermission(permission)) return;
}
int spaceIdx = cursor.indexOf(' ');
String input = spaceIdx >= 0 ? cursor.substring(spaceIdx + 1).toLowerCase() : "";
List<String> suggestions = new ArrayList<>();
for (String server : getServerList()) {
if (server.toLowerCase().startsWith(input)) suggestions.add(server);
}
event.getSuggestions().clear();
event.getSuggestions().addAll(suggestions);
}
}
}

View File

@@ -0,0 +1,579 @@
package net.viper.status.modules.tablist;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.config.ListenerInfo;
import net.md_5.bungee.api.config.ServerInfo;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.event.ServerSwitchEvent;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.api.scheduler.ScheduledTask;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.protocol.packet.PlayerListItem;
import net.md_5.bungee.protocol.packet.PlayerListItem.Item;
import net.md_5.bungee.protocol.packet.PlayerListItemUpdate;
import net.viper.status.module.Module;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* TablistModule fuer StatusAPI (BungeeCord 1.19.3+).
*
* Liest die tab_size aus der BungeeCord-Konfiguration und berechnet
* ROWS/COLUMNS dynamisch:
* tab_size=60 -> 3 Spalten x 20 Zeilen
* tab_size=80 -> 4 Spalten x 20 Zeilen
*
* Layout:
* Spalte 0 = Info (Website / Name / Rank / Server / World / Time / TS)
* Spalte 1 = Spieler auf Server 1 (Lobby)
* Spalte 2 = Spieler auf Server 2
* Spalte 3 = Spieler auf Server 3 (nur bei tab_size=80)
*/
public class TablistModule implements Module, Listener {
private static final String CONFIG_FILE = "tablist.properties";
// Wird beim Start dynamisch aus BungeeCord tab_size ermittelt
private int rows = 20;
private int columns = 4;
private int total = rows * columns;
// Fake-UUIDs werden nach Bestimmung von total initialisiert
private UUID[] fakeUuids;
// ── Config ─────────────────────────────────────────────────────────────────
private boolean enabled = true;
private int updateInterval = 5;
private String headerLine1 = "&8&m" + rep('\u2501', 53);
private String headerLine2 = " &6&lViper Network";
private String headerLine3 = "&8&m" + rep('\u2501', 53);
private String footerLine1 = "&8&m" + rep('\u2501', 53);
private String footerLine2 = " &7Discord: &ediscord.viper-network.de &8| &7Shop: &eviper-network.de/shop";
private String footerLine3 = "&8&m" + rep('\u2501', 53);
private String labelWebsite = "&b&lWebsite:";
private String valueWebsite = "&fviper-network.de";
private String labelName = "&b&lName:";
private String labelRank = "&b&lRank:";
private String labelServer = "&b&lServer:";
private String labelWorld = "&b&lWorld:";
private String labelTime = "&b&lTime:";
private String labelTeamspeak = "&b&lTeamspeak:";
private String valueTeamspeak = "&fts.viper-network.de";
private String colorSrvHeader = "&6&l";
private String timeFormat = "HH:mm:ss / h:mm a";
private SimpleDateFormat sdf;
private List<String> serverOrder = new ArrayList<>();
private Set<String> hiddenServers = new HashSet<>();
// ── State ──────────────────────────────────────────────────────────────────
private Plugin plugin;
private ScheduledTask updateTask;
private Method sendPacketQueuedMethod;
private int tabSizeMax = 80; // maximale Slots laut BungeeCord tab_size
// ══════════════════════════════════════════════════════════════════════════
@Override public String getName() { return "TablistModule"; }
@Override
public void onEnable(Plugin plugin) {
this.plugin = plugin;
ensureConfigExists();
loadConfig();
if (!enabled) { plugin.getLogger().info("[TablistModule] Deaktiviert."); return; }
// Tab-Size aus BungeeCord auslesen und ROWS/COLUMNS berechnen
initGridSize();
// Fake-UUIDs initialisieren
fakeUuids = new UUID[total];
for (int i = 0; i < total; i++) {
fakeUuids[i] = new UUID(0xFFFEDEAD00000000L, (long) i);
}
// Reflection-Cache fuer sendPacketQueued
try {
Class<?> ucClass = Class.forName("net.md_5.bungee.UserConnection");
sendPacketQueuedMethod = ucClass.getMethod("sendPacketQueued",
net.md_5.bungee.protocol.DefinedPacket.class);
sendPacketQueuedMethod.setAccessible(true);
} catch (Exception e) {
plugin.getLogger().severe("[TablistModule] sendPacketQueued nicht gefunden: " + e.getMessage());
return;
}
ProxyServer.getInstance().getPluginManager().registerListener(plugin, this);
updateTask = ProxyServer.getInstance().getScheduler().schedule(
plugin, this::updateAll, 2L, Math.max(1, updateInterval), TimeUnit.SECONDS);
// Server-Erkennung loggen
ProxyServer.getInstance().getScheduler().schedule(plugin, () -> {
List<String> all = new ArrayList<>(ProxyServer.getInstance().getServers().keySet());
plugin.getLogger().info("[TablistModule] Alle BungeeCord-Server: " + all);
plugin.getLogger().info("[TablistModule] Tablist-Spalten (" + columns + "x" + rows + "): " + getServerOrder());
}, 3L, TimeUnit.SECONDS);
plugin.getLogger().info("[TablistModule] Aktiviert. Grid=" + columns + "x" + rows
+ " (total=" + total + "), Interval=" + updateInterval + "s");
}
@Override
public void onDisable(Plugin plugin) {
if (updateTask != null) { updateTask.cancel(); updateTask = null; }
for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) {
try {
removeFakeSlots(p);
p.setTabHeader(new TextComponent(""), new TextComponent(""));
} catch (Exception ignored) {}
}
}
/**
* Liest tab_size aus dem ersten BungeeCord-Listener und berechnet ROWS/COLUMNS.
* Minecraft zeigt immer 20 Zeilen, die Spaltenanzahl ergibt sich aus tab_size/20.
* Fallback: 4 Spalten x 20 Zeilen = 80.
*/
private void initGridSize() {
int tabSize = 80;
try {
for (ListenerInfo li : ProxyServer.getInstance().getConfig().getListeners()) {
// getTabSize() nicht im API-Interface, daher Reflection
try {
java.lang.reflect.Method m = li.getClass().getMethod("getTabSize");
Object val = m.invoke(li);
if (val instanceof Number && ((Number) val).intValue() > 0) {
tabSize = ((Number) val).intValue();
break;
}
} catch (Exception ignored) {}
}
} catch (Exception e) {
plugin.getLogger().warning("[TablistModule] Konnte tab_size nicht lesen, nutze 80.");
}
rows = 20;
tabSizeMax = tabSize;
// Beim Start noch keine Server bekannt → maxColumns als Startwert, recalculateGrid korrigiert später
columns = Math.max(2, tabSize / rows);
total = rows * columns;
// Sofort korrekt berechnen falls Server bereits bekannt
int serverCount = getServerOrder().size();
if (serverCount > 0) {
int needed = 1 + serverCount;
columns = Math.max(2, Math.min(needed, tabSize / rows));
total = rows * columns;
}
plugin.getLogger().info("[TablistModule] BungeeCord tab_size=" + tabSize
+ " -> " + columns + " Spalten x " + rows + " Zeilen = " + total + " Slots");
}
// ══════════════════════════════════════════════════════════════════════════
// Events
// ══════════════════════════════════════════════════════════════════════════
@EventHandler public void onLogin(PostLoginEvent e) {
if (!enabled) return;
ProxyServer.getInstance().getScheduler().schedule(plugin,
() -> updateTablist(e.getPlayer()), 3L, TimeUnit.SECONDS);
}
@EventHandler public void onSwitch(ServerSwitchEvent e) {
if (!enabled) return;
ProxyServer.getInstance().getScheduler().schedule(plugin,
() -> updateTablist(e.getPlayer()), 1L, TimeUnit.SECONDS);
}
@EventHandler public void onDisconnect(PlayerDisconnectEvent e) {
if (!enabled) return;
ProxyServer.getInstance().getScheduler().schedule(plugin, this::updateAll, 1L, TimeUnit.SECONDS);
}
// ══════════════════════════════════════════════════════════════════════════
// Core
// ══════════════════════════════════════════════════════════════════════════
private void updateAll() {
recalculateGrid();
for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) updateTablist(p);
}
/**
* Berechnet Spaltenanzahl dynamisch anhand der aktuell sichtbaren Server.
* Spalte 0 = Info, Spalten 1..n = Server
* Minimum: 2 Spalten (Info + 1 Server)
* Maximum: durch tab_size begrenzt
*/
private void recalculateGrid() {
int serverCount = getServerOrder().size();
int needed = 1 + serverCount; // Info-Spalte + Server-Spalten
int maxColumns = tabSizeMax / rows;
int newColumns = Math.max(2, Math.min(needed, maxColumns));
int newTotal = rows * newColumns;
if (newColumns == columns && newTotal == total) return;
// Grid hat sich geändert alte Fake-Slots bei allen Spielern entfernen
for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) {
try { removeFakeSlots(p); } catch (Exception ignored) {}
}
columns = newColumns;
total = newTotal;
// Fake-UUIDs neu initialisieren
fakeUuids = new UUID[total];
for (int i = 0; i < total; i++) {
fakeUuids[i] = new UUID(0xFFFEDEAD00000000L, (long) i);
}
plugin.getLogger().info("[TablistModule] Grid: "
+ columns + " Spalten x " + rows + " Zeilen = " + total
+ " Slots (" + serverCount + " Server)");
}
private void updateTablist(ProxiedPlayer viewer) {
if (viewer == null || !viewer.isConnected()) return;
try {
String header = c(headerLine1) + "\n" + c(headerLine2) + "\n" + c(headerLine3);
String footer = c(footerLine1) + "\n" + c(footerLine2) + "\n" + c(footerLine3);
viewer.setTabHeader(new TextComponent(header), new TextComponent(footer));
hideRealPlayers(viewer);
sendSlots(viewer, buildItems(viewer));
} catch (Exception ex) {
plugin.getLogger().warning("[TablistModule] Fehler fuer " + viewer.getName() + ": " + ex.getMessage());
}
}
/**
* Setzt alle echten Spieler-Slots auf listed=false damit sie in der Tablist
* unsichtbar werden und unsere Fake-Slots nicht verschieben.
*/
@SuppressWarnings("unchecked")
private void hideRealPlayers(ProxiedPlayer viewer) {
if (sendPacketQueuedMethod == null) return;
try {
java.util.Collection<ProxiedPlayer> online = ProxyServer.getInstance().getPlayers();
if (online.isEmpty()) return;
PlayerListItemUpdate pkt = new PlayerListItemUpdate();
pkt.setActions(EnumSet.of(PlayerListItemUpdate.Action.UPDATE_LISTED));
Item[] items = new Item[online.size()];
int idx = 0;
for (ProxiedPlayer p : online) {
Item item = new Item();
item.setUuid(p.getUniqueId());
item.setListed(false);
items[idx++] = item;
}
pkt.setItems(items);
sendPacketQueuedMethod.invoke(viewer, pkt);
} catch (Exception e) {
plugin.getLogger().warning("[TablistModule] hideRealPlayers: " + e.getMessage());
}
}
// ══════════════════════════════════════════════════════════════════════════
// Item-Matrix aufbauen
// ══════════════════════════════════════════════════════════════════════════
private Item[] buildItems(ProxiedPlayer viewer) {
String[] texts = new String[total];
net.md_5.bungee.protocol.data.Property[][] skins = new net.md_5.bungee.protocol.data.Property[total][];
int[] pings = new int[total];
for (int i = 0; i < total; i++) {
texts[i] = " ";
skins[i] = new net.md_5.bungee.protocol.data.Property[0];
pings[i] = 0; // Fake-Ping fuer leere Slots
}
// ── Spalte 0: Info ────────────────────────────────────────────────────
int base = 0, row = 0;
row = set(texts, base, row, c(labelWebsite));
row = set(texts, base, row, c(valueWebsite));
row = set(texts, base, row, " ");
row = set(texts, base, row, c(labelName));
row = set(texts, base, row, c("&f" + viewer.getName()));
row = set(texts, base, row, " ");
row = set(texts, base, row, c(labelRank));
row = set(texts, base, row, c("&f" + getRank(viewer)));
row = set(texts, base, row, " ");
String srv = viewer.getServer() != null ? capitalize(viewer.getServer().getInfo().getName()) : "\u2014";
row = set(texts, base, row, c(labelServer));
row = set(texts, base, row, c("&f" + srv));
row = set(texts, base, row, " ");
row = set(texts, base, row, c(labelWorld));
String world = net.viper.status.StatusAPI.playerWorlds.getOrDefault(viewer.getUniqueId(), "world");
row = set(texts, base, row, c("&f" + world));
row = set(texts, base, row, " ");
row = set(texts, base, row, c(labelTime));
row = set(texts, base, row, c("&f[" + sdf.format(new Date()) + "]"));
row = set(texts, base, row, " ");
row = set(texts, base, row, c(labelTeamspeak));
row = set(texts, base, row, c(valueTeamspeak));
// ── Spalten 1 bis (columns-1): Server-Spieler ─────────────────────────
List<String> servers = getServerOrder();
for (int col = 1; col < columns && (col - 1) < servers.size(); col++) {
base = col * rows;
row = 0;
String sName = servers.get(col - 1);
row = set(texts, base, row, c(colorSrvHeader + capitalize(sName)));
ServerInfo info = ProxyServer.getInstance().getServerInfo(sName);
if (info != null) {
for (ProxiedPlayer p : info.getPlayers()) {
if (row >= rows) break;
String prefix = getLuckPermsPrefix(p);
String display = prefix.isEmpty()
? c("&7" + p.getName())
: c(prefix + "&r " + p.getName());
set(texts, base, row, display);
skins[base + row] = getPlayerSkin(p);
pings[base + row] = Math.max(0, p.getPing());
row++;
}
}
}
// Items zusammenbauen
Item[] items = new Item[total];
for (int i = 0; i < total; i++) {
Item item = new Item();
item.setUuid(fakeUuids[i]);
item.setUsername(fakeName(i));
item.setProperties(skins[i]);
item.setGamemode(0);
item.setPing(pings[i]);
item.setListed(true);
String text = texts[i];
item.setDisplayName(new TextComponent(text == null || text.isEmpty() ? " " : text));
items[i] = item;
}
return items;
}
private int set(String[] arr, int base, int row, String text) {
if (base + row < total) arr[base + row] = text == null ? " " : text;
return row + 1;
}
private net.md_5.bungee.protocol.data.Property[] getPlayerSkin(ProxiedPlayer player) {
try {
Object pending = player.getPendingConnection();
net.md_5.bungee.connection.LoginResult profile =
(net.md_5.bungee.connection.LoginResult)
pending.getClass().getMethod("getLoginProfile").invoke(pending);
if (profile != null && profile.getProperties() != null) {
return profile.getProperties();
}
} catch (Exception ignored) {}
return new net.md_5.bungee.protocol.data.Property[0];
}
// ══════════════════════════════════════════════════════════════════════════
// Pakete senden
// ══════════════════════════════════════════════════════════════════════════
@SuppressWarnings("unchecked")
private void sendSlots(ProxiedPlayer viewer, Item[] items) {
if (sendPacketQueuedMethod == null) return;
PlayerListItemUpdate pkt = new PlayerListItemUpdate();
EnumSet actions = EnumSet.of(
PlayerListItemUpdate.Action.ADD_PLAYER,
PlayerListItemUpdate.Action.UPDATE_DISPLAY_NAME,
PlayerListItemUpdate.Action.UPDATE_LISTED,
PlayerListItemUpdate.Action.UPDATE_LATENCY
);
pkt.setActions(actions);
pkt.setItems(items);
try { sendPacketQueuedMethod.invoke(viewer, pkt); }
catch (Exception e) { plugin.getLogger().warning("[TablistModule] sendPacketQueued: " + e.getMessage()); }
}
private void removeFakeSlots(ProxiedPlayer viewer) {
if (sendPacketQueuedMethod == null || fakeUuids == null) return;
try {
Class<?> cls = Class.forName("net.md_5.bungee.protocol.packet.PlayerListItemRemove");
Object pkt = cls.getDeclaredConstructor().newInstance();
cls.getMethod("setUuids", UUID[].class).invoke(pkt, (Object) fakeUuids.clone());
sendPacketQueuedMethod.invoke(viewer, pkt);
} catch (Exception e) {
try {
PlayerListItem rem = new PlayerListItem();
rem.setAction(PlayerListItem.Action.REMOVE_PLAYER);
Item[] items = new Item[total];
for (int i = 0; i < total; i++) { Item it = new Item(); it.setUuid(fakeUuids[i]); items[i] = it; }
rem.setItems(items);
sendPacketQueuedMethod.invoke(viewer, rem);
} catch (Exception ignored) {}
}
}
// ══════════════════════════════════════════════════════════════════════════
// Helpers
// ══════════════════════════════════════════════════════════════════════════
private List<String> getServerOrder() {
if (!serverOrder.isEmpty()) return new ArrayList<>(serverOrder);
List<String> list = new ArrayList<>();
final String[] lobbyKey = { null };
for (String key : ProxyServer.getInstance().getServers().keySet()) {
if (key.equalsIgnoreCase("lobby")) { lobbyKey[0] = key; break; }
}
if (lobbyKey[0] != null) list.add(lobbyKey[0]);
ProxyServer.getInstance().getServers().keySet().stream()
.filter(s -> lobbyKey[0] == null || !s.equalsIgnoreCase(lobbyKey[0]))
.filter(s -> !hiddenServers.contains(s.toLowerCase()))
.sorted(String.CASE_INSENSITIVE_ORDER)
.forEach(list::add);
return list;
}
private String getRank(ProxiedPlayer player) {
try {
Class<?> prov = Class.forName("net.luckperms.api.LuckPermsProvider");
Object api = prov.getMethod("get").invoke(null);
Object um = api.getClass().getMethod("getUserManager").invoke(api);
Object usr = um.getClass().getMethod("getUser", UUID.class).invoke(um, player.getUniqueId());
if (usr != null) {
Class<?> qo = Class.forName("net.luckperms.api.query.QueryOptions");
Object opts = qo.getMethod("defaultContextualOptions").invoke(null);
Object cache = usr.getClass().getMethod("getCachedData").invoke(usr);
Object meta = cache.getClass().getMethod("getMetaData", qo).invoke(cache, opts);
Object pfx = meta.getClass().getMethod("getPrefix").invoke(meta);
if (pfx != null && !pfx.toString().isEmpty()) return pfx.toString();
Object pg = usr.getClass().getMethod("getPrimaryGroup").invoke(usr);
if (pg != null && !pg.toString().isEmpty()) return "[" + pg.toString().toUpperCase() + "]";
}
} catch (Exception ignored) {}
return "NONE";
}
private String getLuckPermsPrefix(ProxiedPlayer player) {
try {
Class<?> prov = Class.forName("net.luckperms.api.LuckPermsProvider");
Object api = prov.getMethod("get").invoke(null);
Object um = api.getClass().getMethod("getUserManager").invoke(api);
Object usr = um.getClass().getMethod("getUser", UUID.class).invoke(um, player.getUniqueId());
if (usr != null) {
Class<?> qo = Class.forName("net.luckperms.api.query.QueryOptions");
Object opts = qo.getMethod("defaultContextualOptions").invoke(null);
Object cache = usr.getClass().getMethod("getCachedData").invoke(usr);
Object meta = cache.getClass().getMethod("getMetaData", qo).invoke(cache, opts);
Object pfx = meta.getClass().getMethod("getPrefix").invoke(meta);
if (pfx != null) return ChatColor.translateAlternateColorCodes('&', pfx.toString());
}
} catch (Exception ignored) {}
return "";
}
private static String fakeName(int i) { return String.format("~vt%03d", i); }
private static String c(String s) { return ChatColor.translateAlternateColorCodes('&', s == null ? "" : s); }
private static String capitalize(String s) { return s == null || s.isEmpty() ? s : Character.toUpperCase(s.charAt(0)) + s.substring(1); }
private static String rep(char ch, int n) { StringBuilder sb = new StringBuilder(n); for (int i=0;i<n;i++) sb.append(ch); return sb.toString(); }
private int parseInt(String s, int fb) { try { return Integer.parseInt(s == null ? "" : s.trim()); } catch (Exception e) { return fb; } }
// ══════════════════════════════════════════════════════════════════════════
// Config
// ══════════════════════════════════════════════════════════════════════════
private void ensureConfigExists() {
File f = new File(plugin.getDataFolder(), CONFIG_FILE);
if (f.exists()) return;
if (!plugin.getDataFolder().exists()) plugin.getDataFolder().mkdirs();
String sep = rep('\u2501', 53);
String content =
"# TablistModule Konfiguration\n" +
"tablist.enabled=true\n" +
"tablist.update_interval=5\n\n" +
"# Server-Spalten Reihenfolge (leer = Lobby zuerst, dann alle alphabetisch)\n" +
"# Beispiel: tablist.server_order=lobby,survival,citybuild\n" +
"tablist.server_order=\n\n" +
"# Server die NICHT angezeigt werden (kommagetrennt, leer = alle anzeigen)\n" +
"tablist.hidden_servers=\n\n" +
"tablist.header.line1=&8&m" + sep + "\n" +
"tablist.header.line2= &6&lViper Network\n" +
"tablist.header.line3=&8&m" + sep + "\n\n" +
"tablist.footer.line1=&8&m" + sep + "\n" +
"tablist.footer.line2= &7Discord: &ediscord.viper-network.de &8| &7Shop: &eviper-network.de/shop\n" +
"tablist.footer.line3=&8&m" + sep + "\n\n" +
"tablist.info.label.website=&b&lWebsite:\n" +
"tablist.info.value.website=&fviper-network.de\n" +
"tablist.info.label.name=&b&lName:\n" +
"tablist.info.label.rank=&b&lRank:\n" +
"tablist.info.label.server=&b&lServer:\n" +
"tablist.info.label.world=&b&lWorld:\n" +
"tablist.info.label.time=&b&lTime:\n" +
"tablist.info.label.teamspeak=&b&lTeamspeak:\n" +
"tablist.info.value.teamspeak=&fts.viper-network.de\n\n" +
"tablist.color.server_header=&6&l\n" +
"tablist.time_format=HH:mm:ss / h:mm a\n";
try (OutputStream out = new FileOutputStream(f)) { out.write(content.getBytes(StandardCharsets.UTF_8)); }
catch (Exception e) { plugin.getLogger().warning("[TablistModule] Config-Fehler: " + e.getMessage()); }
}
private void loadConfig() {
File file = new File(plugin.getDataFolder(), CONFIG_FILE);
Properties p = new Properties();
if (file.exists()) {
try (FileInputStream fis = new FileInputStream(file)) {
p.load(new InputStreamReader(fis, StandardCharsets.UTF_8));
} catch (Exception e) { plugin.getLogger().warning("[TablistModule] Ladefehler: " + e.getMessage()); }
}
enabled = Boolean.parseBoolean(p.getProperty("tablist.enabled", "true"));
updateInterval = parseInt(p.getProperty("tablist.update_interval", "5"), 5);
headerLine1 = p.getProperty("tablist.header.line1", headerLine1);
headerLine2 = p.getProperty("tablist.header.line2", headerLine2);
headerLine3 = p.getProperty("tablist.header.line3", headerLine3);
footerLine1 = p.getProperty("tablist.footer.line1", footerLine1);
footerLine2 = p.getProperty("tablist.footer.line2", footerLine2);
footerLine3 = p.getProperty("tablist.footer.line3", footerLine3);
labelWebsite = p.getProperty("tablist.info.label.website", labelWebsite);
valueWebsite = p.getProperty("tablist.info.value.website", valueWebsite);
labelName = p.getProperty("tablist.info.label.name", labelName);
labelRank = p.getProperty("tablist.info.label.rank", labelRank);
labelServer = p.getProperty("tablist.info.label.server", labelServer);
labelWorld = p.getProperty("tablist.info.label.world", labelWorld);
labelTime = p.getProperty("tablist.info.label.time", labelTime);
labelTeamspeak = p.getProperty("tablist.info.label.teamspeak", labelTeamspeak);
valueTeamspeak = p.getProperty("tablist.info.value.teamspeak", valueTeamspeak);
colorSrvHeader = p.getProperty("tablist.color.server_header", colorSrvHeader);
timeFormat = p.getProperty("tablist.time_format", timeFormat);
try { sdf = new SimpleDateFormat(timeFormat); }
catch (Exception e) { sdf = new SimpleDateFormat("HH:mm:ss / h:mm a"); }
serverOrder.clear();
String raw = p.getProperty("tablist.server_order", "").trim();
if (!raw.isEmpty()) {
for (String s : raw.split(",")) { String t = s.trim(); if (!t.isEmpty()) serverOrder.add(t.toLowerCase()); }
}
hiddenServers.clear();
String hiddenRaw = p.getProperty("tablist.hidden_servers", "").trim();
if (!hiddenRaw.isEmpty()) {
for (String s : hiddenRaw.split(",")) { String t = s.trim().toLowerCase(); if (!t.isEmpty()) hiddenServers.add(t); }
}
}
}

View File

@@ -0,0 +1,269 @@
package net.viper.status.modules.vanish;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.event.EventHandler;
import net.md_5.bungee.event.EventPriority;
import net.viper.status.module.Module;
import net.viper.status.modules.chat.VanishProvider;
import java.io.*;
import java.util.Collections;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* VanishModule für StatusAPI (BungeeCord)
*
* Features:
* - /vanish zum Ein-/Ausschalten
* - /vanish <Spieler> für Admin-Vanish anderer Spieler
* - /vanishlist zeigt alle aktuell unsichtbaren Spieler
* - Vanish-Status wird persistent in vanish.dat gespeichert
* - Beim Login wird gespeicherter Status wiederhergestellt
* - Volle Integration mit VanishProvider → ChatModule sieht den Status
*
* Permission:
* - vanish.use → darf vanishen
* - vanish.other → darf andere Spieler vanishen
* - vanish.list → darf /vanishlist nutzen
* - chat.admin.bypass → sieht Vanish-Join/Leave-Meldungen im Chat
*/
public class VanishModule implements Module, Listener {
private static final String PERMISSION = "chat.admin.bypass";
private static final String PERMISSION_OTHER = "chat.admin.bypass";
private static final String PERMISSION_LIST = "chat.admin.bypass";
private Plugin plugin;
// Persistente Vanish-UUIDs (werden in vanish.dat gespeichert)
private final Set<UUID> persistentVanished =
Collections.newSetFromMap(new ConcurrentHashMap<>());
private File dataFile;
@Override
public String getName() {
return "VanishModule";
}
@Override
public void onEnable(Plugin plugin) {
this.plugin = plugin;
this.dataFile = new File(plugin.getDataFolder(), "vanish.dat");
load();
plugin.getProxy().getPluginManager().registerListener(plugin, this);
registerCommands();
}
@Override
public void onDisable(Plugin plugin) {
save();
// Alle als sichtbar markieren beim Shutdown (damit beim nächsten Start
// der VanishProvider sauber ist load() setzt sie beim Login neu)
for (UUID uuid : persistentVanished) {
VanishProvider.setVanished(uuid, false);
}
}
// =========================================================
// EVENTS
// =========================================================
/**
* Beim Login: Wenn der Spieler persistent gevanisht war, sofort
* in den VanishProvider eintragen BEVOR das ChatModule die
* Join-Nachricht nach 2 Sekunden sendet.
*/
@EventHandler(priority = EventPriority.LOWEST)
public void onLogin(PostLoginEvent e) {
ProxiedPlayer player = e.getPlayer();
if (persistentVanished.contains(player.getUniqueId())) {
VanishProvider.setVanished(player.getUniqueId(), true);
// Kurze Bestätigung an den Spieler selbst (nach kurzem Delay damit
// der Client bereit ist)
plugin.getProxy().getScheduler().schedule(plugin, () -> {
if (player.isConnected()) {
player.sendMessage(color("&8[&7Vanish&8] &7Du bist &cUnsichtbar&7."));
}
}, 1, java.util.concurrent.TimeUnit.SECONDS);
}
}
@EventHandler
public void onDisconnect(PlayerDisconnectEvent e) {
// VanishProvider cleanup der Eintrag in persistentVanished bleibt
// erhalten damit der Status beim nächsten Login wiederhergestellt wird
VanishProvider.cleanup(e.getPlayer().getUniqueId());
}
// =========================================================
// COMMANDS
// =========================================================
private void registerCommands() {
// /vanish [spieler]
plugin.getProxy().getPluginManager().registerCommand(plugin,
new Command("vanish", PERMISSION, "v") {
@Override
public void execute(CommandSender sender, String[] args) {
if (args.length == 0) {
// Sich selbst vanishen
if (!(sender instanceof ProxiedPlayer)) {
sender.sendMessage(color("&cNur Spieler!"));
return;
}
toggleVanish((ProxiedPlayer) sender, (ProxiedPlayer) sender);
} else {
// Anderen Spieler vanishen
if (!sender.hasPermission(PERMISSION_OTHER)) {
sender.sendMessage(color("&cDu hast keine Berechtigung für /vanish <Spieler>."));
return;
}
ProxiedPlayer target = ProxyServer.getInstance().getPlayer(args[0]);
if (target == null) {
sender.sendMessage(color("&cSpieler &f" + args[0] + " &cnicht gefunden."));
return;
}
toggleVanish(sender, target);
}
}
});
// /vanishlist
plugin.getProxy().getPluginManager().registerCommand(plugin,
new Command("vanishlist", PERMISSION_LIST, "vlist") {
@Override
public void execute(CommandSender sender, String[] args) {
Set<UUID> vanished = VanishProvider.getVanishedPlayers();
if (vanished.isEmpty()) {
sender.sendMessage(color("&8[Vanish] &7Keine unsichtbaren Spieler."));
return;
}
sender.sendMessage(color("&8[Vanish] &7Unsichtbare Spieler &8(" + vanished.size() + ")&7:"));
for (UUID uuid : vanished) {
ProxiedPlayer p = ProxyServer.getInstance().getPlayer(uuid);
String name = p != null ? p.getName() : uuid.toString().substring(0, 8) + "...";
String online = p != null ? " &8(online)" : " &8(offline/persistent)";
sender.sendMessage(color(" &8- &7" + name + online));
}
}
});
}
// =========================================================
// VANISH-LOGIK
// =========================================================
/**
* Schaltet den Vanish-Status eines Spielers um.
*
* @param executor Der Befehlsgeber (für Feedback-Nachrichten)
* @param target Der betroffene Spieler
*/
private void toggleVanish(CommandSender executor, ProxiedPlayer target) {
boolean nowVanished = !VanishProvider.isVanished(target);
setVanished(target, nowVanished);
String statusMsg = nowVanished
? "&8[&7Vanish&8] &f" + target.getName() + " &7ist jetzt &cUnsichtbar&7."
: "&8[&7Vanish&8] &f" + target.getName() + " &7ist jetzt &aSichtbar&7.";
// Feedback an den Ausführenden
executor.sendMessage(color(statusMsg));
// Falls jemand anderes gevanisht wurde, auch dem Ziel Bescheid geben
if (!executor.equals(target)) {
String selfMsg = nowVanished
? "&8[&7Vanish&8] &7Du wurdest &cUnsichtbar &7gemacht."
: "&8[&7Vanish&8] &7Du wurdest &aSichtbar &7gemacht.";
target.sendMessage(color(selfMsg));
}
// Admins mit chat.admin.bypass informieren (außer dem Ausführenden)
for (ProxiedPlayer p : ProxyServer.getInstance().getPlayers()) {
if (p.equals(executor) || p.equals(target)) continue;
if (p.hasPermission("chat.admin.bypass")) {
p.sendMessage(color(statusMsg));
}
}
}
/**
* Setzt den Vanish-Status direkt (ohne Toggle).
* Aktualisiert VanishProvider UND die persistente Liste.
*/
public void setVanished(ProxiedPlayer player, boolean vanished) {
VanishProvider.setVanished(player.getUniqueId(), vanished);
if (vanished) {
persistentVanished.add(player.getUniqueId());
} else {
persistentVanished.remove(player.getUniqueId());
}
save();
}
/**
* Öffentliche API für andere Module.
*/
public boolean isVanished(ProxiedPlayer player) {
return VanishProvider.isVanished(player);
}
// =========================================================
// PERSISTENZ
// =========================================================
private void save() {
try (BufferedWriter bw = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(dataFile), "UTF-8"))) {
for (UUID uuid : persistentVanished) {
bw.write(uuid.toString());
bw.newLine();
}
} catch (IOException e) {
plugin.getLogger().warning("[VanishModule] Fehler beim Speichern: " + e.getMessage());
}
}
private void load() {
persistentVanished.clear();
if (!dataFile.exists()) return;
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream(dataFile), "UTF-8"))) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) continue;
try {
persistentVanished.add(UUID.fromString(line));
} catch (IllegalArgumentException ignored) {}
}
} catch (IOException e) {
plugin.getLogger().warning("[VanishModule] Fehler beim Laden: " + e.getMessage());
}
}
// =========================================================
// HILFSMETHODEN
// =========================================================
private TextComponent color(String text) {
return new TextComponent(ChatColor.translateAlternateColorCodes('&', text));
}
}

View File

@@ -0,0 +1,190 @@
package net.viper.status.modules.verify;
import net.md_5.bungee.api.ChatColor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.Plugin;
import net.viper.status.module.Module;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* VerifyModule: Multi-Server Support.
*
* Fix #7: Servernamen werden jetzt case-insensitiv verglichen.
* Keys in serverConfigs werden beim Laden auf lowercase normalisiert
* und die Suche erfolgt ebenfalls lowercase.
*/
public class VerifyModule implements Module {
private String wpVerifyUrl;
// Keys sind lowercase normalisiert für case-insensitiven Vergleich
private final Map<String, ServerConfig> serverConfigs = new HashMap<>();
@Override
public String getName() { return "VerifyModule"; }
@Override
public void onEnable(Plugin plugin) {
loadConfig(plugin);
ProxyServer.getInstance().getPluginManager().registerCommand(plugin, new VerifyCommand());
plugin.getLogger().info("VerifyModule aktiviert. " + serverConfigs.size() + " Server-Konfigurationen geladen.");
}
@Override
public void onDisable(Plugin plugin) {}
private void loadConfig(Plugin plugin) {
String fileName = "verify.properties";
File configFile = new File(plugin.getDataFolder(), fileName);
Properties props = new Properties();
if (!configFile.exists()) {
plugin.getDataFolder().mkdirs();
try (InputStream in = plugin.getResourceAsStream(fileName);
OutputStream out = new FileOutputStream(configFile)) {
if (in == null) { plugin.getLogger().warning("Standard-config '" + fileName + "' nicht in JAR."); return; }
byte[] buffer = new byte[1024]; int length;
while ((length = in.read(buffer)) > 0) out.write(buffer, 0, length);
plugin.getLogger().info("Konfigurationsdatei '" + fileName + "' erstellt.");
} catch (Exception e) { plugin.getLogger().severe("Fehler beim Erstellen der Config: " + e.getMessage()); return; }
}
try (InputStream in = new FileInputStream(configFile)) {
props.load(in);
} catch (IOException e) { e.printStackTrace(); return; }
this.wpVerifyUrl = props.getProperty("wp_verify_url", "https://deine-wp-domain.tld");
// FIX #7: Keys beim Laden auf lowercase normalisieren
this.serverConfigs.clear();
for (String key : props.stringPropertyNames()) {
if (key.startsWith("server.")) {
String[] parts = key.split("\\.");
if (parts.length == 3) {
// Servername lowercase → case-insensitiver Lookup
String serverName = parts[1].toLowerCase();
String type = parts[2];
ServerConfig config = serverConfigs.computeIfAbsent(serverName, k -> new ServerConfig());
if ("id".equalsIgnoreCase(type)) {
try { config.serverId = Integer.parseInt(props.getProperty(key)); }
catch (NumberFormatException e) { plugin.getLogger().warning("Ungültige Server ID für " + serverName); }
} else if ("secret".equalsIgnoreCase(type)) {
config.sharedSecret = props.getProperty(key);
}
}
}
}
}
private static class ServerConfig {
int serverId = 0;
String sharedSecret = "";
}
private class VerifyCommand extends Command {
public VerifyCommand() { super("verify"); }
@Override
public void execute(CommandSender sender, String[] args) {
if (!(sender instanceof ProxiedPlayer)) { sender.sendMessage(ChatColor.RED + "Nur Spieler können diesen Befehl benutzen."); return; }
ProxiedPlayer p = (ProxiedPlayer) sender;
if (args.length != 1) { p.sendMessage(ChatColor.YELLOW + "Benutzung: /verify <token>"); return; }
// FIX #7: Servername lowercase für case-insensitiven Lookup
String serverName = p.getServer().getInfo().getName().toLowerCase();
ServerConfig config = serverConfigs.get(serverName);
if (config == null || config.serverId == 0 || config.sharedSecret.isEmpty()) {
p.sendMessage(ChatColor.RED + "✗ Dieser Server ist nicht in der Verify-Konfiguration hinterlegt.");
p.sendMessage(ChatColor.GRAY + "Aktueller Servername: " + ChatColor.WHITE + p.getServer().getInfo().getName());
p.sendMessage(ChatColor.GRAY + "Bitte kontaktiere einen Admin.");
return;
}
String token = args[0].trim();
String playerName = p.getName();
HttpURLConnection conn = null;
try {
Charset utf8 = Charset.forName("UTF-8");
String signature = hmacSHA256(playerName + token, config.sharedSecret, utf8);
String payload = "{\"player\":\"" + escapeJson(playerName)
+ "\",\"token\":\"" + escapeJson(token)
+ "\",\"server_id\":" + config.serverId
+ ",\"signature\":\"" + signature + "\"}";
URL url = new URL(wpVerifyUrl + "/wp-json/mc-gallery/v1/verify");
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(7000);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
try (OutputStream os = conn.getOutputStream()) { os.write(payload.getBytes(utf8)); }
int code = conn.getResponseCode();
String resp = code >= 200 && code < 300
? streamToString(conn.getInputStream(), utf8)
: streamToString(conn.getErrorStream(), utf8);
if (resp != null && !resp.isEmpty() && resp.trim().startsWith("{")) {
boolean isSuccess = resp.contains("\"success\":true");
String message = "Ein unbekannter Fehler ist aufgetreten.";
int keyIndex = resp.indexOf("\"message\":\"");
if (keyIndex != -1) {
int startIndex = keyIndex + 11;
int endIndex = resp.indexOf("\"", startIndex);
if (endIndex != -1) message = resp.substring(startIndex, endIndex);
}
if (isSuccess) {
p.sendMessage(ChatColor.GREEN + "" + message);
p.sendMessage(ChatColor.GRAY + "Du kannst nun Bilder hochladen!");
} else {
p.sendMessage(ChatColor.RED + "" + message);
}
} else {
p.sendMessage(ChatColor.RED + "✗ Fehler beim Verbinden mit der Webseite (Code: " + code + ")");
}
} catch (Exception ex) {
p.sendMessage(ChatColor.RED + "✗ Ein interner Fehler ist aufgetreten.");
ProxyServer.getInstance().getLogger().warning("Verify error: " + ex.getMessage());
ex.printStackTrace();
} finally {
if (conn != null) conn.disconnect();
}
}
}
private static String hmacSHA256(String data, String key, Charset charset) throws Exception {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key.getBytes(charset), "HmacSHA256"));
byte[] raw = mac.doFinal(data.getBytes(charset));
StringBuilder sb = new StringBuilder();
for (byte b : raw) sb.append(String.format("%02x", b));
return sb.toString();
}
private static String streamToString(InputStream in, Charset charset) throws IOException {
if (in == null) return "";
try (BufferedReader br = new BufferedReader(new InputStreamReader(in, charset))) {
StringBuilder sb = new StringBuilder(); String line;
while ((line = br.readLine()) != null) sb.append(line);
return sb.toString();
}
}
private static String escapeJson(String s) {
return s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r");
}
}

View File

@@ -0,0 +1,119 @@
package net.viper.status.ratelimit;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Gemeinsames Rate-Limit-Framework fuer mehrere Module.
*/
public final class GlobalRateLimitFramework {
private static final GlobalRateLimitFramework INSTANCE = new GlobalRateLimitFramework();
private final Map<String, Bucket> buckets = new ConcurrentHashMap<String, Bucket>();
private GlobalRateLimitFramework() {
}
public static GlobalRateLimitFramework getInstance() {
return INSTANCE;
}
public Result check(String scope, String actorId, Rule rule) {
return check(scope, actorId, rule, System.currentTimeMillis());
}
public Result check(String scope, String actorId, Rule rule, long now) {
if (rule == null || !rule.enabled || scope == null || scope.isEmpty() || actorId == null || actorId.isEmpty()) {
return Result.allowed(0, 0L);
}
String key = scope + ":" + actorId;
Bucket bucket = buckets.computeIfAbsent(key, k -> new Bucket());
synchronized (bucket) {
if (bucket.blockedUntil > now) {
return Result.blocked(Math.max(0L, bucket.blockedUntil - now), bucket.hits.size());
}
long minTs = now - Math.max(1L, rule.windowMs);
while (!bucket.hits.isEmpty() && bucket.hits.peekFirst() < minTs) {
bucket.hits.pollFirst();
}
bucket.hits.addLast(now);
if (bucket.hits.size() > Math.max(1, rule.maxActions)) {
long blockMs = Math.max(1L, rule.blockMs);
bucket.blockedUntil = now + blockMs;
return Result.blocked(blockMs, bucket.hits.size());
}
return Result.allowed(bucket.hits.size(), 0L);
}
}
public void clearActor(String actorId) {
if (actorId == null || actorId.isEmpty()) {
return;
}
for (String key : buckets.keySet()) {
if (key.endsWith(":" + actorId)) {
buckets.remove(key);
}
}
}
public static final class Rule {
public final boolean enabled;
public final long windowMs;
public final int maxActions;
public final long blockMs;
public Rule(boolean enabled, long windowMs, int maxActions, long blockMs) {
this.enabled = enabled;
this.windowMs = Math.max(1L, windowMs);
this.maxActions = Math.max(1, maxActions);
this.blockMs = Math.max(1L, blockMs);
}
}
public static final class Result {
private final boolean blocked;
private final int currentHits;
private final long remainingBlockMs;
private Result(boolean blocked, int currentHits, long remainingBlockMs) {
this.blocked = blocked;
this.currentHits = Math.max(0, currentHits);
this.remainingBlockMs = Math.max(0L, remainingBlockMs);
}
public static Result blocked(long remainingBlockMs, int currentHits) {
return new Result(true, currentHits, remainingBlockMs);
}
public static Result allowed(int currentHits, long remainingBlockMs) {
return new Result(false, currentHits, remainingBlockMs);
}
public boolean isBlocked() {
return blocked;
}
public int getCurrentHits() {
return currentHits;
}
public long getRemainingBlockMs() {
return remainingBlockMs;
}
}
private static final class Bucket {
final Deque<Long> hits = new ArrayDeque<Long>();
long blockedUntil = 0L;
}
}

View File

@@ -0,0 +1,113 @@
package net.viper.status.stats;
import java.util.UUID;
public class PlayerStats {
public final UUID uuid;
public String name;
public long firstSeen;
public long lastSeen;
public long totalPlaytime;
public long currentSessionStart;
public int joins;
// Economy
public double balance;
public double totalEarned;
public double totalSpent;
public int transactionsCount;
// Punishments
public int bansCount;
public int mutesCount;
public int warnsCount;
public long lastPunishmentAt; // Unix-Timestamp (Sek.), 0 = nie
public String lastPunishmentType; // "ban", "mute", "warn", "kick", "" = nie
public int punishmentScore;
public PlayerStats(UUID uuid, String name) {
this.uuid = uuid;
this.name = name;
long now = System.currentTimeMillis() / 1000L;
this.firstSeen = now;
this.lastSeen = now;
this.totalPlaytime = 0;
this.currentSessionStart = 0;
this.joins = 0;
this.balance = 0.0;
this.totalEarned = 0.0;
this.totalSpent = 0.0;
this.transactionsCount = 0;
this.bansCount = 0;
this.mutesCount = 0;
this.warnsCount = 0;
this.lastPunishmentAt = 0;
this.lastPunishmentType = "";
this.punishmentScore = 0;
}
public synchronized void onJoin() {
long now = System.currentTimeMillis() / 1000L;
if (this.currentSessionStart == 0) this.currentSessionStart = now;
this.lastSeen = now;
this.joins++;
if (this.firstSeen == 0) this.firstSeen = now;
}
public synchronized void onQuit() {
long now = System.currentTimeMillis() / 1000L;
if (this.currentSessionStart > 0) {
long session = now - this.currentSessionStart;
if (session > 0) this.totalPlaytime += session;
this.currentSessionStart = 0;
}
this.lastSeen = now;
}
public synchronized long getPlaytimeWithCurrentSession() {
long now = System.currentTimeMillis() / 1000L;
if (this.currentSessionStart > 0) return totalPlaytime + (now - currentSessionStart);
return totalPlaytime;
}
public synchronized String toLine() {
String safeType = (lastPunishmentType == null ? "" : lastPunishmentType).replace("|", "_");
return uuid + "|" + name.replace("|", "_") + "|" + firstSeen + "|" + lastSeen + "|" + totalPlaytime + "|" + currentSessionStart + "|" + joins
+ "|" + balance + "|" + totalEarned + "|" + totalSpent + "|" + transactionsCount
+ "|" + bansCount + "|" + mutesCount + "|" + warnsCount + "|" + lastPunishmentAt + "|" + safeType + "|" + punishmentScore;
}
public static PlayerStats fromLine(String line) {
String[] parts = line.split("\\|", -1);
if (parts.length < 7) return null;
try {
UUID uuid = UUID.fromString(parts[0]);
String name = parts[1];
PlayerStats ps = new PlayerStats(uuid, name);
ps.firstSeen = Long.parseLong(parts[2]);
ps.lastSeen = Long.parseLong(parts[3]);
ps.totalPlaytime = Long.parseLong(parts[4]);
ps.currentSessionStart = Long.parseLong(parts[5]);
ps.joins = Integer.parseInt(parts[6]);
// Economy (felder 7-10)
if (parts.length >= 11) {
try { ps.balance = Double.parseDouble(parts[7]); } catch (Exception ignored) {}
try { ps.totalEarned = Double.parseDouble(parts[8]); } catch (Exception ignored) {}
try { ps.totalSpent = Double.parseDouble(parts[9]); } catch (Exception ignored) {}
try { ps.transactionsCount = Integer.parseInt(parts[10]); } catch (Exception ignored) {}
}
// Punishments (felder 11-16)
if (parts.length >= 17) {
try { ps.bansCount = Integer.parseInt(parts[11]); } catch (Exception ignored) {}
try { ps.mutesCount = Integer.parseInt(parts[12]); } catch (Exception ignored) {}
try { ps.warnsCount = Integer.parseInt(parts[13]); } catch (Exception ignored) {}
try { ps.lastPunishmentAt = Long.parseLong(parts[14]); } catch (Exception ignored) {}
ps.lastPunishmentType = parts[15];
try { ps.punishmentScore = Integer.parseInt(parts[16]); } catch (Exception ignored) {}
}
return ps;
} catch (Exception e) {
return null;
}
}
}

View File

@@ -0,0 +1,35 @@
package net.viper.status.stats;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
public class StatsManager {
private final ConcurrentHashMap<UUID, PlayerStats> map = new ConcurrentHashMap<>();
public PlayerStats get(UUID uuid, String name) {
return map.compute(uuid, (k, v) -> {
if (v == null) {
return new PlayerStats(uuid, name != null ? name : "");
} else {
if (name != null && !name.isEmpty()) v.name = name;
return v;
}
});
}
public PlayerStats getIfPresent(UUID uuid) {
return map.get(uuid);
}
public Iterable<PlayerStats> all() {
return map.values();
}
public void put(PlayerStats ps) {
map.put(ps.uuid, ps);
}
public void remove(UUID uuid) {
map.remove(uuid);
}
}

View File

@@ -0,0 +1,97 @@
package net.viper.status.stats;
import net.md_5.bungee.api.event.PlayerDisconnectEvent;
import net.md_5.bungee.api.event.PostLoginEvent;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.api.plugin.Listener;
import net.md_5.bungee.event.EventHandler;
import net.viper.status.module.Module;
import java.util.concurrent.TimeUnit;
/**
* StatsModule: Kümmert sich eigenständig um das Tracking der Spielerdaten.
* Implementiert Module (für das Lifecycle) und Listener (für die Events).
*/
public class StatsModule implements Module, Listener {
private StatsManager manager;
private StatsStorage storage;
@Override
public String getName() {
return "StatsModule";
}
@Override
public void onEnable(Plugin plugin) {
// Initialisierung
manager = new StatsManager();
storage = new StatsStorage(plugin.getDataFolder());
// Laden
try {
storage.load(manager);
} catch (Exception e) {
plugin.getLogger().warning("Fehler beim Laden der Stats: " + e.getMessage());
}
// Event Listener registrieren
plugin.getProxy().getPluginManager().registerListener(plugin, this);
// Auto-Save Task (alle 5 Minuten)
plugin.getProxy().getScheduler().schedule(plugin, () -> {
try {
storage.save(manager);
} catch (Exception e) {
plugin.getLogger().warning("Fehler beim Auto-Save: " + e.getMessage());
}
}, 5, 5, TimeUnit.MINUTES);
}
@Override
public void onDisable(Plugin plugin) {
if (manager != null && storage != null) {
// Laufende Sessions beenden vor dem Speichern
long now = System.currentTimeMillis() / 1000L;
for (PlayerStats ps : manager.all()) {
synchronized (ps) {
if (ps.currentSessionStart > 0) {
long delta = now - ps.currentSessionStart;
if (delta > 0) {
ps.totalPlaytime += delta;
}
ps.currentSessionStart = 0; // Session beenden
}
}
}
try {
storage.save(manager);
} catch (Exception e) {
plugin.getLogger().warning("Fehler beim Speichern (Shutdown): " + e.getMessage());
}
}
}
// Öffentlicher Zugriff für den WebServer
public StatsManager getManager() {
return manager;
}
// --- Events ---
@EventHandler
public void onJoin(PostLoginEvent e) {
try {
manager.get(e.getPlayer().getUniqueId(), e.getPlayer().getName()).onJoin();
} catch (Exception ignored) {}
}
@EventHandler
public void onQuit(PlayerDisconnectEvent e) {
try {
PlayerStats ps = manager.getIfPresent(e.getPlayer().getUniqueId());
if (ps != null) ps.onQuit();
} catch (Exception ignored) {}
}
}

View File

@@ -0,0 +1,46 @@
package net.viper.status.stats;
import java.io.*;
/**
* Fix #9: save() und load() sind jetzt synchronized um Race Conditions
* zwischen Auto-Save-Task und Shutdown-Aufruf zu verhindern.
*/
public class StatsStorage {
private final File file;
private final Object fileLock = new Object();
public StatsStorage(File pluginFolder) {
if (!pluginFolder.exists()) pluginFolder.mkdirs();
this.file = new File(pluginFolder, "stats.dat");
}
public void save(StatsManager manager) {
synchronized (fileLock) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (PlayerStats ps : manager.all()) {
bw.write(ps.toLine());
bw.newLine();
}
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void load(StatsManager manager) {
if (!file.exists()) return;
synchronized (fileLock) {
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
PlayerStats ps = PlayerStats.fromLine(line);
if (ps != null) manager.put(ps);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

View File

@@ -0,0 +1,376 @@
# ============================================================
# StatusAPI - ChatModule Konfiguration
# Kompatibel mit Java & Bedrock (Geyser) | BungeeCord Secure Chat
# ============================================================
# Standard-Kanal beim Einloggen
default-channel: "global"
server-colors:
default: "&7" # Fallback für unbekannte Server
lobby:
color: "&a"
display: "Lobby" # Anzeigename (optional, sonst wird der echte Servername verwendet)
survival:
color: "&#E8A020"
display: "Survival"
skyblock:
color: "&b"
display: "SkyBlock"
citybuild:
color: "&#A020E8"
display: "CityBuild"
minigames:
color: "&e"
display: "MiniGames"
chatlog:
enabled: true
retention-days: 7 # 7 oder 14
reports:
enabled: true
webhook-enabled: true
confirm-message: "&aDein Report &8({id}) &awurde eingereicht. Danke!"
close-permission: "chat.admin.bypass"
view-permission: "chat.admin.bypass"
# Leer = jeder Spieler darf reporten, sonst Permission eintragen (z.B. "chat.report")
report-permission: ""
cooldown: 60
# Discord Webhook für Report-Benachrichtigungen (leer = deaktiviert)
discord-webhook: ""
# Telegram Chat-ID für Report-Benachrichtigungen (leer = deaktiviert)
telegram-chat-id: ""
# ============================================================
# KANÄLE
# Jeder Kanal hat eigene Permissions, Format und Brücken.
# format-Platzhalter:
# {server} - Servername
# {prefix} - LuckPerms Prefix
# {player} - Spielername
# {suffix} - LuckPerms Suffix
# {message} - Nachricht
# {channel} - Kanalname
# ============================================================
channels:
global:
name: "Global"
symbol: "G"
permission: ""
color: "&a"
format: "&8[&a{server}&8] {prefix}&r{player}&8: &f{message}"
discord-webhook: ""
discord-channel-id: ""
telegram-chat-id: ""
# Themen-ID für Telegram-Gruppen mit Themen (0 = kein Thema / normale Gruppe)
telegram-thread-id: 0
local:
name: "Local"
symbol: "L"
permission: "chat.channel.local"
color: "&e"
local-only: true
format: "&8[&e{server}&8] {prefix}&r{player}&8: &f{message}"
discord-webhook: ""
discord-channel-id: ""
telegram-chat-id: ""
telegram-thread-id: 0
trade:
name: "Trade"
symbol: "T"
permission: "chat.channel.trade"
color: "&6"
format: "&8[&6TRADE&8] &8[&7{server}&8] {prefix}&r{player}&8: &f{message}"
discord-webhook: ""
discord-channel-id: ""
telegram-chat-id: ""
telegram-thread-id: 0
staff:
name: "Staff"
symbol: "S"
permission: "chat.channel.staff"
color: "&c"
format: "&8[&cSTAFF&8] &8[&7{server}&8] {prefix}&r{player}&8: &f{message}"
discord-webhook: ""
discord-channel-id: ""
telegram-chat-id: ""
telegram-thread-id: 0
use-admin-bridge: true
# ============================================================
# HELPOP
# ============================================================
helpop:
# Format der HelpOp-Nachricht
format: "&8[&eHELPOP&8] &f{player}&8@&7{server}&8: &e{message}"
# Wer bekommt HelpOp zu sehen
receive-permission: "chat.helpop.receive"
# Cooldown in Sekunden
cooldown: 30
# Bestätigungsnachricht an den Spieler
confirm-message: "&aHilferuf wurde an das Team gesendet!"
# Discord / Telegram auch für HelpOp
discord-webhook: ""
telegram-chat-id: ""
# ============================================================
# BROADCAST
# ============================================================
broadcast:
format: "&c&l[&6&lBroadcast&c&l] &r&e{message}"
permission: "chat.broadcast"
# ============================================================
# PRIVATE NACHRICHTEN
# ============================================================
private-messages:
enabled: true
format-sender: "&8[&7Du &8→ &b{player}&8] &f{message}"
format-receiver: "&8[&b{player} &8→ &7Dir&8] &f{message}"
# Social Spy: Admins können alle PMs sehen
format-social-spy: "&8[&dSPY &7{sender} &8→ &7{receiver}&8] &f{message}"
social-spy-permission: "chat.socialspy"
# ============================================================
# JOIN / LEAVE NACHRICHTEN
# Platzhalter:
# {player} - Spielername
# {prefix} - LuckPerms Prefix
# {suffix} - LuckPerms Suffix
# {server} - Zuletzt bekannter Server (bei Leave) oder "Netzwerk"
# ============================================================
join-leave:
enabled: true
# Normale Join/Leave-Nachrichten (für alle sichtbar)
join-format: "&8[&a+&8] {prefix}&a{player}&r &7hat das Netzwerk betreten."
leave-format: "&8[&c-&8] {prefix}&c{player}&r &7hat das Netzwerk verlassen."
# Vanish: Unsichtbare Spieler erzeugen keine normalen Join/Leave-Meldungen.
# Ist vanish-show-to-admins true, sehen Admins mit bypass-permission eine
# abweichende, dezente Benachrichtigung.
vanish-show-to-admins: true
vanish-join-format: "&8[&7+&8] &8{player} &7hat das Netzwerk betreten. &8(Vanish)"
vanish-leave-format: "&8[&7-&8] &8{player} &7hat das Netzwerk verlassen. &8(Vanish)"
# Brücken-Weitergabe (leer = deaktiviert)
discord-webhook: ""
telegram-chat-id: ""
telegram-thread-id: 0
# ============================================================
# GLOBALES RATE-LIMIT-FRAMEWORK
# Zentraler Schutz für Chat/PM/Command-Flood.
# ============================================================
rate-limit:
chat:
enabled: true
window-ms: 2500
max-actions: 3
block-ms: 6000
message: "&cBitte nicht so schnell schreiben!"
private-messages:
enabled: true
window-ms: 5000
max-actions: 4
block-ms: 10000
message: "&cDu sendest zu viele private Nachrichten. Bitte warte kurz."
# ============================================================
# MUTE
# ============================================================
mute:
# Standard-Mute-Dauer in Minuten (0 = permanent)
default-duration-minutes: 60
# Nachricht an gemuteten Spieler
muted-message: "&cDu bist aktuell stummgeschaltet. Noch: &f{time}"
# ============================================================
# EMOJI
# Spieler schreiben :smile: -> wird zu \uD83D\uDE0A konvertiert
# Bedrock-Spieler erhalten Fallback-Text wenn kein Unicode
# ============================================================
emoji:
enabled: true
# Ob Bedrock-Spieler (via Geyser) auch Emojis erhalten
bedrock-support: true
mappings:
":smile:": "\uD83D\uDE0A"
":laugh:": "\uD83D\uDE04"
":sad:": "\uD83D\uDE22"
":cry:": "\uD83D\uDE2D"
":angry:": "\uD83D\uDE20"
":heart:": "\u2764\uFE0F"
":fire:": "\uD83D\uDD25"
":star:": "\u2B50"
":check:": "\u2705"
":x:": "\u274C"
":warning:": "\u26A0\uFE0F"
":thumbsup:": "\uD83D\uDC4D"
":thumbsdown:": "\uD83D\uDC4E"
":wave:": "\uD83D\uDC4B"
":clap:": "\uD83D\uDC4F"
":sword:": "\u2694\uFE0F"
":shield:": "\uD83D\uDEE1\uFE0F"
":diamond:": "\uD83D\uDC8E"
":crown:": "\uD83D\uDC51"
":skull:": "\uD83D\uDC80"
":sun:": "\u2600\uFE0F"
":moon:": "\uD83C\uDF19"
":tree:": "\uD83C\uDF33"
":house:": "\uD83C\uDFE0"
":money:": "\uD83D\uDCB0"
":rocket:": "\uD83D\uDE80"
":rainbow:": "\uD83C\uDF08"
":ghost:": "\uD83D\uDC7B"
":gift:": "\uD83C\uDF81"
":cake:": "\uD83C\uDF82"
":chicken:": "\uD83D\uDC14"
":pig:": "\uD83D\uDC37"
":creeper:": "\uD83D\uDCA3"
":gg:": "\uD83C\uDFAE"
# ============================================================
# DISCORD INTEGRATION
# ============================================================
discord:
enabled: false
# Bot-Token für bidirektionale Kommunikation
bot-token: "YOUR_BOT_TOKEN_HERE"
# Server (Guild) ID
guild-id: "YOUR_GUILD_ID"
# Polling-Intervall in Sekunden (Discord → Minecraft)
poll-interval: 3
# Format für Discord → Minecraft Nachrichten
from-discord-format: "&9[&bDiscord&9] &b{user}&8: &f{message}"
# Extra Admin-Kanal (für Staff-Kanal und HelpOp)
admin-channel-id: ""
# Standard-Embed-Farbe (Hex ohne #)
embed-color: "5865F2"
# ============================================================
# TELEGRAM INTEGRATION
# ============================================================
telegram:
enabled: false
# Bot-Token von @BotFather
bot-token: "YOUR_TELEGRAM_BOT_TOKEN"
# Polling-Intervall in Sekunden
poll-interval: 3
# Format für Telegram → Minecraft Nachrichten
from-telegram-format: "&3[&bTelegram&3] &b{user}&8: &f{message}"
# Extra Admin-Chat-ID (für Staff-Kanal und HelpOp)
admin-chat-id: ""
# Themen-Gruppe: Topic-ID für den Chat-Kanal (0 = kein Topic / normale Gruppe)
# Die message_thread_id findest du indem du eine Nachricht im Topic weiterleitest
# und dir die forwarded_from_message_id anschaust, oder via Bot-API getUpdates.
chat-topic-id: 0
# Topic-ID für den Admin-Kanal (0 = kein Topic)
admin-topic-id: 0
# ============================================================
# ACCOUNT-VERKNÜPFUNG (Discord & Telegram)
# Spieler können ihre Minecraft-Accounts mit Discord/Telegram
# verknüpfen damit ihr Name im Chat angezeigt wird.
# ============================================================
account-linking:
enabled: true
# Token läuft nach X Minuten ab
token-expire-minutes: 10
# Nachricht die der Spieler nach /linkdiscord bekommt
discord-link-message: "&aSchreibe den folgenden Code als Nachricht an unseren Discord-Bot:\n&f&l{token}\n&7Der Code läuft in &f10 Minuten &7ab."
# Nachricht die der Spieler nach /linktelegram bekommt
telegram-link-message: "&aSchreibe den folgenden Code als Nachricht an unseren Telegram-Bot:\n&f&l{token}\n&7Der Code läuft in &f10 Minuten &7ab."
# Bestätigung nach erfolgreicher Verknüpfung (im Spiel)
success-discord: "&aDiscord-Account erfolgreich verknüpft! &8(&7{discord}&8)"
success-telegram: "&aTelegram-Account erfolgreich verknüpft! &8(&7{telegram}&8)"
# Bestätigung die der Bot in Discord/Telegram schickt
bot-success-discord: "✅ Dein Minecraft-Account **{player}** wurde erfolgreich verknüpft!"
bot-success-telegram: "✅ Dein Minecraft-Account <b>{player}</b> wurde erfolgreich verknüpft!"
# Format wenn verknüpfter Nutzer in Discord/Telegram schreibt
# {player} = Minecraft-Name, {user} = Discord/Telegram-Name, {message} = Nachricht
linked-discord-format: "&9[&bDiscord&9] &f{player} &8(&7{user}&8)&8: &f{message}"
linked-telegram-format: "&3[&bTelegram&3] &f{player} &8(&7{user}&8)&8: &f{message}"
# Themen-ID für den Admin-Chat (0 = kein Thema)
admin-thread-id: 0
# ============================================================
# ADMIN BYPASS
# Spieler mit dieser Permission können nicht geblockt werden
# und sind von Mutes ausgenommen
# ============================================================
admin:
bypass-permission: "chat.admin.bypass"
# Admins erhalten Benachrichtigung bei Mutes/Blocks
notify-permission: "chat.admin.notify"
# ============================================================
# CHAT-FILTER & ANTI-SPAM
# ============================================================
chat-filter:
anti-spam:
enabled: true
cooldown-ms: 1500
max-messages: 3
message: "&cBitte nicht so schnell schreiben!"
duplicate-check:
enabled: true
message: "&cBitte keine identischen Nachrichten senden."
blacklist:
enabled: true
words:
- "beispielwort1"
- "beispielwort2"
caps-filter:
enabled: true
min-length: 6
max-percent: 70
anti-ad:
enabled: true
message: "&cWerbung ist in diesem Chat nicht erlaubt!"
# Domains/Substrings die NICHT geblockt werden (z.B. eigene Serveradresse)
# Vergleich ist case-insensitiv und prüft ob der Substring im Match enthalten ist
whitelist:
- "viper-network.de"
- "m-viper.de"
- "https://www.spigotmc.org"
# TLDs die als Werbung gewertet werden.
# Leer = alle Domain-Treffer blockieren (nicht empfohlen, hohe False-Positive-Rate)
blocked-tlds:
- "net"
- "com"
- "de"
- "org"
- "gg"
- "io"
- "eu"
- "tv"
- "xyz"
- "info"
- "me"
- "cc"
- "co"
- "app"
- "online"
- "site"
- "fun"
# ============================================================
# MENTIONS (@Spielername)
# ============================================================
mentions:
enabled: true
highlight-color: "&e&l"
sound: "ENTITY_EXPERIENCE_ORB_PICKUP"
allow-toggle: true
notify-prefix: "&e&l[Mention] &r"
# ============================================================
# CHAT-HISTORY
# ============================================================
chat-history:
max-lines: 50
default-lines: 10

View File

@@ -0,0 +1,16 @@
# ============================================================
# StatusAPI - ChatModule Wort-Blacklist
# Wörter werden case-insensitiv und als Teilwort geprüft.
# Erkannte Wörter werden durch **** ersetzt.
#
# Diese Datei wird bei /chatreload automatisch neu eingelesen.
# Wörter die hier stehen ÜBERSCHREIBEN NICHT die Einträge in
# chat.yml → beide Listen werden zusammengeführt.
# ============================================================
words:
- beispielwort1
- beispielwort2
# Hier eigene Wörter eintragen, eines pro Zeile:
# - schimpfwort
# - spam

View File

@@ -0,0 +1,18 @@
§8[§2Viper-Netzwerk§8] §7Der Server läuft 24/7 also keine Hektik beim Spielen :)
§8[§2Viper-Netzwerk§8] §7Dies ist ein privater Server hier zählt der Zusammenhalt.
§8[§dTipp§8] §7Wenn du denkst, du bist sicher… schau nochmal nach. Creeper machen keine Geräusche beim Tippen.
§8[§2Viper-Netzwerk§8] §7Wähle einen Server, leg los der Rest ergibt sich. Oder explodiert.
§8[§2Viper-Netzwerk§8] §7Mehr Server. Mehr Blöcke. Mehr Unfälle. Willkommen!
§8[§dTipp§8] §7Halte eine Spitzhacke mit Glück bereit. Man weiß nie, wann das nächste Erz kommt.
§8[§dTipp§8] §7Mit §e/home§7 kannst du dich jederzeit nach Hause teleportieren.
§8[§2Viper-Netzwerk§8] §7Das wichtigste Plugin? Du selbst. Spiel fair, sei kreativ!
§8[§2Viper-Netzwerk§8] §7Redstone ist keine Magie aber fast.
§8[§dTipp§8] §7Schilde sind cool. Besonders wenn Skelette zielen.
§8[§2Viper-Netzwerk§8] §7Wenn du in Lava fällst, bist du nicht der Erste. Nur der Nächste.
§8[§dTipp§8] §7Villager sind nicht dumm nur sehr… eigen.
§8[§2Viper-Netzwerk§8] §7Bau groß, bau sicher oder bau eine Treppe zur Nachbarschaftsklage.
§8[§2Viper-Netzwerk§8] §7Gras wächst. Spieler auch. Gib jedem eine Chance!
§8[§2Viper-Netzwerk§8] §7Ein Creeper ist keine Begrüßung. Es sei denn, du willst es spannend machen.
§8[§dTipp§8] §7Ein voller Magen ist halbe Miete. Farmen lohnt sich!
§8[§2Viper-Netzwerk§8] §7Wir haben keine Probleme nur Redstone-Schaltungen mit Charakter.
§8[§dTipp§8] §7Markiere dein Grundstück mit §e/p claim§7, bevor es jemand anderes tut!

View File

@@ -0,0 +1,102 @@
# ===========================
# NETWORK INFO MODUL
# ===========================
networkinfo.enabled=true
networkinfo.command.enabled=true
# Aus Datenschutzgruenden standardmaessig aus. Wenn true, erscheinen alle Spielernamen im JSON.
networkinfo.include_player_names=false
# Discord Webhook fuer Status-, Warn- und Attack-Meldungen
networkinfo.webhook.enabled=true
networkinfo.webhook.url=https://discord.com/api/webhooks/1488630083164831844/o7L5Mhy5P_xE_n-2Dq9usIVX40o7fCpPHgaGQOVIQHjfK7SDrVJbdeZM-G6vVRVhvzT9
networkinfo.webhook.username=StatusAPI
networkinfo.webhook.thumbnail_url=
networkinfo.webhook.notify_start_stop=true
# compact = kurze Texte | detailed = strukturierte Embeds mit Feldern
networkinfo.webhook.embed_mode=detailed
networkinfo.webhook.check_seconds=30
# Alert-Schwellwerte
networkinfo.alert.memory_percent=90
networkinfo.alert.player_percent=95
networkinfo.alert.cooldown_seconds=300
# Proxy-TPS Alert (20.0 = perfekt, Werte < 20 zeigen Main-Thread-Lag am Proxy)
networkinfo.alert.tps_enabled=true
networkinfo.alert.tps_threshold=18.0
# Attack Meldungen (Detected/Stopped)
networkinfo.attack.enabled=true
# Nutzt automatisch networkinfo.webhook.url
networkinfo.attack.source=Viper-Network
# API-Key fuer POST /network/attack
networkinfo.attack.api_key=2jN8xQ4mL9vK3sT7pR1yW6dH5cF0bZ
# ===========================
# ANTIBOT / ATTACK GUARD
# ===========================
antibot.enabled=true
# Profile: strict | high-traffic
# strict: agressiver Schutz, schnelleres Blocken, VPN-Check standardmaessig aktiv
# high-traffic: toleranter fuer grosse Netzwerke mit Lastspitzen
antibot.profile=high-traffic
# Presets (Referenz):
# strict -> max_cps=120, start_cps=220, stop_cps=120, ip/min=18, block_seconds=900, vpn_check.enabled=true
# high-traffic -> max_cps=180, start_cps=300, stop_cps=170, ip/min=24, block_seconds=600, vpn_check.enabled=false
# Hinweis: Werte unten ueberschreiben das Profil bei Bedarf.
# Globaler Traffic
antibot.max_cps=180
antibot.attack.start_cps=300
antibot.attack.stop_cps=170
antibot.attack.stop_grace_seconds=25
# Pro-IP Limiter
antibot.ip.max_connections_per_minute=24
antibot.ip.block_seconds=600
antibot.kick_message=Zu viele Verbindungen von deiner IP. Bitte warte kurz.
# Optionaler VPN/Proxy/Hosting Check (ip-api)
antibot.vpn_check.enabled=false
antibot.vpn_check.block_proxy=true
antibot.vpn_check.block_hosting=true
antibot.vpn_check.cache_minutes=30
antibot.vpn_check.timeout_ms=2500
# Sicherheitslog fuer Angreifer/VPN/Proxy-Events (mit Name/UUID falls verfuegbar)
antibot.security_log.enabled=true
antibot.security_log.file=antibot-security.log
# Lernmodus: Muster mitschreiben, Score bilden und erst ab Schwellwert blockieren.
antibot.learning.enabled=true
antibot.learning.score_threshold=100
antibot.learning.decay_per_second=2
antibot.learning.state_window_seconds=120
# Punktelogik pro Muster
antibot.learning.rapid.window_ms=1500
antibot.learning.rapid.points=12
antibot.learning.ip_rate_exceeded.points=30
antibot.learning.vpn_proxy.points=40
antibot.learning.vpn_hosting.points=30
antibot.learning.attack_mode.points=12
antibot.learning.high_cps.points=10
antibot.learning.recent_events.limit=30
# ===========================
# BACKEND JOIN GUARD SYNC (optional)
# ===========================
# Diese Werte koennen von BackendJoinGuard im StatusAPI-Sync-Modus abgeholt werden.
# Standalone bleibt weiterhin moeglich.
backendguard.enforcement_enabled=true
backendguard.log_blocked_attempts=true
backendguard.kick_message=&cBitte verbinde dich nur über den Proxy-Server.
# Wichtig: Hier nur echte Proxy-IP(s) eintragen.
backendguard.allowed_proxy_ips=127.0.0.1,::1,10.0.0.10
# Optional: internes Proxy-Netz als CIDR
backendguard.allowed_proxy_cidrs=10.0.0.0/24
# Optionaler API-Key fuer GET /network/backendguard/config
# Leer = kein API-Key erforderlich (nur im internen Netzwerk empfohlen)
backendguard.sync.api_key=bgSync_7Rk9pQ2nLm5xV8cH4tW1yZ6

View File

@@ -0,0 +1,287 @@
name: StatusAPI
main: net.viper.status.StatusAPI
version: 4.1.0
author: M_Viper
description: StatusAPI für BungeeCord inkl. Update-Checker, Modul-System und ChatModule
# Mindestanforderung: Minecraft 1.20 / BungeeCord mit PlayerChatEvent-Unterstützung
softdepend:
- LuckPerms
- Geyser-BungeeCord
commands:
# ── Economy ───────────────────────────────────────────────
pay:
description: Überweise Geld an einen Spieler (auch offline)
usage: /pay <Spieler> <Betrag>
ecoadmin:
description: Admin-Verwaltung des Economy-Systems
usage: /ecoadmin <give|take|set|check> <Spieler> [Betrag]
permission: economy.admin
aliases: [ecomod, moneyadmin]
# ── VanishModule ──────────────────────────────────────────
vanish:
description: Vanish ein-/ausschalten
usage: /vanish [Spieler]
aliases: [v]
vanishlist:
description: Alle unsichtbaren Spieler anzeigen
usage: /vanishlist
aliases: [vlist]
# ── Verify Modul ──────────────────────────────────────────
verify:
description: Verifiziere dich mit einem Token
usage: /verify <token>
# ── ForumBridge Modul ─────────────────────────────────────
forumlink:
description: Verknüpfe deinen Minecraft-Account mit dem Forum
usage: /forumlink <token>
aliases: [fl]
forum:
description: Zeigt ausstehende Forum-Benachrichtigungen an
usage: /forum
# ── NetworkInfo Modul ─────────────────────────────────────
netinfo:
description: Zeigt erweiterte Proxy- und Systeminfos an
usage: /netinfo
antibot:
description: Zeigt AntiBot-Status und Verwaltung
usage: /antibot <status|clearblocks|unblock|profile|reload>
# ── AutoMessage Modul ─────────────────────────────────────
automessage:
description: AutoMessage Verwaltung
usage: /automessage reload
# ── ChatModule Kanal ────────────────────────────────────
channel:
description: Kanal wechseln oder Kanalliste anzeigen
usage: /channel [kanalname]
aliases: [ch, kanal]
# ── ChatModule HelpOp ───────────────────────────────────
helpop:
description: Sende eine Hilfeanfrage an das Team
usage: /helpop <Nachricht>
# ── ChatModule Privat-Nachrichten ───────────────────────
msg:
description: Sende eine private Nachricht
usage: /msg <Spieler> <Nachricht>
aliases: [tell, w, whisper]
r:
description: Antworte auf die letzte private Nachricht
usage: /r <Nachricht>
aliases: [reply, antwort]
# ── ChatModule Blockieren ───────────────────────────────
ignore:
description: Spieler ignorieren
usage: /ignore <Spieler>
aliases: [block]
unignore:
description: Spieler nicht mehr ignorieren
usage: /unignore <Spieler>
aliases: [unblock]
# ── ChatModule Mute (Admin) ─────────────────────────────
chatmute:
description: Spieler im Chat stumm schalten
usage: /chatmute <Spieler> [Minuten]
aliases: [gmute]
chatunmute:
description: Chat-Stummschaltung aufheben
usage: /chatunmute <Spieler>
aliases: [gunmute]
# ── ChatModule Selbst-Mute ──────────────────────────────
chataus:
description: Eigenen Chat-Empfang ein-/ausschalten
usage: /chataus
aliases: [togglechat, chaton, chatoff]
# ── ChatModule Broadcast ────────────────────────────────
broadcast:
description: Nachricht an alle Spieler senden
usage: /broadcast <Nachricht>
aliases: [bc, alert]
# ── ChatModule Emoji ────────────────────────────────────
emoji:
description: Liste aller verfügbaren Emojis
usage: /emoji
aliases: [emojis]
# ── ChatModule Social Spy ───────────────────────────────
socialspy:
description: Private Nachrichten mitlesen (Admin)
usage: /socialspy
aliases: [spy]
# ── ChatModule Reload ───────────────────────────────────
chatreload:
description: Chat-Konfiguration neu laden
usage: /chatreload
# ── ChatModule Admin-Info ───────────────────────────────
chatinfo:
description: Chat-Informationen ueber einen Spieler anzeigen (Admin)
usage: /chatinfo <Spieler>
# ── ChatModule Chat-History ─────────────────────────────
chathist:
description: Chat-History aus dem Logfile anzeigen (Admin)
usage: /chathist [Spieler] [Anzahl]
# ── ChatModule Mentions ─────────────────────────────────
mentions:
description: Mention-Benachrichtigungen ein-/ausschalten
usage: /mentions
aliases: [mention]
# ── ChatModule Plugin-Bypass ────────────────────────────
chatbypass:
description: ChatModule fuer naechste Eingabe ueberspringen (fuer Plugin-Dialoge wie CMI)
usage: /chatbypass
aliases: [cbp]
# ── ChatModule Account-Verknuepfung ─────────────────────
# FIX #4: Command-Namen stimmen jetzt mit der Code-Registrierung überein.
# Im ChatModule wird "discordlink" mit Alias "dlink" registriert,
# und "telegramlink" mit Alias "tlink".
discordlink:
description: Minecraft-Account mit Discord verknuepfen
usage: /discordlink
aliases: [dlink]
telegramlink:
description: Minecraft-Account mit Telegram verknuepfen
usage: /telegramlink
aliases: [tlink]
unlink:
description: Account-Verknuepfung aufheben
usage: /unlink <discord|telegram|all>
# ── ChatModule Report ───────────────────────────────────
report:
description: Spieler melden
usage: /report <Spieler> <Grund>
reports:
description: Offene Reports anzeigen (Admin)
usage: /reports [all]
reportclose:
description: Report schliessen (Admin)
usage: /reportclose <ID>
# ── ServerSwitcherModule ──────────────────────────────────
go:
description: Schneller Serverwechsel ueber Chat-Menue oder direkt
usage: /go [servername]
aliases: [wechsel, switch]
permissions:
# ── StatusAPI Core ────────────────────────────────────────
statusapi.update.notify:
description: Erlaubt Update-Benachrichtigungen
default: op
statusapi.netinfo:
description: Zugriff auf /netinfo
default: op
statusapi.antibot:
description: Zugriff auf /antibot
default: op
statusapi.automessage:
description: Zugriff auf /automessage reload
default: op
# ── ChatModule Kanaele ──────────────────────────────────
chat.channel.local:
description: Zugang zum Local-Kanal
default: true
chat.channel.trade:
description: Zugang zum Trade-Kanal
default: true
chat.channel.staff:
description: Zugang zum Staff-Kanal
default: false
# ── ChatModule HelpOp ───────────────────────────────────
chat.helpop.receive:
description: HelpOp-Nachrichten empfangen
default: false
# ── ChatModule Mute ─────────────────────────────────────
chat.mute:
description: Spieler muten / unmuten
default: false
# ── ChatModule Broadcast ────────────────────────────────
chat.broadcast:
description: Broadcast-Nachrichten senden
default: false
# ── ChatModule Social Spy ───────────────────────────────
chat.socialspy:
description: Private Nachrichten mitlesen
default: false
# ── ChatModule Admin ────────────────────────────────────
chat.admin.bypass:
description: Admin-Bypass - Kann nicht geblockt/gemutet werden
default: op
chat.admin.notify:
description: Benachrichtigungen ueber Mutes und Blocks erhalten
default: false
# ── ChatModule Report ───────────────────────────────────
chat.report:
description: Spieler reporten (/report)
default: true
# ── ChatModule Farben ───────────────────────────────────
chat.color:
description: Farbcodes (&a, &b, ...) im Chat nutzen
default: false
chat.color.format:
description: Formatierungen (&l, &o, &n, ...) im Chat nutzen
default: false
# ── ChatModule Filter ───────────────────────────────────
chat.filter.bypass:
description: Chat-Filter (Anti-Spam, Caps, Blacklist) umgehen
default: false
# ── CommandBlocker ────────────────────────────────────────
commandblocker.bypass:
description: Command-Blocker umgehen
default: op
commandblocker.admin:
description: CommandBlocker verwalten (/cb)
default: op
# ── ServerSwitcherModule ──────────────────────────────────
serverswitcher.use:
description: Zugriff auf /go (Schneller Serverwechsel)
default: false

View File

@@ -0,0 +1,92 @@
# _____ __ __ ___ ____ ____
# / ___// /_____ _/ /___ _______/ | / __ \/ _/
# \__ \/ __/ __ `/ __/ / / / ___/ /| | / /_/ // /
# ___/ / /_/ /_/ / /_/ /_/ (__ ) ___ |/ ____// /
# /____/\__/\__,_/\__/\__,_/____/_/ |_/_/ /___/
broadcast.enabled=true
broadcast.prefix=[Broadcast]
broadcast.prefix-color=&c
broadcast.message-color=&f
broadcast.format=%prefixColored% %messageColored%
# broadcast.format kann angepasst werden; nutze Platzhalter: %name%, %prefix%, %prefixColored%, %message%, %messageColored%, %type%
# ===========================
# StatusAPI Einstellungen
# ===========================
statusapi.port=9191
# ===========================
# WORDPRESS / VERIFY EINSTELLUNGEN
# ===========================
wp_verify_url=https://example.com
# Gemeinsames API-Secret (muss identisch sein mit mc_bridge_api_secret in den WP Forum-Einstellungen)
forum.api_secret=HIER_EIN_SICHERES_PASSWORT_SETZEN
# Verzögerung in Sekunden bevor Login-Benachrichtigungen zugestellt werden
# (damit der Spieler den Server-Wechsel abgeschlossen hat)
forum.login_delay_seconds=3
# ===========================
# COMMAND BLOCKER
# ===========================
commandblocker.enabled=true
commandblocker.bypass.permission=commandblocker.bypass
# ===========================
# SERVER KONFIGURATION
# ===========================
# Hier legst du für jeden Server alles fest:
# 1. Den Anzeigenamen für den Chat (z.B. &bLobby)
# 2. Die Server ID für WordPress (z.B. id=1)
# 3. Das Secret für WordPress (z.B. secret=...)
# Server 1: Lobby
server.Lobby=&bLobby
server.Lobby.id=64
server.Lobby.secret=GeheimesWortFuerLobby789
# Server 1: Citybuild
server.citybuild=&bCitybuild
server.citybuild.id=67
server.citybuild.secret=GeheimesWortFuerCitybuild789
# Server 2: Survival
server.survival=&aSurvival
server.survival.id=68
server.survival.secret=GeheimesWortFuerSurvival789
# Server 3: SkyBlock
server.skyblock=&dSkyBlock
server.skyblock.id=3
server.skyblock.secret=GeheimesWortFuerSkyBlock789
# ===========================
# AUTOMESSAGE
# ===========================
# Aktiviert den automatischen Nachrichten-Rundruf
automessage.enabled=true
# Zeitintervall in Sekunden (Standard: 300 = 5 Minuten)
automessage.interval=300
# Optional: Ein Prefix, das VOR jede Nachricht aus der Datei gesetzt wird.
# Wenn du das Prefix bereits IN der messages.txt hast, lass dieses Feld einfach leer.
automessage.prefix=
# Der Name der Datei, in der die Nachrichten stehen (liegt im Plugin-Ordner)
automessage.file=messages.txt
# ===========================
# ECONOMY (Serverübergreifendes Geld)
# ===========================
# Alle Server (SurvivalPlus + StatusAPI/BungeeCord) müssen dieselbe Datenbank nutzen.
# Die Tabelle bc_accounts wird automatisch erstellt.
economy.mysql.host=localhost
economy.mysql.port=3306
economy.mysql.database=survivalplus
economy.mysql.username=root
economy.mysql.password=
economy.start-balance=500.0

View File

@@ -0,0 +1,8 @@
# Willkommensnachrichten, die zufällig gesendet werden, wenn ein Spieler joint.
# %player% wird durch den Spielernamen ersetzt.
welcome-messages:
- "&aWillkommen, %player%! Viel Spaß auf unserem Server!"
- "&aHey %player%, schön dich hier zu sehen! Los geht's!"
- "&a%player%, dein Abenteuer beginnt jetzt! Viel Spaß!"
- "&aWillkommen an Bord, %player%! Entdecke den Server!"
- "&a%player%, herzlich willkommen! Lass uns loslegen!"