commit cbc7ffe4fb505eb673fe7a17faaf1d53f5f6ef8a Author: Elias Müller Date: Sat Oct 17 22:41:44 2026 +0200 Serverübergreifender Chat als Velocity-Plugin diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..90514a7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.gradle/ +build/ +*.iml +.idea/ +run/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..61bdde9 --- /dev/null +++ b/README.md @@ -0,0 +1,43 @@ +# chat-bridge + +Velocity-Plugin für CraftAttack: Der Chat gilt im ganzen Netzwerk (craftattack, arena, Limbo, Event). +Velocity verteilt jede Zeile als Systemnachricht an alle Spieler; die Backends verwerfen den Chat +selbst („Silencer“), sonst stünde er dort doppelt. + +Warum so herum: Velocity kann eine signierte Chat-Nachricht (ab 1.19.1) weder ändern noch abbrechen, +ohne den Spieler zu trennen. Der Proxy lässt sie deshalb zum Backend durch, schaut nur zu und +verteilt sie selbst. + +- **Öffentlicher Chat** mit Server-Kürzel (`[Arena]`, `[Limbo]` …, der Hauptserver ohne), Namen + von Spielern im Netzwerk werden golden als `@Name` hervorgehoben und hören einen Ton. +- **Name:** Rang-Prefixe schickt spawn (`DisplayName` → Kanal `craftattack:chat`, gilt nur solange + der Spieler auf diesem Server ist), blau mit Permission `adminmarker`, 🎮 für Bedrock. +- **/msg** (`tell`, `w`, `whisper`), **/r**, **/adminchat** (Permission `admin`). +- **/mute `` ``**, **/unmute ``** (Permission `admin`): temporäre + LuckPerms-Permission `chatbridge.muted` in der gemeinsamen MariaDB, läuft von selbst ab. Gestummte + dürfen weder öffentlich noch per /msg schreiben, außer an Admins. +- **Join/Leave** nur beim Ein- und Ausloggen ins Netzwerk, nicht beim Serverwechsel. +- **Log:** Chat, /msg, Adminchat und Mutes stehen im Velocity-Log (`[chat]`, `[msg]`, `[adminchat]`, `[mute]`). + +Silencer auf den Backends: + +| Server | Wo | +|---|---| +| craftattack, arena | spawn, Appliance `NetworkChat` (verwirft Chat und `/me`, `/teammsg`, `minecraft:msg`) | +| limbo | EndlessJumper | +| event | Minigames, `velocity.chat-via-proxy: true` in `resources/config.yml` | + +Server ohne Silencer stehen in `unsilenced-servers`: Deren Spieler bekommen den Chat vom eigenen +Server nicht noch einmal, dort greift der Mute aber nur für die anderen Server. + +Einstellungen: `plugins/chat-bridge/config.properties` (wird beim ersten Start angelegt, kommentiert). +Braucht LuckPerms auf Velocity. + +## Bauen und Deploy + +Java 25, Gradle-Wrapper. + +```bash +./gradlew build # inkl. Tests +./gradlew uploadPlugin # nach ~/velocity/plugins/chat-bridge.jar, danach: sudo systemctl restart velocity +``` diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..16555ea --- /dev/null +++ b/build.gradle @@ -0,0 +1,59 @@ +plugins { + id 'java' +} + +group = 'eu.mhsl.craftattack' +version = '1.0.0' + +repositories { + mavenCentral() + maven { + name = 'papermc' + url = 'https://repo.papermc.io/repository/maven-public/' + } +} + +dependencies { + // Velocity 4.2.x auf dem Proxy (Stand 2026-10) + compileOnly 'com.velocitypowered:velocity-api:4.2.0' + annotationProcessor 'com.velocitypowered:velocity-api:4.2.0' + // LuckPerms 5.5.x auf dem Proxy + compileOnly 'net.luckperms:api:5.5' + + testImplementation 'com.velocitypowered:velocity-api:4.2.0' + testImplementation 'net.luckperms:api:5.5' + testImplementation platform('org.junit:junit-bom:5.13.4') + testImplementation 'org.junit.jupiter:junit-jupiter' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +java { + toolchain.languageVersion = JavaLanguageVersion.of(25) +} + +tasks.withType(JavaCompile).configureEach { + options.encoding = 'UTF-8' + options.release.set(25) +} + +tasks.named('test') { + useJUnitPlatform() +} + +// Hochladen auf den Proxy: ./gradlew uploadPlugin, danach `sudo systemctl restart velocity`. +// Erst in eine Temp-Datei, Prüfsumme vergleichen, dann atomar umbenennen. +tasks.register('uploadPlugin') { + dependsOn jar + doLast { + def file = jar.archiveFile.get().asFile + def checksum = file.bytes.digest('SHA-256') + def target = '/home/minecraft/velocity/plugins/chat-bridge.jar' + providers.exec { + commandLine 'scp', file.absolutePath, "minecraft@10.20.9.3:${target}.new" + }.result.get() + providers.exec { + commandLine 'ssh', 'minecraft@10.20.9.3', + "echo '${checksum} ${target}.new' | sha256sum -c --quiet && mv -f ${target}.new ${target}" + }.result.get() + } +} diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d64cd49 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a351597 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..1aa94a4 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..93e3f59 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..16813ef --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'chat-bridge' diff --git a/src/main/java/eu/mhsl/craftattack/chatbridge/Chat.java b/src/main/java/eu/mhsl/craftattack/chatbridge/Chat.java new file mode 100644 index 0000000..1ecab86 --- /dev/null +++ b/src/main/java/eu/mhsl/craftattack/chatbridge/Chat.java @@ -0,0 +1,135 @@ +package eu.mhsl.craftattack.chatbridge; + +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import com.velocitypowered.api.proxy.ServerConnection; +import net.kyori.adventure.key.Key; +import net.kyori.adventure.sound.Sound; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextColor; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; + +import java.time.Duration; +import java.time.Instant; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Öffentlicher Chat: Velocity schickt jede Zeile als Systemnachricht an alle Spieler im Netzwerk. + * Die Backends verwerfen den Chat selbst (spawn, Limbo), sonst stünde er dort doppelt. + */ +final class Chat { + private static final TextColor GRAY = TextColor.color(0x808080); + private static final TextColor SILVER = TextColor.color(0xC0C0C0); + /** Wort mit optionalem @ davor und Satzzeichen dahinter; Bedrock-Namen beginnen mit einem Punkt. */ + private static final Pattern WORD = Pattern.compile("(@?)(\\.?[A-Za-z0-9_]{1,16})([.,!?:;]*)"); + private static final Sound MENTION = Sound.sound(Key.key("entity.experience_orb.pickup"), Sound.Source.PLAYER, 1f, 1f); + + private final ProxyServer proxy; + private final Logger logger; + private final Config config; + private final Names names; + private final Mutes mutes; + + Chat(ProxyServer proxy, Logger logger, Config config, Names names, Mutes mutes) { + this.proxy = proxy; + this.logger = logger; + this.config = config; + this.names = names; + this.mutes = mutes; + } + + void handle(Player sender, String message) { + String server = serverOf(sender); + if (this.denyMuted(sender)) { + this.logger.info("[chat] [{}] {} (gestummt): {}", server, sender.getUsername(), message); + return; + } + + Set mentioned = new LinkedHashSet<>(); + Component line = Component.text() + .append(this.tag(server)) + .append(this.names.clickable(sender)) + .append(Component.text(" > ", GRAY)) + .append(this.body(message, mentioned).colorIfAbsent(SILVER)) + .build(); + + for (Player player : this.proxy.getAllPlayers()) { + if (server != null && this.config.unsilencedServers().contains(server) && server.equals(serverOf(player))) continue; + player.sendMessage(line); + } + mentioned.stream() + .filter(player -> !player.equals(sender)) + .forEach(player -> player.playSound(MENTION)); + + this.logger.info("[chat] [{}] {}: {}", server, sender.getUsername(), message); + } + + void announceJoin(Player player) { + this.broadcast(Component.text(">>> ", NamedTextColor.GREEN).append(this.names.clickable(player))); + } + + void announceLeave(Player player) { + this.broadcast(Component.text("<<< ", NamedTextColor.RED).append(this.names.clickable(player))); + } + + void broadcast(Component line) { + this.proxy.getAllPlayers().forEach(player -> player.sendMessage(line)); + } + + /** Meldet einem gestummten Spieler die Restzeit; true, wenn er gestummt ist. */ + boolean denyMuted(Player player) { + Optional until = this.mutes.mutedUntil(player.getUniqueId()); + if (until.isEmpty()) return false; + player.sendMessage(Component.text( + "Du bist für " + Mutes.format(Duration.between(Instant.now(), until.get())) + " gestummt!", + NamedTextColor.RED)); + return true; + } + + private Component tag(@Nullable String server) { + String tag = server == null ? null : this.config.serverTags().get(server); + if (tag == null) return Component.empty(); + return Component.text("[" + tag + "] ", NamedTextColor.DARK_GRAY); + } + + /** Text der Nachricht; Namen von Spielern im Netzwerk werden golden als @Name hervorgehoben. */ + private Component body(String message, Set mentioned) { + Map online = new HashMap<>(); + this.proxy.getAllPlayers().forEach(player -> online.put(player.getUsername().toLowerCase(Locale.ROOT), player)); + + TextComponent.Builder body = Component.text(); + Matcher matcher = WORD.matcher(message); + int last = 0; + while (matcher.find()) { + Player target = online.get(matcher.group(2).toLowerCase(Locale.ROOT)); + if (target == null || !isWordBoundary(message, matcher)) continue; + body.append(Component.text(message.substring(last, matcher.start()))); + body.append(Component.text("@" + target.getUsername(), NamedTextColor.GOLD)); + body.append(Component.text(matcher.group(3))); + mentioned.add(target); + last = matcher.end(); + } + body.append(Component.text(message.substring(last))); + return body.build(); + } + + private static boolean isWordBoundary(String message, Matcher matcher) { + boolean startOk = matcher.start() == 0 || Character.isWhitespace(message.charAt(matcher.start() - 1)); + boolean endOk = matcher.end() == message.length() || Character.isWhitespace(message.charAt(matcher.end())); + return startOk && endOk; + } + + static @Nullable String serverOf(Player player) { + return player.getCurrentServer().map(ServerConnection::getServerInfo).map(info -> info.getName()).orElse(null); + } +} diff --git a/src/main/java/eu/mhsl/craftattack/chatbridge/ChatBridge.java b/src/main/java/eu/mhsl/craftattack/chatbridge/ChatBridge.java new file mode 100644 index 0000000..005cda8 --- /dev/null +++ b/src/main/java/eu/mhsl/craftattack/chatbridge/ChatBridge.java @@ -0,0 +1,61 @@ +package eu.mhsl.craftattack.chatbridge; + +import com.google.inject.Inject; +import com.velocitypowered.api.event.Subscribe; +import com.velocitypowered.api.event.proxy.ProxyInitializeEvent; +import com.velocitypowered.api.plugin.Dependency; +import com.velocitypowered.api.plugin.Plugin; +import com.velocitypowered.api.plugin.annotation.DataDirectory; +import com.velocitypowered.api.proxy.ProxyServer; +import com.velocitypowered.api.proxy.messages.ChannelIdentifier; +import com.velocitypowered.api.proxy.messages.MinecraftChannelIdentifier; +import net.luckperms.api.LuckPermsProvider; +import org.slf4j.Logger; + +import java.nio.file.Path; + +@Plugin( + id = "chat-bridge", + name = "chat-bridge", + version = "1.0.0", + description = "Serverübergreifender Chat: öffentlicher Chat, /msg, Adminchat, Mute und Join/Leave", + authors = {"MHSL"}, + dependencies = {@Dependency(id = "luckperms")} +) +public final class ChatBridge { + /** Backend → Proxy: Rang-Prefixe aus spawn ({@code "prefix"}, danach Adventure-JSON oder leer). */ + static final ChannelIdentifier CHANNEL = MinecraftChannelIdentifier.create("craftattack", "chat"); + + private final ProxyServer proxy; + private final Logger logger; + private final Path dataDirectory; + + @Inject + public ChatBridge(ProxyServer proxy, Logger logger, @DataDirectory Path dataDirectory) { + this.proxy = proxy; + this.logger = logger; + this.dataDirectory = dataDirectory; + } + + @Subscribe + public void onProxyInitialize(ProxyInitializeEvent event) { + Config config; + try { + config = Config.load(this.dataDirectory); + } catch (Exception e) { + this.logger.error("Konfiguration ungültig, chat-bridge ist aus", e); + return; + } + + Names names = new Names(config); + Mutes mutes = new Mutes(LuckPermsProvider.get()); + Chat chat = new Chat(this.proxy, this.logger, config, names, mutes); + PrivateMessages privateMessages = new PrivateMessages(this.proxy, this.logger, config, names, chat); + + this.proxy.getChannelRegistrar().register(CHANNEL); + this.proxy.getEventManager().register(this, new ChatListener(this, this.proxy, this.logger, names, chat, privateMessages)); + Commands.register(this, this.proxy, this.logger, config, names, chat, privateMessages, mutes); + + this.logger.info("chat-bridge aktiv, Kürzel {}, ohne Silencer {}", config.serverTags(), config.unsilencedServers()); + } +} diff --git a/src/main/java/eu/mhsl/craftattack/chatbridge/ChatListener.java b/src/main/java/eu/mhsl/craftattack/chatbridge/ChatListener.java new file mode 100644 index 0000000..13ed184 --- /dev/null +++ b/src/main/java/eu/mhsl/craftattack/chatbridge/ChatListener.java @@ -0,0 +1,91 @@ +package eu.mhsl.craftattack.chatbridge; + +import com.google.common.io.ByteArrayDataInput; +import com.velocitypowered.api.event.Subscribe; +import com.velocitypowered.api.event.connection.DisconnectEvent; +import com.velocitypowered.api.event.connection.PluginMessageEvent; +import com.velocitypowered.api.event.player.PlayerChatEvent; +import com.velocitypowered.api.event.player.ServerPostConnectEvent; +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import com.velocitypowered.api.proxy.ServerConnection; +import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; +import org.slf4j.Logger; + +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; + +final class ChatListener { + /** Join-Meldung erst nach dieser Zeit, damit das Backend die Rang-Prefixe schon geschickt hat. */ + private static final long JOIN_DELAY_MS = 1000; + + private final Object plugin; + private final ProxyServer proxy; + private final Logger logger; + private final Names names; + private final Chat chat; + private final PrivateMessages privateMessages; + /** Wer eine Join-Meldung bekommen hat, bekommt beim Verlassen auch eine. */ + private final Set announced = ConcurrentHashMap.newKeySet(); + + ChatListener(Object plugin, ProxyServer proxy, Logger logger, Names names, Chat chat, PrivateMessages privateMessages) { + this.plugin = plugin; + this.proxy = proxy; + this.logger = logger; + this.names = names; + this.chat = chat; + this.privateMessages = privateMessages; + } + + /** + * Nur lesen, nie ablehnen: Eine signierte Nachricht abzulehnen trennt den Spieler. Das Backend + * verwirft den Chat selbst. + */ + @Subscribe + public void onChat(PlayerChatEvent event) { + this.chat.handle(event.getPlayer(), event.getMessage()); + } + + @Subscribe + public void onPluginMessage(PluginMessageEvent event) { + if (!event.getIdentifier().equals(ChatBridge.CHANNEL)) return; + event.setResult(PluginMessageEvent.ForwardResult.handled()); + // Nur Backends dürfen Prefixe setzen, ein Client könnte sich sonst einen eigenen geben + if (!(event.getSource() instanceof ServerConnection connection)) return; + + try { + ByteArrayDataInput in = event.dataAsDataStream(); + String type = in.readUTF(); + if (type.equals("prefix")) { + String json = in.readUTF(); + this.names.setPrefix( + connection.getPlayer().getUniqueId(), + connection.getServerInfo().getName(), + json.isEmpty() ? null : GsonComponentSerializer.gson().deserialize(json)); + } + } catch (Exception e) { + this.logger.warn("Ungültige Nachricht von {} für {}", connection.getServerInfo().getName(), + connection.getPlayer().getUsername(), e); + } + } + + @Subscribe + public void onServerPostConnect(ServerPostConnectEvent event) { + if (event.getPreviousServer() != null) return; + Player player = event.getPlayer(); + this.proxy.getScheduler().buildTask(this.plugin, () -> { + if (!player.isActive() || !this.announced.add(player.getUniqueId())) return; + this.chat.announceJoin(player); + }).delay(JOIN_DELAY_MS, TimeUnit.MILLISECONDS).schedule(); + } + + @Subscribe + public void onDisconnect(DisconnectEvent event) { + Player player = event.getPlayer(); + if (this.announced.remove(player.getUniqueId())) this.chat.announceLeave(player); + this.names.forget(player.getUniqueId()); + this.privateMessages.forget(player.getUniqueId()); + } +} diff --git a/src/main/java/eu/mhsl/craftattack/chatbridge/Commands.java b/src/main/java/eu/mhsl/craftattack/chatbridge/Commands.java new file mode 100644 index 0000000..1e91084 --- /dev/null +++ b/src/main/java/eu/mhsl/craftattack/chatbridge/Commands.java @@ -0,0 +1,183 @@ +package eu.mhsl.craftattack.chatbridge; + +import com.velocitypowered.api.command.CommandManager; +import com.velocitypowered.api.command.SimpleCommand; +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.event.ClickEvent; +import net.kyori.adventure.text.format.NamedTextColor; +import org.slf4j.Logger; + +import java.time.Duration; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; + +/** Befehle auf dem Proxy; sie greifen vor dem Backend und funktionieren damit auf jedem Server. */ +final class Commands { + private Commands() { + } + + static void register(Object plugin, ProxyServer proxy, Logger logger, Config config, Names names, Chat chat, + PrivateMessages privateMessages, Mutes mutes) { + CommandManager manager = proxy.getCommandManager(); + + // tell/w/whisper überdecken die Vanilla-Befehle, die am Mute vorbei flüstern würden + manager.register(manager.metaBuilder("msg").aliases("tell", "w", "whisper").plugin(plugin).build(), + new PlayerCommand() { + @Override + void run(Player sender, String[] args) { + if (args.length < 2) { + PrivateMessages.error(sender, "Es muss ein Spieler sowie eine Nachricht angegeben werden."); + return; + } + privateMessages.message(sender, args[0], String.join(" ", Arrays.copyOfRange(args, 1, args.length))); + } + + @Override + public List suggest(Invocation invocation) { + return invocation.arguments().length <= 1 ? playerNames(proxy, invocation.arguments()) : List.of(); + } + }); + + manager.register(manager.metaBuilder("r").plugin(plugin).build(), new PlayerCommand() { + @Override + void run(Player sender, String[] args) { + privateMessages.reply(sender, String.join(" ", args)); + } + }); + + manager.register(manager.metaBuilder("adminchat").plugin(plugin).build(), new PlayerCommand() { + @Override + void run(Player sender, String[] args) { + if (args.length == 0) { + PrivateMessages.error(sender, "Syntax: /adminchat "); + return; + } + String message = String.join(" ", args); + Component line = Component.text() + .append(Component.text("[Admin] ", NamedTextColor.LIGHT_PURPLE).clickEvent(ClickEvent.suggestCommand("/adminchat "))) + .append(names.plain(sender)) + .append(Component.text(" > ", NamedTextColor.DARK_GRAY)) + .append(Component.text(message)) + .build(); + proxy.getAllPlayers().stream() + .filter(player -> player.hasPermission(config.adminPermission())) + .forEach(player -> player.sendMessage(line)); + logger.info("[adminchat] {}: {}", sender.getUsername(), message); + } + + @Override + public boolean hasPermission(Invocation invocation) { + return invocation.source().hasPermission(config.adminPermission()); + } + }); + + manager.register(manager.metaBuilder("mute").plugin(plugin).build(), new SimpleCommand() { + @Override + public void execute(Invocation invocation) { + String[] args = invocation.arguments(); + int hours; + try { + if (args.length < 2) throw new NumberFormatException(); + hours = Integer.parseInt(args[1]); + if (hours < 1) throw new NumberFormatException(); + } catch (NumberFormatException e) { + invocation.source().sendMessage(Component.text("Syntax: /mute ", NamedTextColor.RED)); + return; + } + resolve(proxy, mutes, args[0]) + .thenCompose(uuid -> mutes.mute(uuid, Duration.ofHours(hours))) + .whenComplete((ignored, error) -> { + if (error != null) { + invocation.source().sendMessage(Component.text("Der Spieler " + args[0] + " ist unbekannt.", NamedTextColor.RED)); + return; + } + invocation.source().sendMessage(Component.text(args[0] + " wurde für " + hours + " Stunden gestummt!", NamedTextColor.GREEN)); + logger.info("[mute] {} stummt {} für {} h", sourceName(invocation), args[0], hours); + }); + } + + @Override + public List suggest(Invocation invocation) { + String[] args = invocation.arguments(); + if (args.length <= 1) return playerNames(proxy, args); + if (args.length == 2) return List.of("1", "2", "4", "8", "24", "48"); + return List.of(); + } + + @Override + public boolean hasPermission(Invocation invocation) { + return invocation.source().hasPermission(config.adminPermission()); + } + }); + + manager.register(manager.metaBuilder("unmute").plugin(plugin).build(), new SimpleCommand() { + @Override + public void execute(Invocation invocation) { + String[] args = invocation.arguments(); + if (args.length != 1) { + invocation.source().sendMessage(Component.text("Syntax: /unmute ", NamedTextColor.RED)); + return; + } + resolve(proxy, mutes, args[0]) + .thenCompose(mutes::unmute) + .whenComplete((ignored, error) -> { + if (error != null) { + invocation.source().sendMessage(Component.text("Der Spieler " + args[0] + " ist unbekannt.", NamedTextColor.RED)); + return; + } + invocation.source().sendMessage(Component.text(args[0] + " ist nicht mehr gestummt.", NamedTextColor.GREEN)); + logger.info("[mute] {} hebt Mute von {} auf", sourceName(invocation), args[0]); + }); + } + + @Override + public List suggest(Invocation invocation) { + return invocation.arguments().length <= 1 ? playerNames(proxy, invocation.arguments()) : List.of(); + } + + @Override + public boolean hasPermission(Invocation invocation) { + return invocation.source().hasPermission(config.adminPermission()); + } + }); + } + + /** Online zuerst über den Proxy, sonst über LuckPerms (Spieler, die schon mal da waren). */ + private static CompletableFuture resolve(ProxyServer proxy, Mutes mutes, String name) { + return proxy.getPlayer(name) + .map(player -> CompletableFuture.completedFuture(player.getUniqueId())) + .orElseGet(() -> mutes.lookup(name).thenApply(uuid -> { + if (uuid == null) throw new IllegalArgumentException("unbekannt: " + name); + return uuid; + })); + } + + private static List playerNames(ProxyServer proxy, String[] args) { + String start = args.length == 0 ? "" : args[0].toLowerCase(Locale.ROOT); + return proxy.getAllPlayers().stream() + .map(Player::getUsername) + .filter(name -> name.toLowerCase(Locale.ROOT).startsWith(start)) + .sorted(String.CASE_INSENSITIVE_ORDER) + .toList(); + } + + private static String sourceName(SimpleCommand.Invocation invocation) { + return invocation.source() instanceof Player player ? player.getUsername() : "Konsole"; + } + + /** Befehl nur für Spieler, nicht für die Konsole. */ + private abstract static class PlayerCommand implements SimpleCommand { + abstract void run(Player sender, String[] args); + + @Override + public void execute(Invocation invocation) { + if (invocation.source() instanceof Player player) run(player, invocation.arguments()); + else invocation.source().sendMessage(Component.text("Nur für Spieler.")); + } + } +} diff --git a/src/main/java/eu/mhsl/craftattack/chatbridge/Config.java b/src/main/java/eu/mhsl/craftattack/chatbridge/Config.java new file mode 100644 index 0000000..78edf2d --- /dev/null +++ b/src/main/java/eu/mhsl/craftattack/chatbridge/Config.java @@ -0,0 +1,69 @@ +package eu.mhsl.craftattack.chatbridge; + +import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Einstellungen aus {@code plugins/chat-bridge/config.properties}. Fehlt die Datei, wird die + * kommentierte Vorlage aus dem JAR geschrieben. + */ +record Config( + Map serverTags, + Set unsilencedServers, + String adminPermission, + String markerPermission +) { + static Config load(Path dataDirectory) throws IOException { + Path file = dataDirectory.resolve("config.properties"); + if (Files.notExists(file)) { + Files.createDirectories(dataDirectory); + try (InputStream template = Config.class.getResourceAsStream("/config.properties")) { + if (template == null) throw new IOException("config.properties fehlt im JAR"); + Files.copy(template, file); + } + } + + Properties properties = new Properties(); + try (Reader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) { + properties.load(reader); + } + return fromProperties(properties); + } + + static Config fromProperties(Properties p) { + return new Config( + pairs(p.getProperty("server-tags", "")), + Set.copyOf(split(p.getProperty("unsilenced-servers", ""))), + p.getProperty("admin-permission", "admin").trim(), + p.getProperty("marker-permission", "adminmarker").trim() + ); + } + + private static Map pairs(String value) { + Map pairs = new HashMap<>(); + for (String entry : split(value)) { + int separator = entry.indexOf('='); + if (separator <= 0) throw new IllegalArgumentException("server-tags: '" + entry + "' braucht Server=Kürzel"); + pairs.put(entry.substring(0, separator).trim(), entry.substring(separator + 1).trim()); + } + return Map.copyOf(pairs); + } + + private static List split(String value) { + return Arrays.stream(value.split("\\|")) + .map(String::trim) + .filter(entry -> !entry.isEmpty()) + .collect(Collectors.toList()); + } +} diff --git a/src/main/java/eu/mhsl/craftattack/chatbridge/Mutes.java b/src/main/java/eu/mhsl/craftattack/chatbridge/Mutes.java new file mode 100644 index 0000000..e387610 --- /dev/null +++ b/src/main/java/eu/mhsl/craftattack/chatbridge/Mutes.java @@ -0,0 +1,77 @@ +package eu.mhsl.craftattack.chatbridge; + +import net.luckperms.api.LuckPerms; +import net.luckperms.api.model.user.User; +import net.luckperms.api.node.Node; +import net.luckperms.api.node.NodeType; +import net.luckperms.api.node.types.PermissionNode; + +import java.time.Duration; +import java.time.Instant; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; + +/** + * Mute als zeitlich begrenzte LuckPerms-Permission {@value #NODE}. Liegt damit in der gemeinsamen + * MariaDB, gilt auf allen Servern und läuft von selbst ab. + */ +final class Mutes { + static final String NODE = "chatbridge.muted"; + + private final LuckPerms luckPerms; + + Mutes(LuckPerms luckPerms) { + this.luckPerms = luckPerms; + } + + /** Ende des Mutes eines online Spielers, leer wenn nicht gestummt. */ + Optional mutedUntil(UUID player) { + User user = this.luckPerms.getUserManager().getUser(player); + if (user == null) return Optional.empty(); + return user.getNodes(NodeType.PERMISSION).stream() + .filter(node -> node.getPermission().equals(NODE) && node.getValue()) + .filter(node -> node.hasExpiry() && !node.hasExpired()) + .map(Node::getExpiry) + .filter(Objects::nonNull) + .max(Instant::compareTo); + } + + CompletableFuture mute(UUID player, Duration duration) { + return this.modify(player, user -> { + user.data().clear(node -> node.getKey().equals(NODE)); + user.data().add(PermissionNode.builder(NODE).expiry(duration).build()); + }); + } + + CompletableFuture unmute(UUID player) { + return this.modify(player, user -> user.data().clear(node -> node.getKey().equals(NODE))); + } + + CompletableFuture lookup(String name) { + return this.luckPerms.getUserManager().lookupUniqueId(name); + } + + private CompletableFuture modify(UUID player, Consumer action) { + User online = this.luckPerms.getUserManager().getUser(player); + if (online == null) return this.luckPerms.getUserManager().modifyUser(player, action); + action.accept(online); + return this.luckPerms.getUserManager().saveUser(online); + } + + /** „2 Stunden 5 Minuten“, unter einer Minute „weniger als eine Minute“. */ + static String format(Duration duration) { + long hours = duration.toHours(); + long minutes = duration.toMinutesPart(); + if (hours == 0 && minutes == 0) return "weniger als eine Minute"; + StringBuilder text = new StringBuilder(); + if (hours > 0) text.append(hours).append(hours == 1 ? " Stunde" : " Stunden"); + if (minutes > 0) { + if (!text.isEmpty()) text.append(' '); + text.append(minutes).append(minutes == 1 ? " Minute" : " Minuten"); + } + return text.toString(); + } +} diff --git a/src/main/java/eu/mhsl/craftattack/chatbridge/Names.java b/src/main/java/eu/mhsl/craftattack/chatbridge/Names.java new file mode 100644 index 0000000..fdb2b7e --- /dev/null +++ b/src/main/java/eu/mhsl/craftattack/chatbridge/Names.java @@ -0,0 +1,78 @@ +package eu.mhsl.craftattack.chatbridge; + +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ServerConnection; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.event.ClickEvent; +import net.kyori.adventure.text.event.HoverEvent; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextColor; +import org.jetbrains.annotations.Nullable; + +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Baut den Namen eines Spielers für den Chat: Rang-Prefixe vom Backend, 🎮 für Bedrock und den + * Namen, blau für Admins. Die Prefixe schickt das Backend (spawn) über {@link ChatBridge#CHANNEL}; + * sie gelten nur, solange der Spieler auf genau diesem Server ist. + */ +final class Names { + private static final TextColor ADMIN = TextColor.color(0x00FFFF); + + private record Prefix(String server, Component component) { + } + + private final Config config; + private final Map prefixes = new ConcurrentHashMap<>(); + + Names(Config config) { + this.config = config; + } + + void setPrefix(UUID player, String server, @Nullable Component prefix) { + if (prefix == null) this.prefixes.remove(player); + else this.prefixes.put(player, new Prefix(server, prefix)); + } + + void forget(UUID player) { + this.prefixes.remove(player); + } + + /** Name ohne Klick, z. B. für die eigene Seite einer Privatnachricht. */ + Component plain(Player player) { + TextComponent.Builder name = Component.text(); + + Prefix prefix = this.prefixes.get(player.getUniqueId()); + String server = player.getCurrentServer().map(ServerConnection::getServerInfo).map(info -> info.getName()).orElse(null); + if (prefix != null && Objects.equals(prefix.server(), server)) { + name.append(prefix.component()).append(Component.space()); + } + + if (isBedrock(player.getUniqueId())) { + name.append(Component.text("🎮", NamedTextColor.GRAY) + .hoverEvent(HoverEvent.showText(Component.text( + player.getUsername() + " spielt die Minecraft: Bedrock Edition")))) + .append(Component.space()); + } + + boolean marked = player.hasPermission(this.config.markerPermission()); + name.append(Component.text(player.getUsername(), marked ? ADMIN : NamedTextColor.WHITE)); + return name.build(); + } + + /** Name mit Hover und Klick, der {@code /msg } vorschlägt. */ + Component clickable(Player player) { + return this.plain(player) + .hoverEvent(HoverEvent.showText(Component.text("Klicke, um " + player.getUsername() + " zu schreiben", NamedTextColor.GOLD))) + .clickEvent(ClickEvent.suggestCommand("/msg " + player.getUsername() + " ")); + } + + /** Floodgate vergibt Bedrock-Spielern UUIDs, deren obere 64 Bit null sind. */ + static boolean isBedrock(UUID uuid) { + return uuid.getMostSignificantBits() == 0; + } +} diff --git a/src/main/java/eu/mhsl/craftattack/chatbridge/PrivateMessages.java b/src/main/java/eu/mhsl/craftattack/chatbridge/PrivateMessages.java new file mode 100644 index 0000000..673a242 --- /dev/null +++ b/src/main/java/eu/mhsl/craftattack/chatbridge/PrivateMessages.java @@ -0,0 +1,163 @@ +package eu.mhsl.craftattack.chatbridge; + +import com.velocitypowered.api.proxy.Player; +import com.velocitypowered.api.proxy.ProxyServer; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.event.ClickEvent; +import net.kyori.adventure.text.event.HoverEvent; +import net.kyori.adventure.text.format.NamedTextColor; +import org.slf4j.Logger; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ConcurrentHashMap; + +/** + * /msg und /r über das ganze Netzwerk. Übernommen aus spawn (PrivateMessage): /r antwortet dem + * letzten Gesprächspartner; hat sich das Ziel in den letzten 30 s geändert, wird nachgefragt. + */ +final class PrivateMessages { + static final int TARGET_CHANGE_TIMEOUT_SECONDS = 30; + static final int CONVERSATION_TIMEOUT_MINUTES = 30; + private static final Component PREFIX = Component.text("[Privat] ", NamedTextColor.LIGHT_PURPLE); + + private record Conversation(UUID target, String targetName, long lastSet) { + } + + private final ProxyServer proxy; + private final Logger logger; + private final Config config; + private final Names names; + private final Chat chat; + private final Map> replyMapping = new ConcurrentHashMap<>(); + + PrivateMessages(ProxyServer proxy, Logger logger, Config config, Names names, Chat chat) { + this.proxy = proxy; + this.logger = logger; + this.config = config; + this.names = names; + this.chat = chat; + } + + void forget(UUID player) { + this.replyMapping.remove(player); + } + + void reply(Player sender, String message) { + List replyList = this.replyMapping.computeIfAbsent(sender.getUniqueId(), uuid -> new ArrayList<>()); + long now = System.currentTimeMillis(); + + synchronized (replyList) { + replyList.removeIf(conversation -> conversation.lastSet() < now - CONVERSATION_TIMEOUT_MINUTES * 60_000L); + if (replyList.isEmpty()) { + error(sender, "Du führst aktuell keine Konversation."); + return; + } + + Conversation youngest = replyList.stream() + .max(Comparator.comparingLong(Conversation::lastSet)) + .orElse(replyList.getLast()); + + if (message.isBlank()) { + Component current = this.proxy.getPlayer(youngest.target()) + .map(this.names::clickable) + .orElse(Component.text("niemandem.")); + sender.sendMessage(PREFIX.append(Component.text("Du schreibst aktuell mit ", NamedTextColor.GRAY)).append(current)); + return; + } + + List old = replyList.stream() + .filter(conversation -> conversation.lastSet() < now - TARGET_CHANGE_TIMEOUT_SECONDS * 1000L) + .toList(); + + if (old.contains(youngest) || replyList.size() == 1) { + Player target = this.proxy.getPlayer(youngest.target()).orElse(null); + if (target == null) { + error(sender, "Der Spieler " + youngest.targetName() + " ist nicht mehr verfügbar."); + return; + } + replyList.clear(); + this.whisper(sender, target, message); + return; + } + + TextComponent.Builder choice = Component.text() + .append(Component.newline()) + .append(PREFIX) + .append(Component.text("Das Ziel für /r hat sich bei dir in den letzten " + TARGET_CHANGE_TIMEOUT_SECONDS + + " Sekunden geändert. Wer soll deine Nachricht erhalten? ", NamedTextColor.RED)) + .append(Component.newline()) + .append(Component.newline()); + + if (!old.isEmpty()) { + Conversation youngestOld = old.stream() + .max(Comparator.comparingLong(Conversation::lastSet)) + .orElse(old.getLast()); + replyList.removeAll(old); + replyList.add(youngestOld); + } + + replyList.stream().map(Conversation::targetName).distinct().forEach(name -> choice + .append(Component.text("[") + .append(Component.text(name, NamedTextColor.GOLD)) + .append(Component.text("]")) + .clickEvent(ClickEvent.runCommand("/msg " + name + " " + message)) + .hoverEvent(HoverEvent.showText(Component.text("Klicke, um diesem Spieler zu schreiben.", NamedTextColor.GOLD)))) + .append(Component.text(" "))); + choice.append(Component.newline()); + sender.sendMessage(choice.build()); + } + } + + void message(Player sender, String targetName, String message) { + Player target = this.proxy.getPlayer(targetName).orElse(null); + if (target == null) { + error(sender, "Der Spieler " + targetName + " konnte nicht gefunden werden."); + return; + } + this.whisper(sender, target, message); + } + + private void whisper(Player sender, Player receiver, String message) { + // Gestummte dürfen nur noch Admins schreiben + if (!receiver.hasPermission(this.config.adminPermission()) && this.chat.denyMuted(sender)) { + this.logger.info("[msg] {} -> {} (gestummt): {}", sender.getUsername(), receiver.getUsername(), message); + return; + } + + long now = System.currentTimeMillis(); + List receiverList = this.replyMapping.computeIfAbsent(receiver.getUniqueId(), uuid -> new ArrayList<>()); + synchronized (receiverList) { + receiverList.removeIf(conversation -> conversation.target().equals(sender.getUniqueId())); + receiverList.add(new Conversation(sender.getUniqueId(), sender.getUsername(), now)); + } + List senderList = new ArrayList<>(); + senderList.add(new Conversation(receiver.getUniqueId(), receiver.getUsername(), now)); + this.replyMapping.put(sender.getUniqueId(), senderList); + + sender.sendMessage(Component.text() + .append(PREFIX.clickEvent(ClickEvent.suggestCommand("/msg " + receiver.getUsername() + " "))) + .append(this.names.plain(sender)) + .append(Component.text(" zu ", NamedTextColor.GRAY)) + .append(this.names.clickable(receiver)) + .append(Component.text(" > ", NamedTextColor.GRAY)) + .append(Component.text(message))); + receiver.sendMessage(Component.text() + .append(PREFIX.clickEvent(ClickEvent.suggestCommand("/msg " + sender.getUsername() + " "))) + .append(this.names.clickable(sender)) + .append(Component.text(" zu ", NamedTextColor.GRAY)) + .append(this.names.plain(receiver)) + .append(Component.text(" > ", NamedTextColor.GRAY)) + .append(Component.text(message))); + + this.logger.info("[msg] {} -> {}: {}", sender.getUsername(), receiver.getUsername(), message); + } + + static void error(Player player, String message) { + player.sendMessage(Component.text(message, NamedTextColor.RED)); + } +} diff --git a/src/main/resources/config.properties b/src/main/resources/config.properties new file mode 100644 index 0000000..9b1d446 --- /dev/null +++ b/src/main/resources/config.properties @@ -0,0 +1,16 @@ +# chat-bridge: serverübergreifender Chat +# Listen werden mit | getrennt. Änderungen brauchen einen Neustart von Velocity. + +# Kürzel vor Nachrichten von diesem Server (Name aus velocity.toml=Kürzel). +# Server ohne Eintrag (der Hauptserver) bekommen keins. +server-tags=arena=Arena|limbo=Limbo|event=Event|grand-event=Event + +# Server, die ihren Chat nicht selbst unterdrücken (kein spawn-Plugin bzw. kein Silencer). +# Deren Spieler sehen den Chat vom eigenen Server schon lokal und bekommen ihn von Velocity nicht +# noch einmal. Achtung: Dort greift der Mute nur für die anderen Server. +unsilenced-servers=event|grand-event + +# Adminchat, /mute und /unmute (LuckPerms auf Velocity) +admin-permission=admin +# Wer diese Permission hat, erscheint blau (invis_admin und technical haben sie auf false) +marker-permission=adminmarker diff --git a/src/test/java/eu/mhsl/craftattack/chatbridge/ConfigTest.java b/src/test/java/eu/mhsl/craftattack/chatbridge/ConfigTest.java new file mode 100644 index 0000000..387350e --- /dev/null +++ b/src/test/java/eu/mhsl/craftattack/chatbridge/ConfigTest.java @@ -0,0 +1,33 @@ +package eu.mhsl.craftattack.chatbridge; + +import org.junit.jupiter.api.Test; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Properties; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class ConfigTest { + @Test + void templateLoads() throws Exception { + Properties properties = new Properties(); + try (InputStream in = ConfigTest.class.getResourceAsStream("/config.properties")) { + properties.load(new InputStreamReader(in, StandardCharsets.UTF_8)); + } + Config config = Config.fromProperties(properties); + assertEquals("Arena", config.serverTags().get("arena")); + assertEquals(Set.of("event", "grand-event"), config.unsilencedServers()); + assertEquals("adminmarker", config.markerPermission()); + } + + @Test + void formatsMuteDuration() { + assertEquals("weniger als eine Minute", Mutes.format(Duration.ofSeconds(30))); + assertEquals("1 Stunde 5 Minuten", Mutes.format(Duration.ofMinutes(65))); + assertEquals("48 Stunden", Mutes.format(Duration.ofHours(48))); + } +}