diff --git a/build.gradle b/build.gradle index 8d62beb..934e75a 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,6 @@ plugins { id 'net.minecraftforge.gradle' version '[6.0.16,6.2)' } - group = mod_group_id version = mod_version @@ -130,6 +129,7 @@ dependencies { // If the group id is "net.minecraft" and the artifact id is one of ["client", "server", "joined"], // then special handling is done to allow a setup of a vanilla dependency without the use of an external repository. minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}" + implementation 'org.yaml:snakeyaml:1.33' // Example mod dependency with JEI - using fg.deobf() ensures the dependency is remapped to your development mappings // The JEI API is declared for compile time use, while the full JEI artifact is used at runtime diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..9bbc975 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 index f57a814..df97d72 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1 +1,7 @@ -distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..faf9300 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/platforms/jvm/plugins-application/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 -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || 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, 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..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@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. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +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/src/main/java/fr/liveinground/admin_craft/AdminCraft.java b/src/main/java/fr/liveinground/admin_craft/AdminCraft.java index ca4fadb..bae6c79 100644 --- a/src/main/java/fr/liveinground/admin_craft/AdminCraft.java +++ b/src/main/java/fr/liveinground/admin_craft/AdminCraft.java @@ -17,6 +17,7 @@ import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; +import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.RegisterCommandsEvent; import net.minecraftforge.event.TickEvent; @@ -27,9 +28,11 @@ import net.minecraftforge.event.level.ExplosionEvent; import net.minecraftforge.event.server.ServerAboutToStartEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; +import net.minecraftforge.fml.StartupMessageManager; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.config.ModConfig; import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext; +import net.minecraftforge.fml.loading.FMLEnvironment; import org.slf4j.Logger; import java.util.ArrayList; @@ -42,23 +45,32 @@ public class AdminCraft { public static final String _VERSION = "1.0.0"; public static final Logger LOGGER = LogUtils.getLogger(); private static final String SP_TAG = "inSpawnProtection"; + public static SanctionConfig sanctionConfig; public static List mutedPlayersUUID = new ArrayList<>(); public static List frozenPlayersUUID = new ArrayList<>(); public static PlayerDataManager playerDataManager; public AdminCraft(FMLJavaModLoadingContext ctx) { + if (FMLEnvironment.dist == Dist.CLIENT) { + StartupMessageManager.addModMessage("AdminCraft mod can only be loaded on a server! " + + "Please remove it from your 'mods' folder."); + LOGGER.error("AdminCraft mod can only be loaded on a server! " + + "Please remove it from your 'mods' folder."); + return; + } + ctx.registerConfig(ModConfig.Type.SERVER, Config.SPEC); MinecraftForge.EVENT_BUS.register(this); MinecraftForge.EVENT_BUS.register(MuteEventsHandler.class); MinecraftForge.EVENT_BUS.register(FreezeEventListener.class); - - ctx.registerConfig(ModConfig.Type.SERVER, Config.SPEC); } + /* @SubscribeEvent public void onServerStarted(ServerAboutToStartEvent event) { - SanctionConfig.load(event.getServer().getServerDirectory().toPath().resolve("world").resolve("serverconfig")); - } + sanctionConfig = new SanctionConfig(event.getServer().getServerDirectory().toPath().resolve("world").resolve("serverconfig")); + sanctionConfig.load(); + }*/ @SubscribeEvent public void onCommandRegister(RegisterCommandsEvent event) { @@ -69,10 +81,7 @@ public void onCommandRegister(RegisterCommandsEvent event) { AltCommand.register(dispatcher); SanctionCommand.register(dispatcher); FreezeCommand.register(dispatcher); - if (Config.enable_reports) { - LOGGER.debug("Enabling reports"); - ReportCommand.register(dispatcher); - } + ReportCommand.register(dispatcher); TempBanCommand.register(dispatcher); // StaffModeCommand.register(dispatcher); } diff --git a/src/main/java/fr/liveinground/admin_craft/Config.java b/src/main/java/fr/liveinground/admin_craft/Config.java index 057d164..bd34087 100644 --- a/src/main/java/fr/liveinground/admin_craft/Config.java +++ b/src/main/java/fr/liveinground/admin_craft/Config.java @@ -1,5 +1,7 @@ package fr.liveinground.admin_craft; +import fr.liveinground.admin_craft.storage.types.sanction.Sanction; +import fr.liveinground.admin_craft.storage.types.sanction.SanctionTemplate; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.effect.MobEffect; import net.minecraft.world.level.block.Block; @@ -52,6 +54,14 @@ public class Config { private static final ForgeConfigSpec.IntValue TEMPBAN_LEVEL; public static int tempban_level; + // --------------- + // -- Sanctions -- + // --------------- + + private static final ForgeConfigSpec.ConfigValue> SANCTION_TEMPLATES; + public static final List availableReasons = new ArrayList<>(); + public static final Map> sanctions = new HashMap<>(); + // ---------------------- // -- Spawn protection -- // ---------------------- @@ -119,7 +129,7 @@ public class Config { // -- Reports -- // ------------- - private static final ForgeConfigSpec.BooleanValue ENABLE_REPORTS; + public static final ForgeConfigSpec.BooleanValue ENABLE_REPORTS; public static boolean enable_reports; private static final ForgeConfigSpec.BooleanValue USE_SANCTIONS_REASONS; @@ -205,6 +215,16 @@ public class Config { BUILDER.pop(); } + static { + BUILDER.push("presetSanctions"); + + SANCTION_TEMPLATES = BUILDER.comment("The sanction presets for the /sanction command. Must follow the format 'displayName@used reason@level->type:duration(if required)@level@...'.") + .comment("Exemple: 'Cheating@Using cheats to get unfair advantages@1->warn@2->tempban:5d@5:ban'") + .comment("This config key will be updated in hte future to be more intuitive, stay tuned!") + .define("sanctions", List.of("Cheating@Unfair advantage@1->tempban:1d@2->tempban:30d@3->ban", + "spam@Spamming@1->warn@3->kick@4->tempmute:1d@5->mute")); + } + static { BUILDER.push("spawnProtection"); @@ -343,6 +363,55 @@ static void onLoad(final ModConfigEvent.Loading event) { reports_level = REPORTS_LEVEL.get(); tempban_level = TEMPBAN_LEVEL.get(); + // --------------- + // -- Sanctions -- + // --------------- + + for (String entry: SANCTION_TEMPLATES.get()) { + try { + String[] parts = entry.split("@"); + if (parts.length < 3) { + AdminCraft.LOGGER.error("Invalid template: " + entry); + continue; + } + + String displayName = parts[0].trim(); + String reason = parts[1].trim(); + + availableReasons.add(displayName); + Map levels = new HashMap<>(); + + for (int i = 2; i < parts.length; i++) { + String segment = parts[i].trim(); + String[] levelSplit = segment.split("->"); + if (levelSplit.length != 2) continue; + + int level = Integer.parseInt(levelSplit[0].trim()); + String action = levelSplit[1].trim(); + + String duration = null; + Sanction type; + + if (action.contains(":")) { + String[] actSplit = action.split(":"); + type = Sanction.valueOf(actSplit[0].trim().toUpperCase()); + duration = actSplit[1].trim(); + } else { + type = Sanction.valueOf(action.trim().toUpperCase()); + } + + SanctionTemplate template = new SanctionTemplate(displayName, reason, type, duration); + levels.put(level, template); + } + + sanctions.put(displayName, levels); + } catch (Exception e) { + AdminCraft.LOGGER.error("Error parsing sanction template: " + entry); + AdminCraft.LOGGER.error(e.getMessage()); + e.printStackTrace(); + } + } + // ---------------------- // -- Spawn protection -- // ---------------------- diff --git a/src/main/java/fr/liveinground/admin_craft/commands/moderation/ReportCommand.java b/src/main/java/fr/liveinground/admin_craft/commands/moderation/ReportCommand.java index d569b21..e1522ae 100644 --- a/src/main/java/fr/liveinground/admin_craft/commands/moderation/ReportCommand.java +++ b/src/main/java/fr/liveinground/admin_craft/commands/moderation/ReportCommand.java @@ -30,6 +30,7 @@ public class ReportCommand { public static void register(CommandDispatcher dispatcher) { dispatcher.register(Commands.literal("report") + .requires(ignored -> Config.enable_reports) .then(Commands.argument("player", EntityArgument.player()) .then(Commands.argument("reason", StringArgumentType.greedyString()) .executes(ctx -> { @@ -89,7 +90,7 @@ public static void register(CommandDispatcher dispatcher) { PlayerReportsData data = AdminCraft.playerDataManager.getReportDatasByUUID(player.getStringUUID()); if (data == null) { - ctx.getSource().sendSuccess(() -> Component.literal(player.getDisplayName().getString() + " wasn't reported."), false); + ctx.getSource().sendSuccess(() -> Component.literal(player.getDisplayName().getString() + " wasn't reported yet."), false); return 1; } StringBuilder list = new StringBuilder(player.getDisplayName().getString() + "'s reports"); diff --git a/src/main/java/fr/liveinground/admin_craft/commands/moderation/SanctionCommand.java b/src/main/java/fr/liveinground/admin_craft/commands/moderation/SanctionCommand.java index 9217812..69b34ca 100644 --- a/src/main/java/fr/liveinground/admin_craft/commands/moderation/SanctionCommand.java +++ b/src/main/java/fr/liveinground/admin_craft/commands/moderation/SanctionCommand.java @@ -27,7 +27,7 @@ public class SanctionCommand { private static final SuggestionProvider REASON_SUGGESTIONS = (context, builder) -> { - List reasons = SanctionConfig.availableReasons; + List reasons = Config.availableReasons; if (reasons == null || reasons.isEmpty()) reasons = Collections.emptyList(); return SharedSuggestionProvider.suggest(reasons, builder); }; @@ -39,11 +39,11 @@ public static void register(CommandDispatcher dispatcher) { .then(Commands.argument("reason", StringArgumentType.word()).suggests(REASON_SUGGESTIONS).executes(ctx -> { ServerPlayer sanctionedPlayer = EntityArgument.getPlayer(ctx, "player"); String reason = StringArgumentType.getString(ctx, "reason"); - if (!SanctionConfig.availableReasons.contains(reason)) { + if (!Config.availableReasons.contains(reason)) { ctx.getSource().sendFailure(Component.literal("This reason is not configured yet.")); return 1; } - Map sanctionMap = SanctionConfig.sanctions.get(reason); + Map sanctionMap = Config.sanctions.get(reason); PlayerHistoryData history = AdminCraft.playerDataManager.getHistoryFromUUID(sanctionedPlayer.getStringUUID()); int counter = 0; if (!(history==null || history.sanctionList.isEmpty())) { @@ -54,6 +54,11 @@ public static void register(CommandDispatcher dispatcher) { } } + if (sanctionMap.isEmpty()) { + ctx.getSource().sendFailure(Component.literal("This reason is not configured yet.")); + return 1; + } + if (counter > sanctionMap.size()) counter = sanctionMap.size(); boolean ok = false; SanctionTemplate template=null; while (!ok) { diff --git a/src/main/java/fr/liveinground/admin_craft/mixins/PlayerRespawnMixin.java b/src/main/java/fr/liveinground/admin_craft/mixins/PlayerRespawnMixin.java index 8f991b5..c6b6be2 100644 --- a/src/main/java/fr/liveinground/admin_craft/mixins/PlayerRespawnMixin.java +++ b/src/main/java/fr/liveinground/admin_craft/mixins/PlayerRespawnMixin.java @@ -1,6 +1,5 @@ package fr.liveinground.admin_craft.mixins; -import fr.liveinground.admin_craft.AdminCraft; import fr.liveinground.admin_craft.Config; import net.minecraft.core.BlockPos; import net.minecraft.server.level.ServerLevel; @@ -16,30 +15,26 @@ public class PlayerRespawnMixin { @Inject( method = "respawn", - at = @At("RETURN"), - cancellable = true) + at = @At("HEAD"), + cancellable = true + ) private void onRespawn(ServerPlayer player, boolean keepEverything, CallbackInfoReturnable cir) { + if (!Config.spawn_override) return; ServerLevel overworld = player.getServer().overworld(); - BlockPos current = player.getRespawnPosition(); - BlockPos defaultSpawn = overworld.getSharedSpawnPos(); + BlockPos configuredSpawn = new BlockPos(Config.spawn_x, Config.spawn_y, Config.spawn_z); - if (!defaultSpawn.equals(configuredSpawn)) { - overworld.setDefaultSpawnPos(configuredSpawn, 0); - } - defaultSpawn = overworld.getSharedSpawnPos(); - if (!defaultSpawn.equals(configuredSpawn)) { - AdminCraft.LOGGER.warn("Failed to change shared spawn pos"); - } - if ((current == null || current.equals(defaultSpawn)) && Config.spawn_override) { - player.setRespawnPosition( - Level.OVERWORLD, - new BlockPos(Config.spawn_x, Config.spawn_y, Config.spawn_z), - 0f, - true, - false - ); + BlockPos respawnPosition = player.getRespawnPosition(); + boolean hasResp = (respawnPosition != null && !respawnPosition.equals(overworld.getSharedSpawnPos())); + + if (!hasResp) { + if (!overworld.getSharedSpawnPos().equals(configuredSpawn)) { + overworld.setDefaultSpawnPos(configuredSpawn, 0); + } + + player.setRespawnPosition(Level.OVERWORLD, configuredSpawn, 0f, true, false); + + cir.setReturnValue(player); } - cir.setReturnValue(player); } } diff --git a/src/main/java/fr/liveinground/admin_craft/moderation/SanctionConfig.java b/src/main/java/fr/liveinground/admin_craft/moderation/SanctionConfig.java index 0118ec7..d6d0a22 100644 --- a/src/main/java/fr/liveinground/admin_craft/moderation/SanctionConfig.java +++ b/src/main/java/fr/liveinground/admin_craft/moderation/SanctionConfig.java @@ -1,7 +1,5 @@ package fr.liveinground.admin_craft.moderation; -import com.electronwill.nightconfig.core.CommentedConfig; -import com.electronwill.nightconfig.core.file.FileConfig; import fr.liveinground.admin_craft.AdminCraft; import fr.liveinground.admin_craft.Config; import fr.liveinground.admin_craft.PlaceHolderSystem; @@ -10,8 +8,11 @@ import org.jetbrains.annotations.Nullable; import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.*; @@ -19,112 +20,137 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; + + public class SanctionConfig { - static FileConfig sanctionConfig; - public static Map> sanctions = new HashMap<>(); // Sanction config - public static List availableReasons = new ArrayList<>(); + /* + private final Path file; + private final List availableReasons = new ArrayList<>(); + private final Map> sanctions = new HashMap<>(); + + public SanctionConfig(Path configDir) { + this.file = configDir.resolve("admin_craft_sanctions.yml"); + } - public static void load(Path configDir) { - Path file = configDir.resolve("admin_craft_sanctions.toml"); - AdminCraft.LOGGER.debug("Loading sanctions configuration (" + file + ")"); + public void load() { + sanctions.clear(); + availableReasons.clear(); if (!Files.exists(file)) { - AdminCraft.LOGGER.debug("Files doesn't exist"); try { - Files.createFile(file); - - // Default config file - Files.writeString(file, """ - # NOTE: The server has to restart to reload this file. - [reasons] - [reasons.cheat] - # This will be displayed in commands, must contain only ONE word (but you still can use underscores)! - displayName = "Cheating" - - # This is used as reason message - message = "Cheating / Unfair advantage" - - 1 = "tempban:1d" # the first one is mandatory - 2 = "tempban:3m" - 3 = "ban" - - [reasons.spam] - displayName = "Spam" - message = "Spamming is not allowed!" - 1 = "warn" - 2 = "kick" - 3 = "tempmute:1h" - 5 = "ban" - """); - AdminCraft.LOGGER.debug("File created and written"); + createDefault(); } catch (IOException e) { - AdminCraft.LOGGER.error(e.getMessage()); + throw new RuntimeException("Failed to create default config", e); } } - sanctionConfig = FileConfig.builder(file).autoreload().autosave().build(); - sanctionConfig.load(); - AdminCraft.LOGGER.debug("File loaded"); + Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); - sanctions.clear(); - AdminCraft.LOGGER.debug("Previous data cleared"); - - if (sanctionConfig.contains("reasons")) { - AdminCraft.LOGGER.debug("'reasons' key detected"); - var reasons = sanctionConfig.get("reasons"); - if (reasons instanceof CommentedConfig commentedConfig) { - AdminCraft.LOGGER.debug("'reasons' key is instance of Map"); - Map map = commentedConfig.valueMap(); - for (var entry : map.entrySet()) { - String reason = entry.getKey(); - AdminCraft.LOGGER.debug("Subkey '" + reason + "'"); // this never appear - Map sanctionsMap = new HashMap<>(); - - // Fallbacks - String displayName = reason; - if (displayName.contains(" ")) { - AdminCraft.LOGGER.warn("A custom sanction reason contains a space, skipping..."); - continue; - } - String message = ""; - - if (entry.getValue() instanceof Map inner) { - for (var innerEntry : inner.entrySet()) { - String key = innerEntry.getKey().toString(); - - if (key.equalsIgnoreCase("displayName")) { - displayName = innerEntry.getValue().toString(); - availableReasons.add(displayName); - AdminCraft.LOGGER.debug("New reason displayName added to list: " + displayName); - continue; - } - if (key.equalsIgnoreCase("message")) { - message = innerEntry.getValue().toString(); - continue; - } - - try { - int lvl = Integer.parseInt(key); - String sanctionStr = innerEntry.getValue().toString(); - - String[] parts = sanctionStr.split(":", 2); - Sanction type = Sanction.valueOf(parts[0].toUpperCase()); - String duration = parts.length > 1 ? parts[1] : ""; - if (!checkDuration(duration)) continue; - - SanctionTemplate s = new SanctionTemplate(displayName, message, type, duration); - sanctionsMap.put(lvl, s); - } catch (NumberFormatException ex) { - AdminCraft.LOGGER.warn("Invalid key in " + reason + ": " + key); - } + try (InputStream in = Files.newInputStream(file)) { + Object root = yaml.load(in); + if (!(root instanceof Map map)) { + AdminCraft.LOGGER.error("Invalid YAML format in " + file); + return; + } + + Object reasonsObj = map.get("reasons"); + if (!(reasonsObj instanceof Map reasons)) { + System.err.println("'reasons' section is missing"); + return; + } + + for (Map.Entry entry : reasons.entrySet()) { + String key = entry.getKey().toString(); + Object sectionObj = entry.getValue(); + if (!(sectionObj instanceof Map section)) continue; + + Object displayNameObj = section.get("displayName"); + String displayName = (displayNameObj != null) ? displayNameObj.toString() : key; + Object messageObj = section.get("message"); + String message = (messageObj != null) ? messageObj.toString() : "No message provided"; + + Map levelMap = new HashMap<>(); + + Object levelsObj = section.get("levels"); + if (levelsObj instanceof Map levels) { + for (Map.Entry levelEntry : levels.entrySet()) { + try { + int level = Integer.parseInt(levelEntry.getKey().toString()); + String raw = levelEntry.getValue().toString(); + SanctionTemplate template = parseTemplate(displayName, message, raw); + levelMap.put(level, template); + } catch (NumberFormatException e) { + System.err.println("Invalid level in " + key + ": " + levelEntry.getKey()); } } - sanctions.put(reason, sanctionsMap); } + + sanctions.put(displayName, levelMap); + availableReasons.add(displayName); } + + System.out.println("Sanctions loaded: " + availableReasons.size() + " reasons."); + } catch (IOException e) { + throw new RuntimeException("Issue when reading " + file, e); + } + } + + private SanctionTemplate parseTemplate(String name, String message, String raw) { + if (raw == null) return new SanctionTemplate(name, message, Sanction.WARN, null); + + String[] parts = raw.split(":", 2); + String typeStr = parts[0].toLowerCase(); + String duration = parts.length > 1 ? parts[1] : null; + + Sanction type = switch (typeStr) { + case "warn" -> Sanction.WARN; + case "kick" -> Sanction.KICK; + case "ban" -> Sanction.BAN; + case "tempban" -> Sanction.TEMPBAN; + case "tempmute" -> Sanction.TEMPMUTE; + default -> throw new IllegalStateException("Unexpected value: " + typeStr); + }; + + return new SanctionTemplate(name, message, type, duration); + } + + private void createDefault() throws IOException { + Files.createDirectories(file.getParent()); + try (OutputStream out = Files.newOutputStream(file, StandardOpenOption.CREATE_NEW)) { + String defaultYaml = """ + reasons: + cheat: + displayName: "Cheating" + message: "Cheating / Unfair advantage" + levels: + 1: "tempban:1d" + 2: "tempban:60d" + 3: "ban" + + spam: + displayName: "Spam" + message: "Spamming is not allowed!" + levels: + 1: "warn" + 2: "kick" + 3: "tempmute:1h" + 5: "ban" + """; + out.write(defaultYaml.getBytes()); } } + public List getAvailableReasons() { + return Collections.unmodifiableList(availableReasons); + } + + public Map> getSanctions() { + return Collections.unmodifiableMap(sanctions); + }*/ + public static boolean checkDuration(String input) { return (getDuration(input) != null); } diff --git a/src/main/java/fr/liveinground/admin_craft/storage/types/sanction/SanctionTemplate.java b/src/main/java/fr/liveinground/admin_craft/storage/types/sanction/SanctionTemplate.java index de30884..c09426a 100644 --- a/src/main/java/fr/liveinground/admin_craft/storage/types/sanction/SanctionTemplate.java +++ b/src/main/java/fr/liveinground/admin_craft/storage/types/sanction/SanctionTemplate.java @@ -1,4 +1,3 @@ package fr.liveinground.admin_craft.storage.types.sanction; -public record SanctionTemplate(String name, String sanctionMessage, Sanction type, String duration) { -} +public record SanctionTemplate(String name, String sanctionMessage, Sanction type, String duration) { }