diff --git a/Jenkinsfile b/Jenkinsfile index dfb60f5..0b167bd 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -3,7 +3,7 @@ pipeline { stages { stage('Build') { tools { - jdk "jdk17" + jdk "jdk25" } steps { sh './gradlew publish' diff --git a/README.md b/README.md index c94c22b..a2122c3 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -***WARNING: Versions for Minecraft 1.20.x are not fully tested yet.*** +***WARNING: Versions for Minecraft 1.21.x are not fully tested yet.*** Please create an issus if you find anything wrong. Thank you. All versions can be found at [Github Release Page](https://github.com/GreenSurvivors/Padlock/releases). diff --git a/build.gradle b/build.gradle deleted file mode 100644 index fa5be72..0000000 --- a/build.gradle +++ /dev/null @@ -1,92 +0,0 @@ -plugins { - id 'java-library' - id 'maven-publish' - id("io.papermc.paperweight.userdev") version "1.7.1" - id("xyz.jpenilla.run-paper") version "2.3.0" -} -// Suppiled by Jenkins -ext.majorVersion = 2 -ext.minorVersion = 14 -ext.minecraftVersion = "1.20.4" - -ext.buildNumber = System.env.BUILD_NUMBER == null ? "dev" : "build" + "$System.env.BUILD_NUMBER" -ext.mavenDirectory = System.env.MAVEN_DIR == null ? "$projectDir/repo" : "$System.env.MAVEN_DIR" -ext.jdDirectory = System.env.JAVADOCS_DIR == null ? null : "$System.env.JAVADOCS_DIR" - -// differet version convension from Nyaa plugins -group = "de.greensurvivors" -archivesBaseName = "Padlock" -version = "$majorVersion.$minorVersion.$buildNumber".toString() -/* -// comment this in, if you want to test with a specific Mc version instead of the one defined in minecraftVersion -runServer { - minecraftVersion("1.20.4") -} - */ - -java { - // Configure the java toolchain. This allows gradle to auto-provision JDK 17 on systems that only have JDK 8 installed for example. - toolchain.languageVersion.set(JavaLanguageVersion.of(17)) -} - -// extra compile warnings -compileJava { - options.compilerArgs += ["-Xlint:deprecation"] - options.encoding = 'UTF-8' - - // Set the release flag. This configures what version bytecode the compiler will emit, as well as what JDK APIs are usable. - // See https://openjdk.java.net/jeps/247 for more information. - options.release.set(17) -} - -repositories { - mavenCentral() - maven { name 'Paper'; url 'https://repo.papermc.io/repository/maven-public/' } - maven { name 'sk89q-repo'; url "https://maven.enginehub.org/repo/" } //worldguard - maven { url 'https://jitpack.io' } // vault -} - -dependencies { - implementation 'org.apache.commons:commons-collections4:4.4' - implementation 'org.jetbrains:annotations:24.1.0' - implementation("com.github.ben-manes.caffeine:caffeine:3.1.8") // caches - implementation("de.mkammerer:argon2-jvm:2.11") // native password hashing with argon2 - - paperweight.paperDevBundle("$minecraftVersion-R0.1-SNAPSHOT") - compileOnly ('com.sk89q.worldguard:worldguard-bukkit:7.1.0-SNAPSHOT') { transitive = false } - compileOnly('com.github.MilkBowl:VaultAPI:1.7') { transitive = false } -} - -processResources { - expand version: project.version, - mcVersion: "$minecraftVersion" -} - -// maven publications -tasks.register('sourcesJar', Jar) { - archiveClassifier.set("sources") - from sourceSets.main.java.srcDirs -} - -tasks { - // Configure reobfJar to run when invoking the build task - assemble { - dependsOn(reobfJar) - } -} - -publishing { - publications { - mavenJava(MavenPublication) { - artifact sourcesJar - artifactId "padlock" - version "$majorVersion.$minorVersion-SNAPSHOT" - from components.java - } - } - repositories { - maven { - url "$mavenDirectory" - } - } -} diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..e8cbf23 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,137 @@ +plugins { + `java-library` + `maven-publish` + id("io.papermc.paperweight.userdev") version "2.0.0-beta.21" + id("xyz.jpenilla.run-paper") version "3.0.2" +} + +val mavenDirectory: String = if (System.getenv("MAVEN_DIR") == null) { + "$projectDir/repo" +} else System.getenv("MAVEN_DIR") +val jdDirectory: String? = if (System.getenv("JAVADOCS_DIR") == null) { + null +} else System.getenv("JAVADOCS_DIR") + +// different version convention than Nyaa plugins +group = "de.greensurvivors" +version = buildString { + append(getProperty("plugin_version")) + + if (getProperty("is_release").toBoolean().not()) { + append("-Snapshot") + } + + append("+${getProperty("minecraft_version")}") + + if (System.getenv("BUILD_NUMBER") != null) { + append("+${System.getenv("BUILD_NUMBER")}") + } +} +description = "Padlock is a chest protection plugin for Paper." + + " It is 80% compatible with original Lockette," + + " but delivers a lot of performance enhancements and feature options." + +java { + // Configure the java toolchain. This allows gradle to auto-provision JDK 21 on systems that only have JDK 8 installed for example. + toolchain.languageVersion.set(JavaLanguageVersion.of(getProperty("java_version").toInt())) + + withSourcesJar() + //withJavadocJar() +} + +repositories { + mavenCentral() + maven { + name = "Paper" + url = uri("https://repo.papermc.io/repository/maven-public/") + } + maven { //worldguard + name = "sk89q-repo" + url = uri("https://maven.enginehub.org/repo/") + } + maven { // vault + url = uri("https://jitpack.io") + } +} + +dependencies { + paperweight.paperDevBundle("${getProperty("minecraft_version")}.build.+") + + implementation("org.apache.commons:commons-collections4:${getProperty("commons_collections_version")}") + compileOnly("com.github.ben-manes.caffeine:caffeine:${getProperty("caffeine_version")}") // caches + implementation("de.mkammerer:argon2-jvm:${getProperty("argon_version")}") // native password hashing with argon2 + + compileOnly("com.sk89q.worldguard:worldguard-bukkit:${getProperty("worldguard_compileVersion")}") { + isTransitive = false + } + compileOnly("com.github.MilkBowl:VaultAPI:${getProperty("vault_version")}") { + isTransitive = false + } +} + +tasks { + processResources { + filteringCharset = Charsets.UTF_8.name() // We want UTF-8 for everything + + expand( + providers.gradlePropertiesPrefixedBy("") + .get() + .toMutableMap() // f you gradle for being inconvenient in newer versions + .plus("version" to version) + .plus("description" to description) + ) + } + + compileJava { + // extra compile warnings + // options.compilerArgs += ["-Xlint:deprecation"] + options.encoding = Charsets.UTF_8.name() // We want UTF-8 for everything + + // Set the release flag. This configures what version bytecode the compiler will emit, as well as what JDK APIs are usable. + // See https://openjdk.java.net/jeps/247 for more information. + options.release.set(getProperty("java_version").toInt()) + } + + runServer { + downloadPlugins { + // make sure to double-check the version id on the Modrinth version page + modrinth("worldedit", getProperty("worldEdit_runVersion")) + modrinth("worldguard", getProperty("worldGuard_runVersion")) + } + + // disable bstats, as it isn't needed for dev environment + doFirst { // this happens after downloading the plugins above, but before the server starts + val cfg = runDirectory.get().asFile.resolve("plugins/bStats/config.yml") + if (!cfg.exists()) { + cfg.parentFile.mkdirs() + cfg.createNewFile() + } + cfg.writeText("enabled: false\n") + } + // automatically agree to eula + jvmArgs("-Dcom.mojang.eula.agree=true") + } +} + +publishing { + publications { + create("Padlock") { + from(components["java"]) + artifactId = "Padlock" + version = buildString { // don't include mc version nor build number here + append(getProperty("plugin_version")) + + if (getProperty("is_release").toBoolean().not()) { + append("-Snapshot") + } + } + } + } + repositories { + maven { + url = uri(mavenDirectory) + } + } +} + +private fun getProperty(value: String): String = providers.gradleProperty(value).get() diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..4e07569 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,16 @@ +# Done to increase the memory available to Gradle. +org.gradle.jvmargs=-Xmx1G + +java_version=25 +plugin_version=3.18.0 +is_release=false +minecraft_version=26.2 +# dependencies +caffeine_version=3.2.3 +commons_collections_version=4.5.0 +argon_version=2.12 +worldguard_compileVersion=7.0.18-SNAPSHOT +vault_version=1.7.1 +# runtime dependencies +worldEdit_runVersion=qNuPcliz +worldGuard_runVersion=7.0.18 \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 7f93135..b1b8ef5 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 9355b41..a9db115 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,7 +1,9 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.1-bin.zip networkTimeout=10000 +retries=0 +retryBackOffMs=500 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 1aa94a4..249efbb 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright © 2015-2021 the original authors. +# Copyright © 2015 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. @@ -15,10 +15,12 @@ # 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. +# gradlew start up script for POSIX generated by Gradle. # # Important for running: # @@ -27,7 +29,7 @@ # bash, then to run this script, type that shell name before the whole # command line, like: # -# ksh Gradle +# ksh gradlew # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: @@ -55,7 +57,7 @@ # 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 +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/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/. @@ -84,7 +86,7 @@ done # 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 +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 @@ -112,7 +114,6 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -170,7 +171,6 @@ fi # 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" ) @@ -203,15 +203,14 @@ fi 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, +# * 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 \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" # Stop when "xargs" is not available. diff --git a/gradlew.bat b/gradlew.bat index 6689b85..8508ef6 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,16 +13,18 @@ @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 gradlew startup script for Windows @rem @rem ########################################################################## -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @@ -43,13 +45,13 @@ 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. +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 +"%COMSPEC%" /c exit 1 :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% @@ -57,36 +59,24 @@ 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. +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 +"%COMSPEC%" /c exit 1 :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 +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel -:omega +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/src/main/java/de/greensurvivors/padlock/Padlock.java b/src/main/java/de/greensurvivors/padlock/Padlock.java index 83a1355..6f6aa8f 100644 --- a/src/main/java/de/greensurvivors/padlock/Padlock.java +++ b/src/main/java/de/greensurvivors/padlock/Padlock.java @@ -3,10 +3,10 @@ import de.greensurvivors.padlock.command.ApplyPassword; import de.greensurvivors.padlock.command.MainCommand; import de.greensurvivors.padlock.config.ConfigManager; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.impl.DependencyManager; import de.greensurvivors.padlock.impl.LockCacheManager; import de.greensurvivors.padlock.impl.openabledata.OpenableToggleManager; +import de.greensurvivors.padlock.language.MessageManager; import de.greensurvivors.padlock.listener.*; import org.bukkit.Bukkit; import org.bukkit.command.PluginCommand; @@ -43,10 +43,6 @@ public void onEnable() { if (lockettePro != null) { plugin.getLogger().warning("I found LockettePro and disabled it. Please remove LockettePro from your Plugin list!"); - // unregister lockette cmds - Bukkit.getCommandMap().getKnownCommands().entrySet().removeIf( - entry -> entry.getValue() instanceof PluginCommand cmd && cmd.getPlugin() == lockettePro); - Bukkit.getPluginManager().disablePlugin(lockettePro); } diff --git a/src/main/java/de/greensurvivors/padlock/PadlockAPI.java b/src/main/java/de/greensurvivors/padlock/PadlockAPI.java index 5a97199..cc6ed32 100644 --- a/src/main/java/de/greensurvivors/padlock/PadlockAPI.java +++ b/src/main/java/de/greensurvivors/padlock/PadlockAPI.java @@ -4,7 +4,8 @@ import de.greensurvivors.padlock.impl.dataTypes.DoubleBlockParts; import de.greensurvivors.padlock.impl.dataTypes.LazySignProperties; import de.greensurvivors.padlock.impl.openabledata.Openables; -import de.greensurvivors.padlock.impl.signdata.*; +import de.greensurvivors.padlock.impl.signdata.SignExpiration; +import de.greensurvivors.padlock.impl.signdata.SignLock; import org.bukkit.Material; import org.bukkit.Tag; import org.bukkit.block.Block; @@ -12,14 +13,15 @@ import org.bukkit.block.Container; import org.bukkit.block.Sign; import org.bukkit.block.data.Bisected; -import org.bukkit.block.data.BlockData; import org.bukkit.block.data.Directional; import org.bukkit.block.data.type.Chest; -import org.bukkit.block.data.type.Door; +import org.bukkit.inventory.BlockInventoryHolder; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import java.util.*; +import java.util.Map; +import java.util.Set; +import java.util.UUID; /** * @@ -28,145 +30,6 @@ public class PadlockAPI { public final static Set cardinalFaces = Set.of(BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST); public final static Set allFaces = Set.of(BlockFace.NORTH, BlockFace.EAST, BlockFace.SOUTH, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN); - /** - * set a sign - legacy additional at best - invalid. the plugin will ignore it in the future. - */ - public static void setInvalid(@NotNull Sign sign) { - SignLock.setInvalid(sign); - } - - /** - * returns lock sign of a block, sets all additional signs invalid - */ - @Deprecated(forRemoval = true) - public static @Nullable Sign updateLegacySign(final @NotNull Sign signToUpdate) { - Block attachedTo = getAttachedBlock(signToUpdate.getBlock()); - - if (attachedTo != null) { - BlockData data = attachedTo.getBlockData(); - - if (data instanceof Door) { // in ancient Lockette times, only doors did have special treatment like this - return updateLagacyDoorSign(signToUpdate, attachedTo); - } else if (data instanceof Chest) { - Sign temp = getLockChest(attachedTo); - - if (temp != null) { - // reuse old instance to not screw with expectations about this sign. Changing the PersistentDataConatiner - // on one instance doesn't change it on the other. - final @NotNull Sign lockSign; - if (temp.getLocation().distanceSquared(signToUpdate.getLocation()) < 1E3) { - lockSign = signToUpdate; - } else { - lockSign = temp; - } - SignLock.updateLegacyLock(lockSign); - SignConnectedOpenable.updateLegacy(lockSign, attachedTo); // even though we now we are protecting a chest, a valid double door could still be below it - SignTimer.updateLegacyTimer(lockSign); - SignAccessType.updateLegacyType(lockSign); - SignDisplay.updateDisplay(lockSign); - - for (Sign additional : getAdditionalSignsChest(attachedTo)) { - SignLock.updateSignFromAdditional(lockSign, additional); - SignTimer.updateLegacyTimerFromAdditional(lockSign, additional); - SignAccessType.updateLegacyTypeFromAdditional(lockSign, additional); - } - - return lockSign; - } else { - Padlock.getPlugin().getLogger().warning("Couldn't find a lock sign to update, but the chest at " + attachedTo.getLocation() + "is locked."); - } - } else { // we still could be part of a door. - Block blockDown = attachedTo.getRelative(BlockFace.DOWN); - if (blockDown.getBlockData() instanceof Door) { - return updateLagacyDoorSign(signToUpdate, blockDown); - } - - Block blockUp = attachedTo.getRelative(BlockFace.DOWN); - if (attachedTo.getRelative(BlockFace.UP).getBlockData() instanceof Door) { - return updateLagacyDoorSign(signToUpdate, blockUp); - } - - Sign temp = getLockSignSingleBlock(attachedTo, null); - - if (temp != null) { - // reuse old instance to not screw with expectations about this sign. Changing the PersistentDataConatiner - // on one instance doesn't change it on the other. - final @NotNull Sign lockSign; - if (temp.getLocation().distanceSquared(signToUpdate.getLocation()) < 1E3) { - lockSign = signToUpdate; - } else { - lockSign = temp; - } - - SignLock.updateLegacyLock(lockSign); - SignConnectedOpenable.updateLegacy(lockSign, attachedTo); - SignTimer.updateLegacyTimer(lockSign); - SignAccessType.updateLegacyType(lockSign); - SignDisplay.updateDisplay(lockSign); - - for (Sign additional : getAdditionalSignsSingleBlock(attachedTo, null)) { - SignLock.updateSignFromAdditional(lockSign, additional); - SignTimer.updateLegacyTimerFromAdditional(lockSign, additional); - SignAccessType.updateLegacyTypeFromAdditional(lockSign, additional); - } - - return lockSign; - } else { - Padlock.getPlugin().getLogger().warning("Couldn't find a lock sign to update, but the block at " + attachedTo.getLocation() + "is locked."); - } - } - } else { - setInvalid(signToUpdate); - } - - return null; - } - - /** - * common code, for the case, if a lock / additional sign protects a door. - * - * @param doorBlock block data of this block has to be an instance of Door - * @return lock sign of a block, sets all additional signs invalid - */ - @Deprecated(forRemoval = true) - private static @Nullable Sign updateLagacyDoorSign(final @NotNull Sign signToUpdate, final @NotNull Block doorBlock) { - DoubleBlockParts attachedDoor = Openables.getDoubleBlockParts(doorBlock); - - if (attachedDoor != null) { - Sign temp = getNearLockDoubleBlock(attachedDoor); - - if (temp != null) { - // reuse old instance to not screw with expectations about this sign. Changing the PersistentDataConatiner - // on one instance doesn't change it on the other. - final @NotNull Sign lockSign; - if (temp.getLocation().distanceSquared(signToUpdate.getLocation()) < 1E3) { - lockSign = signToUpdate; - } else { - lockSign = temp; - } - - SignLock.updateLegacyLock(lockSign); - SignConnectedOpenable.updateLegacy(lockSign, doorBlock); - SignTimer.updateLegacyTimer(lockSign); - SignAccessType.updateLegacyType(lockSign); - SignDisplay.updateDisplay(lockSign); - - for (Sign additional : getAdditionalSignsDoor(attachedDoor)) { - SignLock.updateSignFromAdditional(lockSign, additional); - SignTimer.updateLegacyTimerFromAdditional(lockSign, additional); - SignAccessType.updateLegacyTypeFromAdditional(lockSign, additional); - } - - return lockSign; - } else { - Padlock.getPlugin().getLogger().warning("Couldn't find a lock sign to update, but the door block at " + doorBlock.getLocation() + " is locked."); - } - } else { - Padlock.getPlugin().getLogger().warning("Couldn't get double block parts, but data says there should be one. Is it half? " + doorBlock.getLocation()); - } - return null; - } - /** * get the lock sign of a simple single block */ @@ -344,129 +207,6 @@ public static void setInvalid(@NotNull Sign sign) { return null; } - /** - * get legacy additional signs for a plain old single block. - * - * @param exempt marks the direction to NOT check (we now for sure there could nothing be) - */ - @Deprecated(forRemoval = true) - public static @NotNull List getAdditionalSignsSingleBlock(@NotNull Block block, @Nullable BlockFace exempt) { - List additionalSigns = new ArrayList<>(); - - for (BlockFace blockface : cardinalFaces) { - if (blockface != exempt) { - Sign sign = MiscUtils.getFacingSign(block, blockface); - - // Find additional sign? - if (sign != null && isAdditionalSign(sign)) { - additionalSigns.add(sign); - } - } // exempted blockface - } // for loop - - return additionalSigns; - } - - /** - * get legacy additional signs of doors. - * (doors where the only block supporting additional signs in a special way) - */ - @Deprecated(forRemoval = true) - private static @NotNull List getAdditionalSignsDoor(@NotNull DoubleBlockParts parts) { - List additionalSigns = new ArrayList<>(); - Map connectedParts = Openables.getConnectedBiParts(parts); - - for (BlockFace blockFace : cardinalFaces) { - DoubleBlockParts doubleBlockInDirection = connectedParts.get(blockFace); - - if (doubleBlockInDirection == null) { - //above - Sign sign = MiscUtils.getFacingSign(parts.upPart().getRelative(0, 1, 0), blockFace); - if (sign != null && isAdditionalSign(sign)) { - additionalSigns.add(sign); - } - - //up - sign = MiscUtils.getFacingSign(parts.upPart(), blockFace); - if (sign != null && isAdditionalSign(sign)) { - additionalSigns.add(sign); - } - - //down - sign = MiscUtils.getFacingSign(parts.downPart(), blockFace); - if (sign != null && isAdditionalSign(sign)) { - additionalSigns.add(sign); - } - - //below - sign = MiscUtils.getFacingSign(parts.downPart().getRelative(0, -1, 0), blockFace); - if (sign != null && isAdditionalSign(sign)) { - additionalSigns.add(sign); - } - } else { - BlockFace exempt = blockFace.getOppositeFace(); - Block above = doubleBlockInDirection.upPart().getRelative(0, 1, 0); - Block below = doubleBlockInDirection.downPart().getRelative(0, -1, 0); - - for (BlockFace blockface : cardinalFaces) { - if (blockface != exempt) { - //above - Sign sign = MiscUtils.getFacingSign(above, blockface); - - if (sign != null && isAdditionalSign(sign)) { - additionalSigns.add(sign); - } - - //up - sign = MiscUtils.getFacingSign(doubleBlockInDirection.upPart(), blockface); - - if (sign != null && isAdditionalSign(sign)) { - additionalSigns.add(sign); - } - - //down - sign = MiscUtils.getFacingSign(doubleBlockInDirection.downPart(), blockface); - - if (sign != null && isAdditionalSign(sign)) { - additionalSigns.add(sign); - } - - //below - sign = MiscUtils.getFacingSign(below, blockface); - - if (sign != null && isAdditionalSign(sign)) { - additionalSigns.add(sign); - } - } // exempted blockface - } // for loop - } - } - - return additionalSigns; - } - - /** - * get legacy additional signs of doors. - */ - @Deprecated(forRemoval = true) - private static @NotNull List getAdditionalSignsChest(@NotNull Block chestBlock) { - if (chestBlock.getBlockData() instanceof Chest chest && chest.getType() != Chest.Type.SINGLE) { - List addiditionalSigns = new ArrayList<>(); - - // Check second chest sign - BlockFace chestface = getRelativeChestFace(chest); - if (chestface != null) { - addiditionalSigns.addAll(getAdditionalSignsSingleBlock(chestBlock, chestface)); - // check other half - - addiditionalSigns.addAll(getAdditionalSignsSingleBlock(chestBlock.getRelative(chestface), chestface.getOppositeFace())); - return addiditionalSigns; - } - } - - return getAdditionalSignsSingleBlock(chestBlock, null); - } - /** * get the not expired lock sign of a block, might be null if no where found. */ @@ -600,24 +340,54 @@ public static boolean isUpDownAlsoLockableBlock(@NotNull Block block) { /** * return true, if interference is forbidden, true otherwise */ - public static boolean isInterfering(@NotNull Block block, @NotNull UUID playerUUid) { - if (Padlock.getPlugin().getConfigManager().isCacheEnabled()) { - return Padlock.getPlugin().getLockCacheManager().getProtectedFromCache(block.getLocation()).isLock(); + public static boolean isInterfering(final @NotNull Block block, final @NotNull UUID playerUUid) { // todo I'm sure this can get optimized in some way + // don't allow a block to get locked, by a lock on another block, if the placing player is not an owner + if (isLockable(block)) { + Sign lock = getLock(block, true); + + if (lock != null && !SignLock.isOwner(lock, playerUUid)) { + return true; + } } - Sign lock = getLock(block, true); + if (Padlock.getPlugin().getConfigManager().isInterferePlacementBlocked()) { + // block placing of blocks that can interact with the inventory of another locked block + switch (block.getType()) { + case HOPPER, DISPENSER, DROPPER, CRAFTER -> { + for (BlockFace blockface : allFaces) { + Block newblock = block.getRelative(blockface); + + if (newblock.getState() instanceof BlockInventoryHolder) { + if (!isOwner(newblock, playerUUid)) { + return true; + } + } + } + } + } - if (lock != null && !SignLock.isOwner(lock, playerUUid)) { - return true; - } else if (block.getState() instanceof Container && Padlock.getPlugin().getConfigManager().isInterferePlacementBlocked()) { // container need additional space because of hopper / minecarts - for (BlockFace blockface : allFaces) { - lock = getLock(block.getRelative(blockface), false); - if (lock != null && !SignLock.isOwner(lock, playerUUid)) { - return true; + // block placing of blocks, that can interacted with by another locked blocks + if (block.getBlockData() instanceof Container) { + for (BlockFace blockface : allFaces) { + Block newblock = block.getRelative(blockface); + + switch (newblock.getType()) { + case HOPPER, DISPENSER, DROPPER, CRAFTER -> { + if (!isOwner(newblock, playerUUid)) { + return true; + } + } + } } } - } + // don't allow blocking chests if the player is not the owner + if (block.getType().isOccluding()) { + Block below = block.getRelative(BlockFace.DOWN); + + return below.getBlockData() instanceof Chest && !isOwner(below, playerUUid); + } + } return false; } @@ -643,14 +413,6 @@ public static boolean isLockSign(@NotNull Sign sign) { return SignLock.isLockSign(sign); } - /** - * Check if a sign is an additional sign - */ - @Deprecated(forRemoval = true) - public static boolean isAdditionalSign(@NotNull Sign sign) { - return SignLock.isAdditionalSign(sign); - } - /** * check if a lock is expired */ diff --git a/src/main/java/de/greensurvivors/padlock/command/AddMember.java b/src/main/java/de/greensurvivors/padlock/command/AddMember.java index 5511b33..84220c3 100644 --- a/src/main/java/de/greensurvivors/padlock/command/AddMember.java +++ b/src/main/java/de/greensurvivors/padlock/command/AddMember.java @@ -1,8 +1,8 @@ package de.greensurvivors.padlock.command; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; +import de.greensurvivors.padlock.language.LangPath; import net.kyori.adventure.text.Component; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -33,7 +33,7 @@ protected boolean checkPermission(@NotNull Permissible permissible) { @Override protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_ADD_MEMBER); + return plugin.getMessageManager().getLang(LangPath.HELP_ADD_MEMBER); } /** diff --git a/src/main/java/de/greensurvivors/padlock/command/AddOwner.java b/src/main/java/de/greensurvivors/padlock/command/AddOwner.java index 8ba8061..3665c64 100644 --- a/src/main/java/de/greensurvivors/padlock/command/AddOwner.java +++ b/src/main/java/de/greensurvivors/padlock/command/AddOwner.java @@ -1,8 +1,8 @@ package de.greensurvivors.padlock.command; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; +import de.greensurvivors.padlock.language.LangPath; import net.kyori.adventure.text.Component; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -33,7 +33,7 @@ protected boolean checkPermission(@NotNull Permissible permissible) { @Override protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_ADD_OWNER); + return plugin.getMessageManager().getLang(LangPath.HELP_ADD_OWNER); } /** diff --git a/src/main/java/de/greensurvivors/padlock/command/ApplyPassword.java b/src/main/java/de/greensurvivors/padlock/command/ApplyPassword.java index c50d860..4e21790 100644 --- a/src/main/java/de/greensurvivors/padlock/command/ApplyPassword.java +++ b/src/main/java/de/greensurvivors/padlock/command/ApplyPassword.java @@ -2,10 +2,10 @@ import de.greensurvivors.padlock.Padlock; import de.greensurvivors.padlock.PadlockAPI; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; import de.greensurvivors.padlock.impl.SignSelection; import de.greensurvivors.padlock.impl.signdata.SignPasswords; +import de.greensurvivors.padlock.language.LangPath; import net.kyori.adventure.text.Component; import org.bukkit.block.Sign; import org.bukkit.command.Command; @@ -58,28 +58,21 @@ public static void onExternalCommand(char @NotNull [] password, @NotNull Player Sign sign = SignSelection.getSelectedSign(player); if (sign != null) { - //check for old Lockett(Pro) signs and try to update them - sign = MainCommand.checkAndUpdateLegacySign(sign, player); - if (sign == null) { - Padlock.getPlugin().getMessageManager().sendLang(player, MessageManager.LangPath.SIGN_NEED_RESELECT); - return; - } - if (PadlockAPI.isLockSign(sign)) { if (!SignPasswords.isOnCooldown(player.getUniqueId(), sign.getLocation())) { // this will communicate if access was granted or not SignPasswords.checkPasswordAndGrandAccess(sign, player, password); } else { - Padlock.getPlugin().getMessageManager().sendLang(player, MessageManager.LangPath.PASSWORD_ON_COOLDOWN); + Padlock.getPlugin().getMessageManager().sendLang(player, LangPath.PASSWORD_ON_COOLDOWN); } } else { - Padlock.getPlugin().getMessageManager().sendLang(player, MessageManager.LangPath.SIGN_NEED_RESELECT); + Padlock.getPlugin().getMessageManager().sendLang(player, LangPath.SIGN_NEED_RESELECT); } } else { - Padlock.getPlugin().getMessageManager().sendLang(player, MessageManager.LangPath.SIGN_NOT_SELECTED); + Padlock.getPlugin().getMessageManager().sendLang(player, LangPath.SIGN_NOT_SELECTED); } } else { - Padlock.getPlugin().getMessageManager().sendLang(player, MessageManager.LangPath.NO_PERMISSION); + Padlock.getPlugin().getMessageManager().sendLang(player, LangPath.NO_PERMISSION); } } @@ -95,16 +88,16 @@ protected boolean checkPermission(@NotNull Permissible permissible) { @Override protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_PASSWORD); + return plugin.getMessageManager().getLang(LangPath.HELP_PASSWORD); } @Override protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] args) { if (sender instanceof Player player) { - plugin.getMessageManager().sendLang(player, MessageManager.LangPath.PASSWORD_START_PROCESSING); + plugin.getMessageManager().sendLang(player, LangPath.PASSWORD_START_PROCESSING); return true; } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_A_PLAYER); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_A_PLAYER); return false; } } @@ -115,17 +108,17 @@ protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] arg } @Override - public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + public @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String @NotNull [] args) { return onTabComplete(sender, args); } @Override - public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { + public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String @NotNull [] args) { if (sender instanceof Player player) { - plugin.getMessageManager().sendLang(player, MessageManager.LangPath.PASSWORD_START_PROCESSING); + plugin.getMessageManager().sendLang(player, LangPath.PASSWORD_START_PROCESSING); return true; } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_A_PLAYER); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_A_PLAYER); return false; } } diff --git a/src/main/java/de/greensurvivors/padlock/command/Debug.java b/src/main/java/de/greensurvivors/padlock/command/Debug.java index 2091ca0..7fe17c6 100644 --- a/src/main/java/de/greensurvivors/padlock/command/Debug.java +++ b/src/main/java/de/greensurvivors/padlock/command/Debug.java @@ -1,8 +1,8 @@ package de.greensurvivors.padlock.command; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; +import de.greensurvivors.padlock.language.LangPath; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; @@ -33,7 +33,7 @@ protected boolean checkPermission(@NotNull Permissible permissible) { @Override protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_DEBUG); + return plugin.getMessageManager().getLang(LangPath.HELP_DEBUG); } @Override @@ -62,7 +62,7 @@ protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] arg sender.sendMessage(" - none"); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NO_PERMISSION); + plugin.getMessageManager().sendLang(sender, LangPath.NO_PERMISSION); } return true; diff --git a/src/main/java/de/greensurvivors/padlock/command/Help.java b/src/main/java/de/greensurvivors/padlock/command/Help.java index b0c4fad..59c4113 100644 --- a/src/main/java/de/greensurvivors/padlock/command/Help.java +++ b/src/main/java/de/greensurvivors/padlock/command/Help.java @@ -1,8 +1,9 @@ package de.greensurvivors.padlock.command; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; +import de.greensurvivors.padlock.language.LangPath; +import de.greensurvivors.padlock.language.PlaceHolder; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.minimessage.MiniMessage; @@ -37,7 +38,7 @@ protected boolean checkPermission(@NotNull Permissible permissible) { @Override protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_HELP); + return plugin.getMessageManager().getLang(LangPath.HELP_HELP); } @Override @@ -48,20 +49,20 @@ protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] arg if (command != null) { TextComponent.Builder builder = Component.text(); - builder.append(plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_HEADER)); + builder.append(plugin.getMessageManager().getLang(LangPath.HELP_HEADER)); builder.append(Component.newline()); builder.append(command.getHelpText()); sender.sendMessage(builder); } else { // didn't type a valid subcommand. - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.CMD_NOT_A_SUBCOMMAND, - Placeholder.unparsed(MessageManager.PlaceHolder.ARGUMENT.getPlaceholder(), args[1])); + plugin.getMessageManager().sendLang(sender, LangPath.CMD_NOT_A_SUBCOMMAND, + Placeholder.unparsed(PlaceHolder.ARGUMENT.getPlaceholder(), args[1])); return false; } } else { //todo maybe pages - Component component = plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_HEADER) + Component component = plugin.getMessageManager().getLang(LangPath.HELP_HEADER) .append(Component.newline()) - .append(plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_DESCRIPTION) + .append(plugin.getMessageManager().getLang(LangPath.HELP_DESCRIPTION) .append(Component.newline())); // list all subcommands alias per line component = component.append(MiniMessage.miniMessage().deserialize( diff --git a/src/main/java/de/greensurvivors/padlock/command/Info.java b/src/main/java/de/greensurvivors/padlock/command/Info.java index 0d12684..2c5327c 100644 --- a/src/main/java/de/greensurvivors/padlock/command/Info.java +++ b/src/main/java/de/greensurvivors/padlock/command/Info.java @@ -1,7 +1,6 @@ package de.greensurvivors.padlock.command; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; import de.greensurvivors.padlock.impl.MiscUtils; import de.greensurvivors.padlock.impl.SignSelection; @@ -9,6 +8,7 @@ import de.greensurvivors.padlock.impl.signdata.SignExpiration; import de.greensurvivors.padlock.impl.signdata.SignLock; import de.greensurvivors.padlock.impl.signdata.SignTimer; +import de.greensurvivors.padlock.language.LangPath; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; import org.bukkit.Bukkit; @@ -65,7 +65,7 @@ protected boolean checkPermission(@NotNull Permissible permissible) { @Override protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_INFO); + return plugin.getMessageManager().getLang(LangPath.HELP_INFO); } @Override @@ -74,13 +74,6 @@ protected boolean checkPermission(@NotNull Permissible permissible) { if (sender instanceof Player player) { Sign sign = SignSelection.getSelectedSign(player); if (sign != null) { - //check for old Lockett(Pro) signs and try to update them - sign = MainCommand.checkAndUpdateLegacySign(sign, player); - if (sign == null) { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NEED_RESELECT); - return true; - } - // only admins, owners and members if (player.hasPermission(PermissionManager.ADMIN_USE.getPerm()) || SignLock.isOwner(sign, player.getUniqueId()) || @@ -88,9 +81,9 @@ protected boolean checkPermission(@NotNull Permissible permissible) { // owners TextComponent.Builder builder = Component.text(); - builder.append(plugin.getMessageManager().getLang(MessageManager.LangPath.INFO_HEAD)); + builder.append(plugin.getMessageManager().getLang(LangPath.INFO_HEAD)); builder.append(Component.newline()); - builder.append(plugin.getMessageManager().getLang(MessageManager.LangPath.INFO_OWNERS).appendSpace()); + builder.append(plugin.getMessageManager().getLang(LangPath.INFO_OWNERS).appendSpace()); for (String name : getNamesFromUUIDStrSet(SignLock.getUUIDs(sign, true, false))) { builder.append(Component.text(name)); builder.append(Component.text(", ")); @@ -98,7 +91,7 @@ protected boolean checkPermission(@NotNull Permissible permissible) { // members builder.append(Component.newline()); - builder.append(plugin.getMessageManager().getLang(MessageManager.LangPath.INFO_MEMBERS)).appendSpace(); + builder.append(plugin.getMessageManager().getLang(LangPath.INFO_MEMBERS)).appendSpace(); if (SignAccessType.getAccessType(sign, false) != SignAccessType.AccessType.PUBLIC) { for (String name : getNamesFromUUIDStrSet(SignLock.getUUIDs(sign, false, false))) { builder.append(Component.text(name)); @@ -108,50 +101,49 @@ protected boolean checkPermission(@NotNull Permissible permissible) { // access type builder.append(Component.newline()); - builder.append(plugin.getMessageManager().getLang(MessageManager.LangPath.INFO_ACCESS_TYPE)).appendSpace(); + builder.append(plugin.getMessageManager().getLang(LangPath.INFO_ACCESS_TYPE)).appendSpace(); switch (SignAccessType.getAccessType(sign, false)) { case PRIVATE -> - builder.append(Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SIGN_LINE_PRIVATE)); + builder.append(Padlock.getPlugin().getMessageManager().getLang(LangPath.SIGN_LINE_PRIVATE)); case PUBLIC -> - builder.append(Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SIGN_LINE_PUBLIC)); + builder.append(Padlock.getPlugin().getMessageManager().getLang(LangPath.SIGN_LINE_PUBLIC)); case DONATION -> - builder.append(Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SIGN_LINE_DONATION)); + builder.append(Padlock.getPlugin().getMessageManager().getLang(LangPath.SIGN_LINE_DONATION)); case DISPLAY -> - builder.append(Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SIGN_LINE_DISPLAY)); + builder.append(Padlock.getPlugin().getMessageManager().getLang(LangPath.SIGN_LINE_DISPLAY)); case SUPPLY -> - builder.append(Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SIGN_LINE_SUPPLY_SIGN)); - /*case null, // todo next java version*/ - default -> - builder.append(Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SIGN_LINE_ERROR)); + builder.append(Padlock.getPlugin().getMessageManager().getLang(LangPath.SIGN_LINE_SUPPLY_SIGN)); + case null, default -> + builder.append(Padlock.getPlugin().getMessageManager().getLang(LangPath.SIGN_LINE_ERROR)); } // timer - Long timer = SignTimer.getTimer(sign, false); + Duration timer = SignTimer.getTimer(sign, false); if (timer != null) { builder.append(Component.newline()); - builder.append(plugin.getMessageManager().getLang(MessageManager.LangPath.INFO_TIMER)).appendSpace(); - builder.append(Component.text(MiscUtils.formatTimeString(Duration.ofMillis(timer)))); + builder.append(plugin.getMessageManager().getLang(LangPath.INFO_TIMER)).appendSpace(); + builder.append(Component.text(MiscUtils.formatTimeString(timer))); } // expiration builder.append(Component.newline()); - builder.append(plugin.getMessageManager().getLang(MessageManager.LangPath.INFO_EXPIRED)).appendSpace(); + builder.append(plugin.getMessageManager().getLang(LangPath.INFO_EXPIRED)).appendSpace(); builder.append(Component.text(SignExpiration.isSignExpired(sign))); sender.sendMessage(builder.asComponent()); } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NO_PERMISSION); + plugin.getMessageManager().sendLang(sender, LangPath.NO_PERMISSION); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NOT_SELECTED); + plugin.getMessageManager().sendLang(sender, LangPath.SIGN_NOT_SELECTED); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_A_PLAYER); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_A_PLAYER); return false; } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NO_PERMISSION); + plugin.getMessageManager().sendLang(sender, LangPath.NO_PERMISSION); } return true; diff --git a/src/main/java/de/greensurvivors/padlock/command/MainCommand.java b/src/main/java/de/greensurvivors/padlock/command/MainCommand.java index 8b82b6c..df4dd31 100644 --- a/src/main/java/de/greensurvivors/padlock/command/MainCommand.java +++ b/src/main/java/de/greensurvivors/padlock/command/MainCommand.java @@ -2,12 +2,12 @@ import de.greensurvivors.padlock.Padlock; import de.greensurvivors.padlock.PadlockAPI; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; import de.greensurvivors.padlock.impl.MiscUtils; import de.greensurvivors.padlock.impl.SignSelection; import de.greensurvivors.padlock.impl.signdata.SignLock; -import net.kyori.adventure.audience.Audience; +import de.greensurvivors.padlock.language.LangPath; +import de.greensurvivors.padlock.language.PlaceHolder; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; import org.apache.commons.collections4.set.ListOrderedSet; @@ -55,7 +55,6 @@ public MainCommand(@NotNull Padlock plugin) { SUBCOMMANDS.add(new AddOwner(plugin)); SUBCOMMANDS.add(new RemoveOwner(plugin)); SUBCOMMANDS.add(new UpdateDisplay(plugin)); - SUBCOMMANDS.add(new UpdateLegacy(plugin)); SUBCOMMANDS.add(new Version(plugin)); SUBCOMMANDS.add(new Debug(plugin)); SUBCOMMANDS.add(new Reload(plugin)); @@ -119,30 +118,6 @@ protected static Set getSubCommands(@NotNull Permissible permissible return SUBCOMMANDS.stream().filter(subCommand -> subCommand.checkPermission(permissible)).collect(Collectors.toSet()); } - /** - * Checks if a sign is a legacy or an additional sign and starts the update process. - * - * @return the main lock sign if found or null else - */ - @Deprecated(forRemoval = true) - protected static @Nullable Sign checkAndUpdateLegacySign(@NotNull Sign sign, @NotNull Audience audience) { - //check for old Lockett(Pro) signs and try to update them - if (PadlockAPI.isAdditionalSign(sign) || SignLock.isLegacySign(sign)) { - Sign otherSign = PadlockAPI.updateLegacySign(sign); //get main sign - - if (otherSign == null) { // couldn't find the main sign of the block. - //the calling function will return feedback to the player, since this may also get called on tabCompletable - PadlockAPI.setInvalid(sign); - return null; - } else { - plugin.getMessageManager().sendLang(audience, MessageManager.LangPath.UPDATE_LEGACY_SUCCESS); - return otherSign; - } - } - - return sign; - } - /** * Since removing a member or an owner share most of their code, * Both of it gets dealt here in a common place instead of in the subcommands @@ -165,12 +140,6 @@ protected static Set getSubCommands(@NotNull Permissible permissible Sign sign = SignSelection.getSelectedSign(player); if (sign != null) { - //check for old Lockett(Pro) signs and try to update them - sign = checkAndUpdateLegacySign(sign, player); - if (sign == null) { - return null; - } - if (PadlockAPI.isLockSign(sign)) { // check sign or admin permission, since only admins can mess with owners if (sender.hasPermission(PermissionManager.ADMIN_EDIT.getPerm()) || // /lock removeowner @@ -224,13 +193,6 @@ protected static boolean onAddPlayer(@NotNull CommandSender sender, final @NotNu Sign sign = SignSelection.getSelectedSign(player); if (sign != null) { - //check for old Lockett(Pro) signs and try to update them - sign = checkAndUpdateLegacySign(sign, player); - if (sign == null) { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NEED_RESELECT); - return true; - } - if (PadlockAPI.isLockSign(sign)) { // check sign or admin permission, since only admins can mess with owners if (player.hasPermission(PermissionManager.ADMIN_EDIT.getPerm()) || // /lock addowner @@ -242,38 +204,38 @@ protected static boolean onAddPlayer(@NotNull CommandSender sender, final @NotNu //success! SignLock.addPlayer(sign, addOwner, offlinePlayer); - TagResolver tagResolver = Placeholder.unparsed(MessageManager.PlaceHolder.PLAYER.getPlaceholder(), + TagResolver tagResolver = Placeholder.unparsed(PlaceHolder.PLAYER.getPlaceholder(), offlinePlayer.getName() == null ? offlinePlayer.getUniqueId().toString() : offlinePlayer.getName()); // tell the player if (addOwner) { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.ADD_OWNER_SUCCESS, tagResolver); + plugin.getMessageManager().sendLang(sender, LangPath.ADD_OWNER_SUCCESS, tagResolver); } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.ADD_MEMBER_SUCCESS, tagResolver); + plugin.getMessageManager().sendLang(sender, LangPath.ADD_MEMBER_SUCCESS, tagResolver); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.UNKNOWN_PLAYER, - Placeholder.unparsed(MessageManager.PlaceHolder.PLAYER.getPlaceholder(), args[1])); + plugin.getMessageManager().sendLang(sender, LangPath.UNKNOWN_PLAYER, + Placeholder.unparsed(PlaceHolder.PLAYER.getPlaceholder(), args[1])); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NO_PERMISSION); + plugin.getMessageManager().sendLang(sender, LangPath.NO_PERMISSION); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NEED_RESELECT); + plugin.getMessageManager().sendLang(sender, LangPath.SIGN_NEED_RESELECT); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NOT_SELECTED); + plugin.getMessageManager().sendLang(sender, LangPath.SIGN_NOT_SELECTED); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_ENOUGH_ARGS); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_ENOUGH_ARGS); return false; } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NO_PERMISSION); + plugin.getMessageManager().sendLang(sender, LangPath.NO_PERMISSION); } return true; } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_A_PLAYER); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_A_PLAYER); return false; } } @@ -302,13 +264,6 @@ protected static boolean onRemovePlayer(@NotNull CommandSender sender, final @No Sign sign = SignSelection.getSelectedSign(player); if (sign != null) { - //check for old Lockett(Pro) signs and try to update them - sign = checkAndUpdateLegacySign(sign, player); - if (sign == null) { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NEED_RESELECT); - return true; - } - if (PadlockAPI.isLockSign(sign)) { // check sign or admin permission, since only admins can mess with owners if (player.hasPermission(PermissionManager.ADMIN_EDIT.getPerm()) || // /lock removeowner @@ -318,48 +273,48 @@ protected static boolean onRemovePlayer(@NotNull CommandSender sender, final @No OfflinePlayer offlinePlayer = getPlayerFromArgument(args[1]); if (offlinePlayer != null) { //prepare resolber - TagResolver tagResolver = Placeholder.unparsed(MessageManager.PlaceHolder.PLAYER.getPlaceholder(), + TagResolver tagResolver = Placeholder.unparsed(PlaceHolder.PLAYER.getPlaceholder(), offlinePlayer.getName() == null ? offlinePlayer.getUniqueId().toString() : offlinePlayer.getName()); // try to remove the member/owner, may fail if the player is not a member/owner if (SignLock.removePlayer(sign, removeOwner, offlinePlayer.getUniqueId())) { //success if (removeOwner) { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.REMOVE_OWNER_SUCCESS, tagResolver); + plugin.getMessageManager().sendLang(sender, LangPath.REMOVE_OWNER_SUCCESS, tagResolver); } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.REMOVE_MEMBER_SUCCESS, tagResolver); + plugin.getMessageManager().sendLang(sender, LangPath.REMOVE_MEMBER_SUCCESS, tagResolver); } } else { if (removeOwner) { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.REMOVE_OWNER_ERROR, tagResolver); + plugin.getMessageManager().sendLang(sender, LangPath.REMOVE_OWNER_ERROR, tagResolver); } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.REMOVE_MEMBER_ERROR, tagResolver); + plugin.getMessageManager().sendLang(sender, LangPath.REMOVE_MEMBER_ERROR, tagResolver); } } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.UNKNOWN_PLAYER, - Placeholder.unparsed(MessageManager.PlaceHolder.PLAYER.getPlaceholder(), args[1])); + plugin.getMessageManager().sendLang(sender, LangPath.UNKNOWN_PLAYER, + Placeholder.unparsed(PlaceHolder.PLAYER.getPlaceholder(), args[1])); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NO_PERMISSION); + plugin.getMessageManager().sendLang(sender, LangPath.NO_PERMISSION); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NEED_RESELECT); + plugin.getMessageManager().sendLang(sender, LangPath.SIGN_NEED_RESELECT); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NOT_SELECTED); + plugin.getMessageManager().sendLang(sender, LangPath.SIGN_NOT_SELECTED); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_ENOUGH_ARGS); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_ENOUGH_ARGS); return false; } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NO_PERMISSION); + plugin.getMessageManager().sendLang(sender, LangPath.NO_PERMISSION); } return true; } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_A_PLAYER); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_A_PLAYER); return false; } } @@ -381,7 +336,7 @@ protected static boolean onRemovePlayer(@NotNull CommandSender sender, final @No * to default to the command executor */ @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull org.bukkit.command.Command command, @NotNull String label, @NotNull String[] args) { + public List onTabComplete(@NotNull CommandSender sender, @NotNull org.bukkit.command.Command command, @NotNull String label, @NotNull String @NotNull [] args) { List suggestionList = null; if (args.length == 1) { @@ -433,7 +388,7 @@ public List onTabComplete(@NotNull CommandSender sender, @NotNull org.bu */ public boolean onCommand(@NotNull CommandSender sender, @NotNull org.bukkit.command.Command command, @NotNull String commandLabel, final String[] args) { if (args.length == 0) { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.CMD_USAGE); + plugin.getMessageManager().sendLang(sender, LangPath.CMD_USAGE); return true; } else { SubCommand subCommand = getSubCommandFromString(sender, args[0]); @@ -446,7 +401,7 @@ public boolean onCommand(@NotNull CommandSender sender, @NotNull org.bukkit.comm return true; } - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.CMD_USAGE); + plugin.getMessageManager().sendLang(sender, LangPath.CMD_USAGE); return false; } } diff --git a/src/main/java/de/greensurvivors/padlock/command/Reload.java b/src/main/java/de/greensurvivors/padlock/command/Reload.java index 6c06e58..3134a95 100644 --- a/src/main/java/de/greensurvivors/padlock/command/Reload.java +++ b/src/main/java/de/greensurvivors/padlock/command/Reload.java @@ -1,8 +1,8 @@ package de.greensurvivors.padlock.command; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; +import de.greensurvivors.padlock.language.LangPath; import net.kyori.adventure.text.Component; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permissible; @@ -32,7 +32,7 @@ protected boolean checkPermission(@NotNull Permissible permissible) { @Override protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_RELOAD); + return plugin.getMessageManager().getLang(LangPath.HELP_RELOAD); } @Override @@ -40,9 +40,9 @@ protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] arg if (this.checkPermission(sender)) { plugin.getConfigManager().reload(); - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.RELOAD_SUCCESS); + plugin.getMessageManager().sendLang(sender, LangPath.RELOAD_SUCCESS); } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NO_PERMISSION); + plugin.getMessageManager().sendLang(sender, LangPath.NO_PERMISSION); } return true; diff --git a/src/main/java/de/greensurvivors/padlock/command/RemoveMember.java b/src/main/java/de/greensurvivors/padlock/command/RemoveMember.java index 747df90..5bdefa0 100644 --- a/src/main/java/de/greensurvivors/padlock/command/RemoveMember.java +++ b/src/main/java/de/greensurvivors/padlock/command/RemoveMember.java @@ -1,8 +1,8 @@ package de.greensurvivors.padlock.command; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; +import de.greensurvivors.padlock.language.LangPath; import net.kyori.adventure.text.Component; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permissible; @@ -32,7 +32,7 @@ protected boolean checkPermission(@NotNull Permissible permissible) { @Override protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_REMOVE_MEMBER); + return plugin.getMessageManager().getLang(LangPath.HELP_REMOVE_MEMBER); } /** diff --git a/src/main/java/de/greensurvivors/padlock/command/RemoveOwner.java b/src/main/java/de/greensurvivors/padlock/command/RemoveOwner.java index d6d1349..6726276 100644 --- a/src/main/java/de/greensurvivors/padlock/command/RemoveOwner.java +++ b/src/main/java/de/greensurvivors/padlock/command/RemoveOwner.java @@ -1,8 +1,8 @@ package de.greensurvivors.padlock.command; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; +import de.greensurvivors.padlock.language.LangPath; import net.kyori.adventure.text.Component; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permissible; @@ -32,7 +32,7 @@ protected boolean checkPermission(@NotNull Permissible permissible) { @Override protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_REMOVE_OWNER); + return plugin.getMessageManager().getLang(LangPath.HELP_REMOVE_OWNER); } /** diff --git a/src/main/java/de/greensurvivors/padlock/command/SetAccessType.java b/src/main/java/de/greensurvivors/padlock/command/SetAccessType.java index b6fcda0..049254a 100644 --- a/src/main/java/de/greensurvivors/padlock/command/SetAccessType.java +++ b/src/main/java/de/greensurvivors/padlock/command/SetAccessType.java @@ -1,11 +1,13 @@ package de.greensurvivors.padlock.command; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; import de.greensurvivors.padlock.impl.SignSelection; import de.greensurvivors.padlock.impl.signdata.SignAccessType; import de.greensurvivors.padlock.impl.signdata.SignLock; +import de.greensurvivors.padlock.language.LangPath; +import de.greensurvivors.padlock.language.MessageManager; +import de.greensurvivors.padlock.language.PlaceHolder; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import org.bukkit.block.Sign; @@ -24,15 +26,15 @@ protected SetAccessType(@NotNull Padlock plugin) { super(plugin); MessageManager manager = Padlock.getPlugin().getMessageManager(); - accessTypeStrs.put(manager.getNakedSignText(MessageManager.LangPath.SIGN_LINE_PRIVATE).toLowerCase(). + accessTypeStrs.put(manager.getNakedSignText(LangPath.SIGN_LINE_PRIVATE).toLowerCase(). replace("[", "").replace("]", "").trim(), SignAccessType.AccessType.PRIVATE); - accessTypeStrs.put(manager.getNakedSignText(MessageManager.LangPath.SIGN_LINE_PUBLIC).toLowerCase(). + accessTypeStrs.put(manager.getNakedSignText(LangPath.SIGN_LINE_PUBLIC).toLowerCase(). replace("[", "").replace("]", "").trim(), SignAccessType.AccessType.PUBLIC); - accessTypeStrs.put(manager.getNakedSignText(MessageManager.LangPath.SIGN_LINE_DONATION).toLowerCase(). + accessTypeStrs.put(manager.getNakedSignText(LangPath.SIGN_LINE_DONATION).toLowerCase(). replace("[", "").replace("]", "").trim(), SignAccessType.AccessType.DONATION); - accessTypeStrs.put(manager.getNakedSignText(MessageManager.LangPath.SIGN_LINE_DISPLAY).toLowerCase(). + accessTypeStrs.put(manager.getNakedSignText(LangPath.SIGN_LINE_DISPLAY).toLowerCase(). replace("[", "").replace("]", "").trim(), SignAccessType.AccessType.DISPLAY); - accessTypeStrs.put(manager.getNakedSignText(MessageManager.LangPath.SIGN_LINE_SUPPLY_SIGN).toLowerCase(). + accessTypeStrs.put(manager.getNakedSignText(LangPath.SIGN_LINE_SUPPLY_SIGN).toLowerCase(). replace("[", "").replace("]", "").trim(), SignAccessType.AccessType.SUPPLY); } @@ -48,7 +50,7 @@ protected boolean checkPermission(@NotNull Permissible permissible) { @Override protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_SET_ACCESS_TYPE); + return plugin.getMessageManager().getLang(LangPath.HELP_SET_ACCESS_TYPE); } @Override @@ -59,13 +61,6 @@ protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] arg Sign sign = SignSelection.getSelectedSign(player); if (sign != null) { - //check for old Lockett(Pro) signs and try to update them - sign = MainCommand.checkAndUpdateLegacySign(sign, player); - if (sign == null) { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NEED_RESELECT); - return true; - } - // only admins and owners can change a signs properties if (SignLock.isOwner(sign, player.getUniqueId()) || player.hasPermission(PermissionManager.ADMIN_EDIT.getPerm())) { @@ -75,29 +70,29 @@ protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] arg if (accessType != null) { // success! SignAccessType.setAccessType(sign, accessType, true); - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SET_ACCESS_TYPE_SUCCESS, - Placeholder.component(MessageManager.PlaceHolder.ARGUMENT.getPlaceholder(), Component.text(accessType.name().toLowerCase(Locale.ENGLISH)))); + plugin.getMessageManager().sendLang(sender, LangPath.SET_ACCESS_TYPE_SUCCESS, + Placeholder.component(PlaceHolder.ARGUMENT.getPlaceholder(), Component.text(accessType.name().toLowerCase(Locale.ENGLISH)))); } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_ACCESS_TYPE, - Placeholder.unparsed(MessageManager.PlaceHolder.ARGUMENT.getPlaceholder(), args[1])); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_ACCESS_TYPE, + Placeholder.unparsed(PlaceHolder.ARGUMENT.getPlaceholder(), args[1])); return false; } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_OWNER); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_OWNER); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NOT_SELECTED); + plugin.getMessageManager().sendLang(sender, LangPath.SIGN_NOT_SELECTED); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_ENOUGH_ARGS); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_ENOUGH_ARGS); return false; } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_A_PLAYER); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_A_PLAYER); return false; } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NO_PERMISSION); + plugin.getMessageManager().sendLang(sender, LangPath.NO_PERMISSION); } return true; diff --git a/src/main/java/de/greensurvivors/padlock/command/SetConnected.java b/src/main/java/de/greensurvivors/padlock/command/SetConnected.java index 70b1c7c..a70d6b5 100644 --- a/src/main/java/de/greensurvivors/padlock/command/SetConnected.java +++ b/src/main/java/de/greensurvivors/padlock/command/SetConnected.java @@ -1,11 +1,12 @@ package de.greensurvivors.padlock.command; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; import de.greensurvivors.padlock.impl.SignSelection; import de.greensurvivors.padlock.impl.signdata.SignConnectedOpenable; import de.greensurvivors.padlock.impl.signdata.SignLock; +import de.greensurvivors.padlock.language.LangPath; +import de.greensurvivors.padlock.language.PlaceHolder; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import org.apache.commons.lang3.BooleanUtils; @@ -37,7 +38,7 @@ protected boolean checkPermission(@NotNull Permissible permissible) { @Override protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_SET_CONNECTED); + return plugin.getMessageManager().getLang(LangPath.HELP_SET_CONNECTED); } @Override @@ -48,13 +49,6 @@ protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] arg Sign sign = SignSelection.getSelectedSign(player); if (sign != null) { - //check for old Lockett(Pro) signs and try to update them - sign = MainCommand.checkAndUpdateLegacySign(sign, player); - if (sign == null) { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NEED_RESELECT); - return true; - } - // only admins and owners can change a signs properties if (SignLock.isOwner(sign, player.getUniqueId()) || player.hasPermission(PermissionManager.ADMIN_EDIT.getPerm())) { @@ -65,29 +59,29 @@ protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] arg if (shouldConnected != null) { // success! SignConnectedOpenable.setConnected(sign, shouldConnected); - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SET_CONNECTED_SUCCESS, - Placeholder.component(MessageManager.PlaceHolder.ARGUMENT.getPlaceholder(), Component.text(shouldConnected))); + plugin.getMessageManager().sendLang(sender, LangPath.SET_CONNECTED_SUCCESS, + Placeholder.component(PlaceHolder.ARGUMENT.getPlaceholder(), Component.text(shouldConnected))); } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_A_BOOL, - Placeholder.unparsed(MessageManager.PlaceHolder.ARGUMENT.getPlaceholder(), args[1])); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_A_BOOL, + Placeholder.unparsed(PlaceHolder.ARGUMENT.getPlaceholder(), args[1])); return false; } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_OWNER); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_OWNER); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NOT_SELECTED); + plugin.getMessageManager().sendLang(sender, LangPath.SIGN_NOT_SELECTED); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_ENOUGH_ARGS); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_ENOUGH_ARGS); return false; } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_A_PLAYER); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_A_PLAYER); return false; } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NO_PERMISSION); + plugin.getMessageManager().sendLang(sender, LangPath.NO_PERMISSION); } return true; diff --git a/src/main/java/de/greensurvivors/padlock/command/SetPassword.java b/src/main/java/de/greensurvivors/padlock/command/SetPassword.java index e15b645..fecb6aa 100644 --- a/src/main/java/de/greensurvivors/padlock/command/SetPassword.java +++ b/src/main/java/de/greensurvivors/padlock/command/SetPassword.java @@ -2,11 +2,11 @@ import de.greensurvivors.padlock.Padlock; import de.greensurvivors.padlock.PadlockAPI; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; import de.greensurvivors.padlock.impl.SignSelection; import de.greensurvivors.padlock.impl.signdata.SignLock; import de.greensurvivors.padlock.impl.signdata.SignPasswords; +import de.greensurvivors.padlock.language.LangPath; import net.kyori.adventure.text.Component; import org.bukkit.block.Sign; import org.bukkit.command.CommandSender; @@ -45,29 +45,22 @@ public static void onExternalCommand(char @Nullable [] newPassword, @NotNull Pla //get and check selected sign Sign sign = SignSelection.getSelectedSign(player); if (sign != null) { - //check for old Lockett(Pro) signs and try to update them - sign = MainCommand.checkAndUpdateLegacySign(sign, player); - if (sign == null) { - Padlock.getPlugin().getMessageManager().sendLang(player, MessageManager.LangPath.SIGN_NEED_RESELECT); - return; - } - if (PadlockAPI.isLockSign(sign)) { // check sign owner, even admins can't change a password of something they don't own. if (SignLock.isOwner(sign, player.getUniqueId()) || player.hasPermission(PermissionManager.ADMIN_PASSWORD.getPerm())) { // this will communicate if password was set or removed SignPasswords.setPassword(sign, player, newPassword); } else { - Padlock.getPlugin().getMessageManager().sendLang(player, MessageManager.LangPath.NO_PERMISSION); + Padlock.getPlugin().getMessageManager().sendLang(player, LangPath.NO_PERMISSION); } } else { - Padlock.getPlugin().getMessageManager().sendLang(player, MessageManager.LangPath.SIGN_NEED_RESELECT); + Padlock.getPlugin().getMessageManager().sendLang(player, LangPath.SIGN_NEED_RESELECT); } } else { - Padlock.getPlugin().getMessageManager().sendLang(player, MessageManager.LangPath.SIGN_NOT_SELECTED); + Padlock.getPlugin().getMessageManager().sendLang(player, LangPath.SIGN_NOT_SELECTED); } } else { - Padlock.getPlugin().getMessageManager().sendLang(player, MessageManager.LangPath.NO_PERMISSION); + Padlock.getPlugin().getMessageManager().sendLang(player, LangPath.NO_PERMISSION); } // yes I know I invalidate the arrays at multiple places, but in terms of password safety it's better to be double and tripple safe then sorry. @@ -88,17 +81,17 @@ protected boolean checkPermission(@NotNull Permissible permissible) { @Override protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_SET_PASSWORD); + return plugin.getMessageManager().getLang(LangPath.HELP_SET_PASSWORD); } @Override protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] args) { if (sender instanceof Player player) { - plugin.getMessageManager().sendLang(player, MessageManager.LangPath.PASSWORD_SAFETY_WARNING); - plugin.getMessageManager().sendLang(player, MessageManager.LangPath.PASSWORD_START_PROCESSING); + plugin.getMessageManager().sendLang(player, LangPath.PASSWORD_SAFETY_WARNING); + plugin.getMessageManager().sendLang(player, LangPath.PASSWORD_START_PROCESSING); return true; } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_A_PLAYER); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_A_PLAYER); return false; } } diff --git a/src/main/java/de/greensurvivors/padlock/command/SetTimer.java b/src/main/java/de/greensurvivors/padlock/command/SetTimer.java index a2013ee..474fcea 100644 --- a/src/main/java/de/greensurvivors/padlock/command/SetTimer.java +++ b/src/main/java/de/greensurvivors/padlock/command/SetTimer.java @@ -1,12 +1,13 @@ package de.greensurvivors.padlock.command; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; import de.greensurvivors.padlock.impl.MiscUtils; import de.greensurvivors.padlock.impl.SignSelection; import de.greensurvivors.padlock.impl.signdata.SignLock; import de.greensurvivors.padlock.impl.signdata.SignTimer; +import de.greensurvivors.padlock.language.LangPath; +import de.greensurvivors.padlock.language.PlaceHolder; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import org.bukkit.block.Sign; @@ -16,6 +17,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Set; @@ -43,7 +45,7 @@ protected boolean checkPermission(@NotNull Permissible permissible) { @Override protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_SET_TIMER); + return plugin.getMessageManager().getLang(LangPath.HELP_SET_TIMER); } @Override @@ -54,13 +56,6 @@ protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] arg Sign sign = SignSelection.getSelectedSign(player); if (sign != null) { - //check for old Lockett(Pro) signs and try to update them - sign = MainCommand.checkAndUpdateLegacySign(sign, player); - if (sign == null) { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NEED_RESELECT); - return true; - } - // only owners and admins can change a signs properties if (SignLock.isOwner(sign, player.getUniqueId()) || player.hasPermission(PermissionManager.ADMIN_EDIT.getPerm())) { @@ -68,12 +63,12 @@ protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] arg // note: writing every time element in one argument, // would have the same effect as spreading them across multiple arguments. // using the same time unit more than once is permitted. - Long timerDuration = null; + Duration timerDuration = null; if (args.length == 2) { try { if (Integer.parseInt(args[1]) <= 0) { - timerDuration = -1L; + timerDuration = Duration.ofSeconds(-1); } } catch (NumberFormatException ignored) { } @@ -81,16 +76,16 @@ protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] arg if (timerDuration == null) { for (int i = 1; i < args.length; i++) { - Long period = MiscUtils.parsePeriod(args[i]); + Duration period = MiscUtils.parsePeriod(args[i]); if (period != null) { if (timerDuration == null) { - timerDuration = 0L; + timerDuration = Duration.ZERO; } - timerDuration += period; + timerDuration = timerDuration.plus(period); } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SET_TIMER_ERROR); + plugin.getMessageManager().sendLang(sender, LangPath.SET_TIMER_ERROR); return false; } } @@ -99,29 +94,29 @@ protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] arg // success SignTimer.setTimer(sign, timerDuration, true); - if (timerDuration > 0) { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SET_TIMER_SUCCESS_ON, - Placeholder.component(MessageManager.PlaceHolder.TIME.getPlaceholder(), Component.text(timerDuration))); + if (timerDuration.toMillis() > 0) { + plugin.getMessageManager().sendLang(sender, LangPath.SET_TIMER_SUCCESS_ON, + Placeholder.unparsed(PlaceHolder.TIME.getPlaceholder(), MiscUtils.formatTimeString(timerDuration))); } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SET_TIMER_SUCCESS_OFF); + plugin.getMessageManager().sendLang(sender, LangPath.SET_TIMER_SUCCESS_OFF); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_OWNER); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_OWNER); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NOT_SELECTED); + plugin.getMessageManager().sendLang(sender, LangPath.SIGN_NOT_SELECTED); } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_ENOUGH_ARGS); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_ENOUGH_ARGS); return false; } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NO_PERMISSION); + plugin.getMessageManager().sendLang(sender, LangPath.NO_PERMISSION); } return true; } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_A_PLAYER); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_A_PLAYER); return false; } } diff --git a/src/main/java/de/greensurvivors/padlock/command/UpdateDisplay.java b/src/main/java/de/greensurvivors/padlock/command/UpdateDisplay.java index f6febf1..26b9d53 100644 --- a/src/main/java/de/greensurvivors/padlock/command/UpdateDisplay.java +++ b/src/main/java/de/greensurvivors/padlock/command/UpdateDisplay.java @@ -1,11 +1,11 @@ package de.greensurvivors.padlock.command; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; import de.greensurvivors.padlock.impl.SignSelection; import de.greensurvivors.padlock.impl.signdata.SignDisplay; import de.greensurvivors.padlock.impl.signdata.SignLock; +import de.greensurvivors.padlock.language.LangPath; import net.kyori.adventure.text.Component; import org.bukkit.block.Sign; import org.bukkit.command.CommandSender; @@ -39,7 +39,7 @@ protected boolean checkPermission(@NotNull Permissible permissible) { @Override protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_UPDATE_DISPLAY); + return plugin.getMessageManager().getLang(LangPath.HELP_UPDATE_DISPLAY); } @Override @@ -49,28 +49,21 @@ protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] arg Sign sign = SignSelection.getSelectedSign(player); if (sign != null) { - //check for old Lockett(Pro) signs and try to update them - sign = MainCommand.checkAndUpdateLegacySign(sign, player); - if (sign == null) { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NEED_RESELECT); - return true; - } - if (SignLock.isOwner(sign, player.getUniqueId()) || SignLock.isMember(sign, player.getUniqueId()) || player.hasPermission(PermissionManager.ADMIN_EDIT.getPerm())) { SignDisplay.updateDisplay(sign); - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.UPDATE_DISPLAY_SUCCESS); + plugin.getMessageManager().sendLang(sender, LangPath.UPDATE_DISPLAY_SUCCESS); } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_OWNER); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_OWNER); } } } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NO_PERMISSION); + plugin.getMessageManager().sendLang(sender, LangPath.NO_PERMISSION); } return true; } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_A_PLAYER); + plugin.getMessageManager().sendLang(sender, LangPath.NOT_A_PLAYER); return false; } } diff --git a/src/main/java/de/greensurvivors/padlock/command/UpdateLegacy.java b/src/main/java/de/greensurvivors/padlock/command/UpdateLegacy.java deleted file mode 100644 index 6c3c2ec..0000000 --- a/src/main/java/de/greensurvivors/padlock/command/UpdateLegacy.java +++ /dev/null @@ -1,72 +0,0 @@ -package de.greensurvivors.padlock.command; - -import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.PadlockAPI; -import de.greensurvivors.padlock.config.MessageManager; -import de.greensurvivors.padlock.config.PermissionManager; -import de.greensurvivors.padlock.impl.SignSelection; -import net.kyori.adventure.text.Component; -import org.bukkit.block.Sign; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.permissions.Permissible; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.List; -import java.util.Set; - -/** - * updates a selected legacy or additional sign. - */ -@Deprecated(forRemoval = true) -public class UpdateLegacy extends SubCommand { - protected UpdateLegacy(@NotNull Padlock plugin) { - super(plugin); - } - - @Override - protected boolean checkPermission(@NotNull Permissible permissible) { - return permissible.hasPermission(PermissionManager.CMD_UPDATE_LEGACY.getPerm()); - } - - @Override - protected @NotNull Set getAliases() { - return Set.of("updatelegacy"); - } - - @Override - protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_UPDATE_LEGACY); - } - - @Override - protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] args) { - if (this.checkPermission(sender)) { - if (sender instanceof Player player) { - Sign sign = SignSelection.getSelectedSign(player); - if (sign != null) { - if (PadlockAPI.updateLegacySign(sign) != null) { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.UPDATE_LEGACY_SUCCESS); - } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NEED_RESELECT); - } - } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.SIGN_NOT_SELECTED); - } - } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NOT_A_PLAYER); - return false; - } - } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NO_PERMISSION); - } - - return true; - } - - @Override - protected @Nullable List onTabComplete(@NotNull CommandSender sender, @NotNull String[] args) { - return null; - } -} diff --git a/src/main/java/de/greensurvivors/padlock/command/Version.java b/src/main/java/de/greensurvivors/padlock/command/Version.java index 2ba73c3..f2b6628 100644 --- a/src/main/java/de/greensurvivors/padlock/command/Version.java +++ b/src/main/java/de/greensurvivors/padlock/command/Version.java @@ -1,8 +1,8 @@ package de.greensurvivors.padlock.command; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.config.PermissionManager; +import de.greensurvivors.padlock.language.LangPath; import net.kyori.adventure.text.Component; import org.bukkit.command.CommandSender; import org.bukkit.permissions.Permissible; @@ -32,16 +32,16 @@ protected boolean checkPermission(@NotNull Permissible permissible) { @Override protected @NotNull Component getHelpText() { - return plugin.getMessageManager().getLang(MessageManager.LangPath.HELP_VERSION); + return plugin.getMessageManager().getLang(LangPath.HELP_VERSION); } @Override protected boolean onCommand(@NotNull CommandSender sender, @NotNull String[] args) { if (this.checkPermission(sender)) { //plugin.getPluginMeta().getName() + " " + plugin.getPluginMeta().getVersion(); - plugin.getMessageManager().sendMessageWithPrefix(sender, Component.text(plugin.getDescription().getFullName())); //todo once it is worth making the jump to the paper-plugin system + plugin.getMessageManager().sendMessageWithPrefix(sender, Component.text(plugin.getName() + " v" + plugin.getPluginMeta().getVersion())); } else { - plugin.getMessageManager().sendLang(sender, MessageManager.LangPath.NO_PERMISSION); + plugin.getMessageManager().sendLang(sender, LangPath.NO_PERMISSION); } return true; } diff --git a/src/main/java/de/greensurvivors/padlock/config/ConfigManager.java b/src/main/java/de/greensurvivors/padlock/config/ConfigManager.java index 1e5ddef..7eba644 100644 --- a/src/main/java/de/greensurvivors/padlock/config/ConfigManager.java +++ b/src/main/java/de/greensurvivors/padlock/config/ConfigManager.java @@ -20,7 +20,6 @@ public class ConfigManager { private final @NotNull Padlock plugin; // please note: While fallback values are defined here, these are in fact NOT the default options. They are just used in the unfortunate case loading them goes wrong. // if you want to change default options, have also a look into resources/config.yaml - private final ConfigOption IMPORT_FROM_LOCKETTEPRO = new ConfigOption<>("import-fromLockettePro", false); private final ConfigOption LANG_FILENAME = new ConfigOption<>("language-file-name", "lang/lang_en.yml"); private final ConfigOption DEPENDENCY_WORLDGUARD_ENABLED = new ConfigOption<>("dependency.worldguard.enabled", true); private final ConfigOption DEPENDENCY_WORLDGUARD_OVERWRITE = new ConfigOption<>("dependency.worldguard.overwrite", false); @@ -49,11 +48,6 @@ public void reload() { plugin.saveDefaultConfig(); FileConfiguration config = plugin.getConfig(); - if (config.getBoolean(IMPORT_FROM_LOCKETTEPRO.getPath(), IMPORT_FROM_LOCKETTEPRO.getFallbackValue())) { - getFromLegacy(); - } - IMPORT_FROM_LOCKETTEPRO.setValue(false); - //reload Language files plugin.getMessageManager().reload(config.getString(LANG_FILENAME.getPath(), LANG_FILENAME.getFallbackValue())); @@ -63,76 +57,20 @@ public void reload() { // load Material set of lockable blocks List objects = config.getList(LOCKABLES.getPath(), new ArrayList<>(LOCKABLES.getFallbackValue())); - Set resultSet = new HashSet<>(); + /* we need two sets, in case a remove entry happens before an add entry, like in case of: + - -STONE + - * + */ + Set addSet = new HashSet<>(); + Set removeSet = new HashSet<>(); Iterable> tagCache = null; for (Object object : objects) { - if (object instanceof Material material) { - resultSet.add(material); - } else if (object instanceof String string) { - if (string.equals("*")) { - Collections.addAll(resultSet, Material.values()); - plugin.getLogger().info("All blocks are default to be lockable!"); - plugin.getLogger().info("Add '-' to exempt a block, such as '-STONE'!"); - } else { - boolean add = true; - - if (string.startsWith("-")) { - add = false; - string = string.substring(1); - } - Material material = Material.matchMaterial(string); - - if (material != null) { - if (material.isBlock()) { - if (add) { - resultSet.add(material); - } else { - resultSet.remove(material); - } - } else { - plugin.getLogger().warning("\"" + string + " in lockable block list is not a block!"); - } - } else { //try tags - // lazy initialisation - if (tagCache == null) { - tagCache = plugin.getServer().getTags(Tag.REGISTRY_BLOCKS, Material.class); - } - - string = string.toUpperCase(java.util.Locale.ENGLISH); - string = string.replaceAll("\\s+", "_"); - - if (!string.startsWith(MC_NAMESPACE)) { - string = MC_NAMESPACE + string; - } - - boolean found = false; - - for (Tag tag : tagCache) { - if (tag.getKey().asString().equalsIgnoreCase(string)) { - - resultSet.addAll(tag.getValues()); - found = true; - break; - } - } - - if (!found) { - plugin.getLogger().warning("Couldn't get Material \"" + string + "\" for lockable block list. Ignoring."); - } - } - } - } else { - if (object != null) { - plugin.getLogger().warning("Couldn't get Material \"" + object + "\" for lockable block list. Ignoring."); - } - } - /* todo use this in next version - switch (object) { - case Material material -> resultSet.add(material); + switch (object) { + case Material material -> addSet.add(material); case String string -> { if (string.equals("*")) { - Collections.addAll(resultSet, Material.values()); + Collections.addAll(addSet, Material.values()); plugin.getLogger().info("All blocks are default to be lockable!"); plugin.getLogger().info("Add '-' to exempt a block, such as '-STONE'!"); } else { @@ -147,9 +85,9 @@ public void reload() { if (material != null) { if (material.isBlock()) { if (add) { - resultSet.add(material); + addSet.add(material); } else { - resultSet.remove(material); + removeSet.add(material); } } else { plugin.getLogger().warning("\"" + string + " in lockable block list is not a block!"); @@ -160,7 +98,7 @@ public void reload() { tagCache = plugin.getServer().getTags(Tag.REGISTRY_BLOCKS, Material.class); } - string = string.toUpperCase(java.util.Locale.ENGLISH); + string = string.toUpperCase(Locale.ENGLISH); string = string.replaceAll("\\s+", "_"); if (!string.startsWith(MC_NAMESPACE)) { @@ -172,7 +110,11 @@ public void reload() { for (Tag tag : tagCache) { if (tag.getKey().asString().equalsIgnoreCase(string)) { - resultSet.addAll(tag.getValues()); + if (add) { + addSet.addAll(tag.getValues()); + } else { + removeSet.addAll(tag.getValues()); + } found = true; break; } @@ -184,46 +126,39 @@ public void reload() { } } } + case null -> + plugin.getLogger().warning("Couldn't get empty Material for lockable block list. Ignoring."); default -> plugin.getLogger().warning("Couldn't get Material \"" + object + "\" for lockable block list. Ignoring."); } - */ } + addSet.removeAll(removeSet); //never allow these! - resultSet.removeAll(Tag.ALL_SIGNS.getValues()); - resultSet.remove(Material.SCAFFOLDING); - resultSet.remove(Material.AIR); - resultSet.remove(Material.CAVE_AIR); - LOCKABLES.setValue(resultSet); + addSet.removeAll(Tag.ALL_SIGNS.getValues()); + addSet.remove(Material.SCAFFOLDING); + addSet.remove(Material.AIR); + addSet.remove(Material.CAVE_AIR); + LOCKABLES.setValue(addSet); Object object = config.get(QUICKPROTECT_TYPE.getPath(), QUICKPROTECT_TYPE.getFallbackValue()); - if (object instanceof QuickProtectOption quickProtectOption) { - QUICKPROTECT_TYPE.setValue(quickProtectOption); - } else if (object instanceof String string) { - QuickProtectOption setting = MiscUtils.getEnum(QuickProtectOption.class, string); - - if (setting != null) { - QUICKPROTECT_TYPE.setValue(setting); - } else { - plugin.getLogger().warning("Couldn't get QuickProtectOption \"" + string + "\" for quick lock setting. Ignoring and using default value."); - } - } else { - plugin.getLogger().warning("Couldn't get QuickProtectOption \"" + object + "\" for quick lock setting. Ignoring and using default value."); - } - /* todo use this next java version + switch (object) { case QuickProtectOption quickProtectOption -> QUICKPROTECT_TYPE.setValue(quickProtectOption); case String string -> { - QuickProtectOption setting = (QuickProtectOption) getEnumVal(string, QuickProtectOption.values()); + QuickProtectOption setting = MiscUtils.getEnum(QuickProtectOption.class, string); if (setting != null) { QUICKPROTECT_TYPE.setValue(setting); } else { - plugin.getLogger().warning("Couldn't get QuickProtectOption \"" + string + "\" for quick lock setting. Ignoring and using default value."); + plugin.getLogger().warning("Couldn't get QuickProtectOption \"" + string + "\" for quick lock setting. Ignoring and using fallback value."); + QUICKPROTECT_TYPE.setValue(null); } } - default -> plugin.getLogger().warning("Couldn't get QuickProtectOption \"" + object + "\" for quick lock setting. Ignoring and using default value."); - }*/ + default -> { + plugin.getLogger().warning("Couldn't get QuickProtectOption \"" + object + "\" for quick lock setting. Ignoring and using fallback value."); + QUICKPROTECT_TYPE.setValue(null); + } + } LOCK_BLOCKS_INTERFERE.setValue(config.getBoolean(LOCK_BLOCKS_INTERFERE.getPath(), LOCK_BLOCKS_INTERFERE.getFallbackValue())); LOCK_BLOCKS_ITEM_TRANSFER_IN.setValue(config.getBoolean(LOCK_BLOCKS_ITEM_TRANSFER_IN.getPath(), LOCK_BLOCKS_ITEM_TRANSFER_IN.getFallbackValue())); @@ -231,58 +166,33 @@ public void reload() { ITEM_TRANSFER_COOLDOWN.setValue(Math.max(0, config.getInt(ITEM_TRANSFER_COOLDOWN.getPath(), ITEM_TRANSFER_COOLDOWN.getFallbackValue()))); object = config.get(LOCK_BLOCKS_HOPPER_MINECART.getPath(), LOCK_BLOCKS_HOPPER_MINECART.getFallbackValue()); - if (Objects.requireNonNull(object) instanceof HopperMinecartMoveItemOption quickProtectOption) { - LOCK_BLOCKS_HOPPER_MINECART.setValue(quickProtectOption); - } else if (object instanceof String string) { - HopperMinecartMoveItemOption setting = MiscUtils.getEnum(HopperMinecartMoveItemOption.class, string); - - if (setting != null) { - LOCK_BLOCKS_HOPPER_MINECART.setValue(setting); - } else { - plugin.getLogger().warning("Couldn't get QuickProtectOption \"" + string + "\" for quick lock setting. Ignoring and using default value."); - } - } else { - plugin.getLogger().warning("Couldn't get QuickProtectOption \"" + object + "\" for quick lock setting. Ignoring and using default value."); - } - /* todo use this next java version switch (object) { case HopperMinecartMoveItemOption quickProtectOption -> - LOCK_BLOCKS_HOPPER_MINECART.setValue(quickProtectOption); + LOCK_BLOCKS_HOPPER_MINECART.setValue(quickProtectOption); case String string -> { - HopperMinecartMoveItemOption setting = (HopperMinecartMoveItemOption) getEnumVal(string, HopperMinecartMoveItemOption.values()); + HopperMinecartMoveItemOption setting = MiscUtils.getEnum(HopperMinecartMoveItemOption.class, string); if (setting != null) { LOCK_BLOCKS_HOPPER_MINECART.setValue(setting); } else { - plugin.getLogger().warning("Couldn't get QuickProtectOption \"" + string + "\" for quick lock setting. Ignoring and using default value."); + plugin.getLogger().warning("Couldn't get QuickProtectOption \"" + string + "\" for quick lock setting. Ignoring and using fallback value."); + LOCK_BLOCKS_HOPPER_MINECART.setValue(null); } } - default -> plugin.getLogger().warning("Couldn't get QuickProtectOption \"" + object + "\" for quick lock setting. Ignoring and using default value."); + default -> { + plugin.getLogger().warning("Couldn't get QuickProtectOption \"" + object + "\" for quick lock setting. Ignoring and using fallback value."); + LOCK_BLOCKS_HOPPER_MINECART.setValue(null); + } } - */ // load lock exemptions objects = config.getList(LOCK_EXEMPTIONS.getPath(), new ArrayList<>(LOCK_EXEMPTIONS.getFallbackValue())); Set exemptions = new HashSet<>(); for (Object exemptionObj : objects) { - if (exemptionObj instanceof ProtectionExemption protectionExemtion) { - exemptions.add(protectionExemtion); - } else if (exemptionObj instanceof String string) { - ProtectionExemption protectionExemtion = MiscUtils.getEnum(ProtectionExemption.class, string); - - if (protectionExemtion != null) { - exemptions.add(protectionExemtion); - } else { - plugin.getLogger().warning("Couldn't get exemtion \"" + string + "\" for lock exemtion list. Ignoring."); - } - } else { - plugin.getLogger().warning("Couldn't get exemtion \"" + exemptionObj + "\" for lock exemtion list. Ignoring."); - } - /* todo use this next java version switch (exemptionObj) { case ProtectionExemption protectionExemtion -> exemptions.add(protectionExemtion); case String string -> { - ProtectionExemption protectionExemtion = (ProtectionExemption) getEnumVal(string, ProtectionExemption.values()); + ProtectionExemption protectionExemtion = MiscUtils.getEnum(ProtectionExemption.class, string); if (protectionExemtion != null) { exemptions.add(protectionExemtion); @@ -290,10 +200,10 @@ public void reload() { plugin.getLogger().warning("Couldn't get exemtion \"" + string + "\" for lock exemtion list. Ignoring."); } } - default -> - plugin.getLogger().warning("Couldn't get exemtion \"" + exemptionObj + "\" for lock exemtion list. Ignoring."); + case null, default -> + plugin.getLogger().warning("Couldn't get exemtion \"" + exemptionObj + "\" for lock exemtion list. Ignoring."); } - */ + } LOCK_EXEMPTIONS.setValue(exemptions); @@ -309,32 +219,6 @@ public void reload() { MiscUtils.setBedrockPrefix(BEDROCK_PREFIX.getValueOrFallback()); } - /** - * Bridge to load LockettePro configs for easy switch - */ - @Deprecated(forRemoval = true) - private void getFromLegacy() { - LegacyLocketteConfigAdapter adapter = new LegacyLocketteConfigAdapter(); - adapter.reload(plugin); - - FileConfiguration config = plugin.getConfig(); - - config.set(IMPORT_FROM_LOCKETTEPRO.getPath(), false); - config.set(DEPENDENCY_WORLDGUARD_ENABLED.getPath(), adapter.workWithWorldguard()); - config.set(LOCKABLES.getPath(), adapter.getLockables().stream().map(mat -> mat.getKey().asString()).toArray(String[]::new)); - config.set(QUICKPROTECT_TYPE.getPath(), adapter.getQuickProtectAction().toString()); - config.set(LOCK_BLOCKS_INTERFERE.getPath(), adapter.isInterferePlacementBlocked()); - config.set(LOCK_BLOCKS_ITEM_TRANSFER_IN.getPath(), adapter.isItemTransferInBlocked()); - config.set(LOCK_BLOCKS_ITEM_TRANSFER_OUT.getPath(), adapter.isItemTransferOutBlocked()); - config.set(LOCK_BLOCKS_HOPPER_MINECART.getPath(), adapter.getHopperMinecartAction().toString()); - config.set(LOCK_EXEMPTIONS.getPath(), adapter.getProtectionExemptions().toArray(new ProtectionExemption[0])); - config.set(LOCK_EXPIRE_DAYS.getPath(), adapter.getLockExpireDays()); - config.set(CACHE_SECONDS.getPath(), adapter.getCacheTimeSeconds()); - - plugin.saveConfig(); - plugin.reloadConfig(); - } - public @NotNull QuickProtectOption getQuickProtectAction() { return QUICKPROTECT_TYPE.getValueOrFallback(); } diff --git a/src/main/java/de/greensurvivors/padlock/config/ConfigOption.java b/src/main/java/de/greensurvivors/padlock/config/ConfigOption.java index 21d480e..0e6abe4 100644 --- a/src/main/java/de/greensurvivors/padlock/config/ConfigOption.java +++ b/src/main/java/de/greensurvivors/padlock/config/ConfigOption.java @@ -37,7 +37,7 @@ protected ConfigOption(@NotNull String path, @NotNull T fallbackValue) { return Objects.requireNonNullElse(this.value, fallbackValue); } - protected void setValue(@NotNull T value) { + protected void setValue(@Nullable T value) { this.value = value; } } diff --git a/src/main/java/de/greensurvivors/padlock/config/LegacyLocketteConfigAdapter.java b/src/main/java/de/greensurvivors/padlock/config/LegacyLocketteConfigAdapter.java deleted file mode 100644 index 9eec420..0000000 --- a/src/main/java/de/greensurvivors/padlock/config/LegacyLocketteConfigAdapter.java +++ /dev/null @@ -1,171 +0,0 @@ -package de.greensurvivors.padlock.config; - -import de.greensurvivors.padlock.impl.MiscUtils; -import org.bukkit.Material; -import org.bukkit.Tag; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -import java.io.File; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Loads LockettePro config. - * for whomever and why ever to update this adapter: - * Please be aware that this class may look a lot like the config class in LockettePro and this indeed intentional. - * However, please be aware that there were made changes, like using Enums or giving the cache time in seconds back. - */ -@Deprecated(forRemoval = true) -class LegacyLocketteConfigAdapter { - private boolean worldguard = false; - private boolean coreprotect = false; - private Set lockables = new HashSet<>(); - private ConfigManager.QuickProtectOption enablequickprotect = null; - private boolean blockinterfereplacement = true; - private boolean blockitemtransferin = false; - private boolean blockitemtransferout = false; - private int cachetime = 0; - private boolean cacheenabled = false; - private ConfigManager.HopperMinecartMoveItemOption blockhopperminecart = null; - private double lockexpiredays = 999.9D; - private long lockdefaultcreatetime = -1L; - private Set protectionexempt = new HashSet<>(); - - protected LegacyLocketteConfigAdapter() { - } - - protected void reload(@NotNull Plugin plugin) { - FileConfiguration config = YamlConfiguration.loadConfiguration(new File("plugins/LockettePro/config.yml")); - - worldguard = config.getBoolean("worldguard", true); - coreprotect = config.getBoolean("coreprotect", true); - String enablequickprotectstring = config.getString("enable-quick-protect", "true"); - - switch (enablequickprotectstring.toLowerCase()) { - case "false" -> enablequickprotect = ConfigManager.QuickProtectOption.NO_QUICKLOCK; - case "sneak" -> enablequickprotect = ConfigManager.QuickProtectOption.SNEAK_REQUIRED; - default -> enablequickprotect = ConfigManager.QuickProtectOption.NOT_SNEAKING_REQUIRED; - } - blockinterfereplacement = config.getBoolean("block-interfere-placement", true); - blockitemtransferin = config.getBoolean("block-item-transfer-in", false); - blockitemtransferout = config.getBoolean("block-item-transfer-out", true); - - // load Material set of lockable blocks - List stringList = config.getStringList("protection-exempt"); - protectionexempt = new HashSet<>(); - for (String string : stringList) { - ConfigManager.ProtectionExemption protectionExemtion = MiscUtils.getEnum(ConfigManager.ProtectionExemption.class, string); - - if (protectionExemtion != null) { - protectionexempt.add(protectionExemtion); - } else if (!string.equals("nothing")) { // special case, we will just leave it empty. - plugin.getLogger().warning("Couldn't get exemtion from legacy \"" + string + "\" for lock exemtion list. Ignoring."); - } - } - - cachetime = config.getInt("cache-time-seconds", 0); - cacheenabled = (config.getInt("cache-time-seconds", 0) > 0); - if (cacheenabled) { - plugin.getLogger().info("Cache is enabled! In case of inconsistency, turn off immediately."); - } - - String blockhopperminecartstring = config.getString("block-hopper-minecart", "remove"); - switch (blockhopperminecartstring.toLowerCase()) { - case "true" -> blockhopperminecart = ConfigManager.HopperMinecartMoveItemOption.BLOCKED; - case "false" -> blockhopperminecart = ConfigManager.HopperMinecartMoveItemOption.ALLOWED; - default -> blockhopperminecart = ConfigManager.HopperMinecartMoveItemOption.REMOVE; - } - - if (config.getBoolean("lock-expire", false)) { - lockexpiredays = config.getDouble("lock-expire-days", 999.9D); - } else { - lockexpiredays = 0.0D; - } - lockdefaultcreatetime = config.getLong("lock-default-create-time-unix", -1L); - if (lockdefaultcreatetime < -1L) lockdefaultcreatetime = -1L; - List unprocesseditems = config.getStringList("lockables"); - lockables = new HashSet<>(); - for (String unprocesseditem : unprocesseditems) { - if (unprocesseditem.equals("*")) { - Collections.addAll(lockables, Material.values()); - plugin.getLogger().info("All blocks are default to be lockable!"); - plugin.getLogger().info("Add '-' to exempt a block, such as '-STONE'!"); - continue; - } - boolean add = true; - if (unprocesseditem.startsWith("-")) { - add = false; - unprocesseditem = unprocesseditem.substring(1); - } - Material material = Material.getMaterial(unprocesseditem); - if (material == null || !material.isBlock()) { - plugin.getLogger().warning(unprocesseditem + " is not a block!"); - } else { - if (add) { - lockables.add(material); - } else { - lockables.remove(material); - } - } - } - lockables.removeAll(Tag.SIGNS.getValues()); - lockables.remove(Material.SCAFFOLDING); - } - - protected ConfigManager.QuickProtectOption getQuickProtectAction() { - return enablequickprotect; - } - - protected boolean isInterferePlacementBlocked() { - return blockinterfereplacement; - } - - protected boolean isItemTransferInBlocked() { - return blockitemtransferin; - } - - protected boolean isItemTransferOutBlocked() { - return blockitemtransferout; - } - - protected ConfigManager.HopperMinecartMoveItemOption getHopperMinecartAction() { - return blockhopperminecart; - } - - protected Double getLockExpireDays() { - return lockexpiredays; - } - - protected long getLockDefaultCreateTimeUnix() { - return lockdefaultcreatetime; - } - - protected int getCacheTimeSeconds() { - return cachetime; - } - - protected boolean isCacheEnabled() { - return cacheenabled; - } - - protected boolean workWithWorldguard() { - return worldguard; - } - - protected boolean workWithCoreprotect() { - return coreprotect; - } - - protected Set getProtectionExemptions() { - return protectionexempt; - } - - protected Set getLockables() { - return lockables; - } -} \ No newline at end of file diff --git a/src/main/java/de/greensurvivors/padlock/config/PermissionManager.java b/src/main/java/de/greensurvivors/padlock/config/PermissionManager.java index ab6c9d2..a8118e3 100644 --- a/src/main/java/de/greensurvivors/padlock/config/PermissionManager.java +++ b/src/main/java/de/greensurvivors/padlock/config/PermissionManager.java @@ -3,6 +3,7 @@ import org.bukkit.Bukkit; import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionDefault; +import org.jetbrains.annotations.NotNull; import java.util.Map; @@ -37,10 +38,6 @@ public enum PermissionManager { CMD_UPDATE_DISPLAY(new Permission("padlock.cmd.updatedisplay", "Owners or members of a sign may update the display, to reflect the latest language changes or the changed username.", PermissionDefault.OP)), - @Deprecated(forRemoval = true) - CMD_UPDATE_LEGACY(new Permission("padlock.cmd.updatelegacy", - "Using `/padlock updatelegacy` forces the plugin to update a lock sign from Lockette(Pro) signs.", - PermissionDefault.OP)), CMD_VERSION(new Permission("padlock.cmd.version", "`/padlock version` returns the version of this plugin.", PermissionDefault.OP)), @@ -57,7 +54,6 @@ public enum PermissionManager { Map.entry(CMD_SET_PASSWORD.perm.getName(), true), Map.entry(CMD_SET_TIMER.perm.getName(), true), Map.entry(CMD_UPDATE_DISPLAY.perm.getName(), true), - Map.entry(CMD_UPDATE_LEGACY.perm.getName(), true), Map.entry(CMD_VERSION.perm.getName(), true) ))), @@ -104,7 +100,7 @@ public enum PermissionManager { private final Permission perm; - PermissionManager(Permission perm) { + PermissionManager(@NotNull Permission perm) { this.perm = perm; Bukkit.getPluginManager().addPermission(perm); diff --git a/src/main/java/de/greensurvivors/padlock/impl/LockCacheManager.java b/src/main/java/de/greensurvivors/padlock/impl/LockCacheManager.java index 668465a..6f2b213 100644 --- a/src/main/java/de/greensurvivors/padlock/impl/LockCacheManager.java +++ b/src/main/java/de/greensurvivors/padlock/impl/LockCacheManager.java @@ -25,7 +25,7 @@ * Normally not, no. But with many Inventory movement attempts like big hopper contraptions or * heavy redstone wire use might be. */ -public class LockCacheManager { +public class LockCacheManager { // todo check Persistent data container use // cache has a maximum size to not grow unlimited private final Map lockLazyProps = new HashMap<>(); private final @NotNull Cache<@NotNull Location, @NotNull LockWrapper> lockStateCache = Caffeine.newBuilder(). @@ -44,7 +44,7 @@ public void setExpirationTime(@NonNegative long duration, @NotNull TimeUnit unit policy.ifPresent(expiration -> expiration.setExpiresAfter(duration, unit)); } - public @NotNull LazySignProperties getProtectedFromCache(@NotNull Location location) { + public @NotNull LazySignProperties getProtectedFromCache(final @NotNull Location location) { LockWrapper lockWrapper = lockStateCache.getIfPresent(location); if (lockWrapper != null) { @@ -64,7 +64,7 @@ public void setExpirationTime(@NonNegative long duration, @NotNull TimeUnit unit if (lock != null) { lockStateCache.put(location, new LockWrapper(lock.getLocation())); - LazySignProperties lazySignPropertys = lockLazyProps.get(lock); + LazySignProperties lazySignPropertys = lockLazyProps.get(lock.getLocation()); if (lazySignPropertys == null) { lazySignPropertys = new LazySignProperties(lock); diff --git a/src/main/java/de/greensurvivors/padlock/impl/MiscUtils.java b/src/main/java/de/greensurvivors/padlock/impl/MiscUtils.java index 3ec1cd9..969590a 100644 --- a/src/main/java/de/greensurvivors/padlock/impl/MiscUtils.java +++ b/src/main/java/de/greensurvivors/padlock/impl/MiscUtils.java @@ -21,7 +21,6 @@ import java.util.Locale; import java.util.Set; import java.util.UUID; -import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -138,43 +137,45 @@ public static void setBedrockPrefix(@NotNull String bedrockPrefix) { * First try ISO-8601 duration, and afterward our own implementation * using the same time unit more than once is permitted. * - * @return the duration in milliseconds, or null if not possible + * @return the duration, or null if not possible */ - public static @Nullable Long parsePeriod(@NotNull String period) { + public static @Nullable Duration parsePeriod(@NotNull String period) { try { //try Iso - return Duration.parse(period).toMillis(); + return Duration.parse(period); } catch (DateTimeParseException e) { Padlock.getPlugin().getLogger().log(Level.FINE, "Couldn't get time period \"" + period + "\" as duration. Trying to parse manual next.", e); } + @Nullable Duration result = null; + Matcher matcher = periodPattern.matcher(period); - Long millis = null; while (matcher.find()) { // we got a match. - if (millis == null) { - millis = 0L; + if (result == null) { + result = Duration.ZERO; } try { long num = Long.parseLong(matcher.group(1)); String typ = matcher.group(2); - millis += switch (typ) { // from periodPattern - case "t", "T" -> Math.round(50D * num); // ticks - case "s", "S" -> TimeUnit.SECONDS.toMillis(num); - case "m" -> TimeUnit.MINUTES.toMillis(num); - case "h", "H" -> TimeUnit.HOURS.toMillis(num); - case "d", "D" -> TimeUnit.DAYS.toMillis(num); - case "w", "W" -> TimeUnit.DAYS.toMillis(Period.ofWeeks((int) num).getDays()); - case "M" -> TimeUnit.DAYS.toMillis(Period.ofMonths((int) num).getDays()); - default -> 0; + + result = switch (typ) { // from periodPattern + case "t", "T" -> result.plusMillis(Math.round(50D * num)); // ticks + case "s", "S" -> result.plusSeconds(num); + case "m" -> result.plusMinutes(num); + case "h", "H" -> result.plusHours(num); + case "d", "D" -> result.plusDays(num); + case "w", "W" -> result.plusDays(Period.ofWeeks((int) num).getDays()); + case "M" -> result.plusDays(Period.ofMonths((int) num).getDays()); + default -> Duration.ZERO; }; } catch (NumberFormatException e) { Padlock.getPlugin().getLogger().log(Level.WARNING, "Couldn't get time period for " + period, e); } } - return millis; + return result; } public static @NotNull String formatTimeString(final @NotNull Duration duration) { diff --git a/src/main/java/de/greensurvivors/padlock/impl/dataTypes/LazySignProperties.java b/src/main/java/de/greensurvivors/padlock/impl/dataTypes/LazySignProperties.java index bd3ff53..520917e 100644 --- a/src/main/java/de/greensurvivors/padlock/impl/dataTypes/LazySignProperties.java +++ b/src/main/java/de/greensurvivors/padlock/impl/dataTypes/LazySignProperties.java @@ -7,13 +7,15 @@ import org.bukkit.block.Sign; import org.jetbrains.annotations.Nullable; +import java.time.Duration; + public class LazySignProperties { private final @Nullable Sign lock; private final boolean isLock; private ListOrderedSet ownerUUIDStrs; private ListOrderedSet memberUUIDStrs; - private Long timer; + private Duration timer; private SignAccessType.AccessType accessType; public LazySignProperties(@Nullable Sign lockSign) { @@ -46,7 +48,7 @@ public boolean isLock() { return memberUUIDStrs; } - public @Nullable Long getTimer() { + public @Nullable Duration getTimer() { if (isLock && timer == null) { timer = SignTimer.getTimer(lock, true); } diff --git a/src/main/java/de/greensurvivors/padlock/impl/openabledata/OpenableToggleManager.java b/src/main/java/de/greensurvivors/padlock/impl/openabledata/OpenableToggleManager.java index d448018..d3c443c 100644 --- a/src/main/java/de/greensurvivors/padlock/impl/openabledata/OpenableToggleManager.java +++ b/src/main/java/de/greensurvivors/padlock/impl/openabledata/OpenableToggleManager.java @@ -6,9 +6,11 @@ import org.bukkit.Location; import org.bukkit.Tag; import org.bukkit.block.Block; +import org.bukkit.entity.Player; import org.bukkit.scheduler.BukkitTask; import org.jetbrains.annotations.NotNull; +import java.time.Duration; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @@ -51,9 +53,9 @@ public void cancelAllTasks() { * If at least one of the blocks already as a task for it running the task will be canceled and no new * task will get created. That's because the block was already closed, and we would open it running any task at this point. * - * @param timeUntilToggle time to wait until all the given blocks will get toggled in milliseconds + * @param timeUntilToggle time to wait until all the given blocks will get toggled */ - public void toggleCancelRunning(final @NotNull Set<@NotNull Block> blocksToToggle, final long timeUntilToggle) { + public void toggleCancelRunning(final @NotNull Player player, final @NotNull Set<@NotNull Block> blocksToToggle, Duration timeUntilToggle) { Set locationsToToggle = blocksToToggle.stream().map(Block::getLocation).collect(Collectors.toSet()); // remove running tasks @@ -88,16 +90,17 @@ public void toggleCancelRunning(final @NotNull Set<@NotNull Block> blocksToToggl } } - Openables.toggleOpenable(openableBlock); + Openables.toggleOpenable(player, openableBlock); if (taskToClearUp != null) { final BukkitTask finalTaskToClearUp = taskToClearUp; // just Java being Java and needing a final variable, even if this can't change at this point. toggleTasks.entrySet().removeIf(entry -> entry.getValue().equals(finalTaskToClearUp)); } } - // the reason why we multiply with 20 before converting to seconds, not after (millis -> seconds --> ticks), - // is that with time durations smaller than one second it would always result in 0 instead of an amount of ticks. - }, TimeUnit.MILLISECONDS.toSeconds(timeUntilToggle * 20L)); + + // the reason why we multiply with the rick rate (20 per default) before we convert to TimeUnit seconds, is because of accuracy of decimal places. + // like in cases where it was set to below 999ms we would get 0 ticks instead of 20 you would expect (with default tick rate) + }, TimeUnit.MILLISECONDS.toSeconds(Math.round(timeUntilToggle.toMillis() * (double) plugin.getServer().getServerTickManager().getTickRate()))); for (Location location : locationsToToggle) { toggleTasks.put(location, task); diff --git a/src/main/java/de/greensurvivors/padlock/impl/openabledata/Openables.java b/src/main/java/de/greensurvivors/padlock/impl/openabledata/Openables.java index b6ee613..bfbeabf 100644 --- a/src/main/java/de/greensurvivors/padlock/impl/openabledata/Openables.java +++ b/src/main/java/de/greensurvivors/padlock/impl/openabledata/Openables.java @@ -1,34 +1,118 @@ package de.greensurvivors.padlock.impl.openabledata; +import de.greensurvivors.padlock.Padlock; import de.greensurvivors.padlock.PadlockAPI; import de.greensurvivors.padlock.impl.dataTypes.DoubleBlockParts; +import net.minecraft.core.BlockPos; +import net.minecraft.server.level.ServerLevel; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.DoorBlock; +import net.minecraft.world.level.block.FenceGateBlock; +import net.minecraft.world.level.block.TrapDoorBlock; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.phys.BlockHitResult; +import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; +import org.bukkit.SoundCategory; import org.bukkit.Tag; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.data.Openable; +import org.bukkit.craftbukkit.CraftWorld; +import org.bukkit.craftbukkit.block.CraftBlockType; +import org.bukkit.craftbukkit.block.data.CraftBlockData; +import org.bukkit.craftbukkit.entity.CraftPlayer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; +import java.util.Random; /** * Helper class for openables */ public class Openables { + private static final Random RANDOM = new Random(); + // cache found methods, since reflection is expensive + private static final Map<@NotNull Class, @NotNull Method> cachedMethods = new HashMap<>(); + /** * open/closes the openable block (door, fence gate, trapdoor,...) * will do nothing if the block can't be opened. */ - public static void toggleOpenable(@NotNull Block block) { + public static void toggleOpenable(@NotNull org.bukkit.entity.Player player, @NotNull Block block) { if (block.getBlockData() instanceof Openable openable) { boolean open = !openable.isOpen(); + if (block.getBlockData() instanceof CraftBlockData craftBlockData) { + net.minecraft.world.level.block.Block nmsBlock = CraftBlockType.bukkitToMinecraft(block.getType()); + Location location = block.getLocation(); + + final BlockPos blockPos = new BlockPos(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + final ServerLevel level = ((CraftWorld) block.getWorld()).getHandle(); + final ServerPlayer serverPlayer = ((CraftPlayer) player).getHandle(); + + switch (nmsBlock) { + case DoorBlock doorBlock -> { + // don't use useWithoutItem because of iron door check + doorBlock.setOpen(serverPlayer, level, craftBlockData.getState(), blockPos, open); + + return; + } + case TrapDoorBlock trapDoorBlock -> { + try { + Class clazz = trapDoorBlock.getClass(); + Method method = cachedMethods.get(clazz); + + if (method == null) { + // don't use useWithoutItem because of iron trapdoor check + method = clazz.getDeclaredMethod("toggle", BlockState.class, Level.class, BlockPos.class, Player.class); + method.setAccessible(true); + + cachedMethods.put(clazz, method); + } + + method.invoke(trapDoorBlock, craftBlockData.getState(), level, blockPos, serverPlayer); + + return; + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + Padlock.getPlugin().getComponentLogger().warn("Could use \"useWithoutItem\" of trapdoor, block: " + block, e); + } + } + case FenceGateBlock fenceGateBlock -> { + try { + Class clazz = fenceGateBlock.getClass(); + Method method = cachedMethods.get(clazz); + + if (method == null) { + method = clazz.getDeclaredMethod("useWithoutItem", BlockState.class, Level.class, BlockPos.class, Player.class, BlockHitResult.class); + method.setAccessible(true); + + cachedMethods.put(clazz, method); + } + + method.invoke(fenceGateBlock, craftBlockData.getState(), level, blockPos, serverPlayer, null); + + return; + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + Padlock.getPlugin().getComponentLogger().warn("Could use \"useWithoutItem\" of fence gate, block: " + block, e); + } + } + case null, default -> { + } + } + } + + // unknown, get fallback openable.setOpen(open); block.setBlockData(openable); - block.getWorld().playSound(block.getLocation(), open ? OpenableSound.getOpenSound(block.getType()) : OpenableSound.getCloseSound(block.getType()), 1, 1); + block.getWorld().playSound(block.getLocation(), open ? getOpenSound(block.getType()) : getCloseSound(block.getType()), SoundCategory.BLOCKS, 1, RANDOM.nextFloat() * 0.1f + 0.9f); } } @@ -75,7 +159,7 @@ public static boolean isSingleOpenable(@NotNull Material material) { * @return mapping from all directions to adjacent to the block of the same type. * A direction might be missing if there was no fitting block */ - public static @NotNull Map<@NotNull BlockFace, @NotNull Block> getConnectedSingle(Block block) { + public static @NotNull Map<@NotNull BlockFace, @NotNull Block> getConnectedSingle(@NotNull Block block) { Map adjacent = new HashMap<>(); for (BlockFace blockFace : PadlockAPI.allFaces) { @@ -107,13 +191,14 @@ public static boolean isSingleOpenable(@NotNull Material material) { } } + return adjacent; } /** * Returns true if the submitted block OR the one below / above it is a door */ - public static boolean isUpDownDoor(Block block) { + public static boolean isUpDownDoor(@NotNull Block block) { return // is door Tag.DOORS.isTagged(block.getType()) || // Indirectly protecting a door @@ -121,110 +206,29 @@ public static boolean isUpDownDoor(Block block) { Tag.DOORS.isTagged(block.getRelative(BlockFace.DOWN).getType()); } - /** - * enum containing all the sounds to play, when an openable open/closes - * This is here because just setting the data of a block to open/close doesn't make a sound. - */ - private enum OpenableSound { // todo find a way to use net.minecraft.world.level.block.state.properties.BlockSetType - OAK_DOOR(Material.OAK_DOOR), - SPRUCE_DOOR(Material.SPRUCE_DOOR), - BIRCH_DOOR(Material.BIRCH_DOOR), - ACACIA_DOOR(Material.ACACIA_DOOR), - JUNGLE_DOOR(Material.JUNGLE_DOOR), - DARK_OAK_DOOR(Material.DARK_OAK_DOOR), - MANGROVE_DOOR(Material.MANGROVE_DOOR), - IRON_DOOR(Material.IRON_DOOR, Sound.BLOCK_IRON_DOOR_CLOSE, Sound.BLOCK_IRON_DOOR_OPEN), - CRIMSON_DOOR(Material.CRIMSON_DOOR, Sound.BLOCK_NETHER_WOOD_DOOR_CLOSE, Sound.BLOCK_NETHER_WOOD_DOOR_OPEN), - WARPED_DOOR(Material.WARPED_DOOR, Sound.BLOCK_NETHER_WOOD_DOOR_CLOSE, Sound.BLOCK_NETHER_WOOD_DOOR_OPEN), - CHERRY_DOOR(Material.CHERRY_DOOR, Sound.BLOCK_CHERRY_WOOD_DOOR_CLOSE, Sound.BLOCK_CHERRY_WOOD_DOOR_OPEN), - BAMBOO_DOOR(Material.BAMBOO_DOOR, Sound.BLOCK_BAMBOO_WOOD_DOOR_CLOSE, Sound.BLOCK_BAMBOO_WOOD_DOOR_OPEN), - OAK_TRAPDOOR(Material.OAK_TRAPDOOR), - SPRUCE_TRAPDOOR(Material.SPRUCE_TRAPDOOR), - BIRCH_TRAPDOOR(Material.BIRCH_TRAPDOOR), - ACACIA_TRAPDOOR(Material.ACACIA_TRAPDOOR), - JUNGLE_TRAPDOOR(Material.JUNGLE_TRAPDOOR), - DARK_OAK_TRAPDOOR(Material.DARK_OAK_TRAPDOOR), - MANGROVE_TRAPDOOR(Material.MANGROVE_TRAPDOOR), - IRON_TRAPDOOR(Material.IRON_TRAPDOOR, Sound.BLOCK_IRON_TRAPDOOR_CLOSE, Sound.BLOCK_IRON_TRAPDOOR_OPEN), - CRIMSON_TRAPDOOR(Material.CRIMSON_TRAPDOOR, Sound.BLOCK_NETHER_WOOD_TRAPDOOR_CLOSE, Sound.BLOCK_NETHER_WOOD_TRAPDOOR_OPEN), - WARPED_TRAPDOOR(Material.WARPED_TRAPDOOR, Sound.BLOCK_NETHER_WOOD_TRAPDOOR_CLOSE, Sound.BLOCK_NETHER_WOOD_TRAPDOOR_OPEN), - CHERRY_TRAPDOOR(Material.CHERRY_TRAPDOOR, Sound.BLOCK_CHERRY_WOOD_TRAPDOOR_CLOSE, Sound.BLOCK_CHERRY_WOOD_TRAPDOOR_OPEN), - BAMBOO_TRAPDOOR(Material.BAMBOO_TRAPDOOR, Sound.BLOCK_BAMBOO_WOOD_TRAPDOOR_CLOSE, Sound.BLOCK_BAMBOO_WOOD_TRAPDOOR_OPEN), - OAK_FENCE_GATE(Material.OAK_FENCE_GATE), - SPRUCE_FENCE_GATE(Material.SPRUCE_FENCE_GATE), - BIRCH_FENCE_GATE(Material.BIRCH_FENCE_GATE), - ACACIA_FENCE_GATE(Material.ACACIA_FENCE_GATE), - JUNGLE_FENCE_GATE(Material.JUNGLE_FENCE_GATE), - DARK_OAK_FENCE_GATE(Material.DARK_OAK_FENCE_GATE), - MANGROVE_FENCE_GATE(Material.MANGROVE_FENCE_GATE), - CRIMSON_FENCE_GATE(Material.CRIMSON_FENCE_GATE, Sound.BLOCK_NETHER_WOOD_FENCE_GATE_CLOSE, Sound.BLOCK_NETHER_WOOD_FENCE_GATE_OPEN), - WARPED_FENCE_GATE(Material.WARPED_FENCE_GATE, Sound.BLOCK_NETHER_WOOD_FENCE_GATE_CLOSE, Sound.BLOCK_NETHER_WOOD_FENCE_GATE_OPEN), - CHERRY_FENCE_GATE(Material.CHERRY_FENCE_GATE, Sound.BLOCK_CHERRY_WOOD_FENCE_GATE_CLOSE, Sound.BLOCK_CHERRY_WOOD_FENCE_GATE_OPEN), - BAMBOO_FENCE_GATE(Material.BAMBOO_FENCE_GATE, Sound.BLOCK_BAMBOO_WOOD_FENCE_GATE_CLOSE, Sound.BLOCK_BAMBOO_WOOD_FENCE_GATE_OPEN); - - private final Material material; - private final Sound closeSound; - private final Sound openSound; - - OpenableSound(@NotNull Material material) { - this.material = material; - if (Tag.DOORS.isTagged(material)) { - this.closeSound = Sound.BLOCK_WOODEN_DOOR_CLOSE; - this.openSound = Sound.BLOCK_WOODEN_DOOR_OPEN; - } else if (Tag.TRAPDOORS.isTagged(material)) { - this.closeSound = Sound.BLOCK_WOODEN_TRAPDOOR_CLOSE; - this.openSound = Sound.BLOCK_WOODEN_TRAPDOOR_OPEN; - } else if (Tag.FENCE_GATES.isTagged(material)) { - this.closeSound = Sound.BLOCK_FENCE_GATE_CLOSE; - this.openSound = Sound.BLOCK_FENCE_GATE_OPEN; - } else { // I have no idea. Should never happen... - this.closeSound = Sound.ENTITY_VILLAGER_NO; - this.openSound = Sound.ENTITY_VILLAGER_YES; - } + private static @NotNull Sound getCloseSound(@NotNull Material material) { + // fallback in case a material wasn't implemented yet + if (Tag.DOORS.isTagged(material)) { + return Sound.BLOCK_WOODEN_DOOR_CLOSE; + } else if (Tag.TRAPDOORS.isTagged(material)) { + return Sound.BLOCK_WOODEN_TRAPDOOR_CLOSE; + } else if (Tag.FENCE_GATES.isTagged(material)) { + return Sound.BLOCK_FENCE_GATE_CLOSE; + } else { // I have no idea. Should never happen... + return Sound.ENTITY_VILLAGER_NO; } + } - OpenableSound(@NotNull Material material, @NotNull Sound closeSound, @NotNull Sound openSound) { - this.material = material; - this.closeSound = closeSound; - this.openSound = openSound; - } - - public static @NotNull Sound getCloseSound(@NotNull Material material) { - for (OpenableSound doorSound : OpenableSound.values()) { - if (doorSound.material.equals(material)) { - return doorSound.closeSound; - } - } - - // fallback in case a new door wasn't implemented yet - if (Tag.DOORS.isTagged(material)) { - return Sound.BLOCK_WOODEN_DOOR_CLOSE; - } else if (Tag.TRAPDOORS.isTagged(material)) { - return Sound.BLOCK_WOODEN_TRAPDOOR_CLOSE; - } else if (Tag.FENCE_GATES.isTagged(material)) { - return Sound.BLOCK_FENCE_GATE_CLOSE; - } else { // I have no idea. Should never happen... - return Sound.ENTITY_VILLAGER_NO; - } - } - - public static @NotNull Sound getOpenSound(@NotNull Material material) { - for (OpenableSound doorSound : OpenableSound.values()) { - if (doorSound.material.equals(material)) { - return doorSound.openSound; - } - } - - // fallback in case a new door wasn't implemented yet - if (Tag.DOORS.isTagged(material)) { - return Sound.BLOCK_WOODEN_DOOR_OPEN; - } else if (Tag.TRAPDOORS.isTagged(material)) { - return Sound.BLOCK_WOODEN_TRAPDOOR_OPEN; - } else if (Tag.FENCE_GATES.isTagged(material)) { - return Sound.BLOCK_FENCE_GATE_OPEN; - } else { // I have no idea. Should never happen... - return Sound.ENTITY_VILLAGER_YES; - } + private static @NotNull Sound getOpenSound(@NotNull Material material) { + // fallback in case a new material wasn't implemented yet + if (Tag.DOORS.isTagged(material)) { + return Sound.BLOCK_WOODEN_DOOR_OPEN; + } else if (Tag.TRAPDOORS.isTagged(material)) { + return Sound.BLOCK_WOODEN_TRAPDOOR_OPEN; + } else if (Tag.FENCE_GATES.isTagged(material)) { + return Sound.BLOCK_FENCE_GATE_OPEN; + } else { // I have no idea. Should never happen... + return Sound.ENTITY_VILLAGER_YES; } } } diff --git a/src/main/java/de/greensurvivors/padlock/impl/signdata/SignAccessType.java b/src/main/java/de/greensurvivors/padlock/impl/signdata/SignAccessType.java index 39d04bb..52faebe 100644 --- a/src/main/java/de/greensurvivors/padlock/impl/signdata/SignAccessType.java +++ b/src/main/java/de/greensurvivors/padlock/impl/signdata/SignAccessType.java @@ -1,14 +1,13 @@ package de.greensurvivors.padlock.impl.signdata; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.PadlockAPI; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.impl.MiscUtils; +import de.greensurvivors.padlock.language.LangPath; +import de.greensurvivors.padlock.language.MessageManager; import net.kyori.adventure.text.Component; import org.bukkit.NamespacedKey; import org.bukkit.block.Block; import org.bukkit.block.Sign; -import org.bukkit.block.sign.Side; import org.bukkit.inventory.InventoryHolder; import org.bukkit.persistence.PersistentDataContainer; import org.bukkit.persistence.PersistentDataType; @@ -37,21 +36,19 @@ public static void setAccessType(@NotNull Sign sign, @NotNull AccessType accessT /** * unless you work with player input use {@link #getAccessType(Sign, boolean)} instead! */ - public static AccessType getAccessTypeFromComp(@NotNull Component line) { - MessageManager manager = Padlock.getPlugin().getMessageManager(); + public static @Nullable AccessType getAccessTypeFromComp(@NotNull Component line) { + final @NotNull MessageManager manager = Padlock.getPlugin().getMessageManager(); - if (manager.isSignComp(line, MessageManager.LangPath.SIGN_LINE_PRIVATE)) { + if (manager.isSignComp(line, LangPath.SIGN_LINE_PRIVATE)) { return AccessType.PRIVATE; - } else if (manager.isSignComp(line, MessageManager.LangPath.SIGN_LINE_PUBLIC)) { + } else if (manager.isSignComp(line, LangPath.SIGN_LINE_PUBLIC)) { return AccessType.PUBLIC; - } else if (manager.isSignComp(line, MessageManager.LangPath.SIGN_LINE_DONATION)) { + } else if (manager.isSignComp(line, LangPath.SIGN_LINE_DONATION)) { return AccessType.DONATION; - } else if (manager.isSignComp(line, MessageManager.LangPath.SIGN_LINE_DISPLAY)) { + } else if (manager.isSignComp(line, LangPath.SIGN_LINE_DISPLAY)) { return AccessType.DISPLAY; - } else if (manager.isSignComp(line, MessageManager.LangPath.SIGN_LINE_SUPPLY_SIGN)) { + } else if (manager.isSignComp(line, LangPath.SIGN_LINE_SUPPLY_SIGN)) { return AccessType.SUPPLY; - } else if (manager.isLegacySignComp(line, MessageManager.LangPath.LEGACY_PRIVATE_SIGN)) { - return AccessType.PRIVATE; } else { return null; } @@ -68,12 +65,7 @@ public static AccessType getAccessTypeFromComp(@NotNull Component line) { AccessType accessType; if (accessTypeStr == null) { - accessType = getLegacySetting(sign); - if (accessType != null) { - PadlockAPI.updateLegacySign(sign); - } else { - return null; - } + return null; } else { accessType = MiscUtils.getEnum(AccessType.class, accessTypeStr); @@ -87,66 +79,6 @@ public static AccessType getAccessTypeFromComp(@NotNull Component line) { } } - /** - * update a legacy lockette lock sign with potential an everyone line on it. - * Will not update the Display of the sign afterwarts to not overwrite other unimported data like timers - */ - @Deprecated(forRemoval = true) - public static void updateLegacyType(@NotNull Sign sign) { - AccessType type = getLegacySetting(sign); - - if (type != null) { - setAccessType(sign, type, false); - } else { - Padlock.getPlugin().getLogger().warning("couldn't get an access type to update from. Using private. sign at: " + sign.getLocation()); - setAccessType(sign, AccessType.PRIVATE, false); - } - } - - /** - * checks if a line would be a line of an everyone sign. - * This is only available to make sure the line can safely interpreted as a username. - * Please don't use this to get data of a legacy sign. - * Use {@link #updateLegacyType(Sign)} and then {@link #getAccessType(Sign, boolean)} - */ - @Deprecated(forRemoval = true) - public static boolean isLegacyEveryOneComp(@NotNull Component component) { - return Padlock.getPlugin().getMessageManager().isLegacySignComp(component, MessageManager.LangPath.LEGACY_EVERYONE_SIGN); - } - - /** - * returns {@link AccessType#PUBLIC} if at least one sign is a legacy lockette everyone line. - */ - @Deprecated(forRemoval = true) - private static @Nullable AccessType getLegacySetting(@NotNull Sign sign) { - boolean isPrivate = false; - for (Component line : sign.getSide(Side.FRONT).lines()) { - if (Padlock.getPlugin().getMessageManager().isLegacySignComp(line, MessageManager.LangPath.LEGACY_PRIVATE_SIGN)) { - isPrivate = true; // a lockette sign can have [Everyone] and [Private] on the same sign, and the Everyone-one overwrites - } else if (Padlock.getPlugin().getMessageManager().isLegacySignComp(line, MessageManager.LangPath.LEGACY_EVERYONE_SIGN)) { - return AccessType.PUBLIC; - } - } - - if (isPrivate) { - return AccessType.PRIVATE; - } else { - return null; - } - } - - /** - * update a legacy lockette additional sign with potential an everyone line on it. - */ - public static void updateLegacyTypeFromAdditional(Sign lockSign, Sign additional) { - AccessType type = getLegacySetting(additional); - - // not every additional sign has an "everyone" on it, and this is the only access type they can have - if (type != null) { - setAccessType(lockSign, type, true); - } - } - public enum AccessType { PRIVATE(false), PUBLIC(false), // everyone is member @@ -160,7 +92,7 @@ public enum AccessType { this.isInventoryHolderOnly = isInventoryHolderOnly; } - public boolean doesQualifyAs(Block block) { //todo + public boolean doesQualifyAs(@NotNull Block block) { //todo return !isInventoryHolderOnly || block.getState() instanceof InventoryHolder; } } diff --git a/src/main/java/de/greensurvivors/padlock/impl/signdata/SignConnectedOpenable.java b/src/main/java/de/greensurvivors/padlock/impl/signdata/SignConnectedOpenable.java index 24c963d..ce8eb9d 100644 --- a/src/main/java/de/greensurvivors/padlock/impl/signdata/SignConnectedOpenable.java +++ b/src/main/java/de/greensurvivors/padlock/impl/signdata/SignConnectedOpenable.java @@ -1,9 +1,7 @@ package de.greensurvivors.padlock.impl.signdata; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.impl.openabledata.Openables; import org.bukkit.NamespacedKey; -import org.bukkit.block.Block; import org.bukkit.block.Sign; import org.bukkit.persistence.PersistentDataType; import org.jetbrains.annotations.NotNull; @@ -22,16 +20,4 @@ public static void setConnected(@NotNull Sign sign, boolean isConnected) { sign.getPersistentDataContainer().set(connectedOpenableKey, PersistentDataType.BOOLEAN, isConnected); sign.update(); } - - /** - * updates from a legacy lockette sign, automatically setting to connected if the block is a door, - * or has a door above / below it. - */ - @Deprecated(forRemoval = true) - public static void updateLegacy(@NotNull Sign sign, Block protectedBlock) { - if (Openables.isUpDownDoor(protectedBlock)) { - setConnected(sign, true); - } - } - } diff --git a/src/main/java/de/greensurvivors/padlock/impl/signdata/SignDisplay.java b/src/main/java/de/greensurvivors/padlock/impl/signdata/SignDisplay.java index 5d2ab1d..839d945 100644 --- a/src/main/java/de/greensurvivors/padlock/impl/signdata/SignDisplay.java +++ b/src/main/java/de/greensurvivors/padlock/impl/signdata/SignDisplay.java @@ -1,7 +1,8 @@ package de.greensurvivors.padlock.impl.signdata; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.config.MessageManager; +import de.greensurvivors.padlock.language.LangPath; +import de.greensurvivors.padlock.language.PlaceHolder; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import org.bukkit.Bukkit; @@ -52,8 +53,8 @@ private static boolean fillWithPlayers(@Nullable Component @NotNull [] toFill, @ OfflinePlayer player = Bukkit.getOfflinePlayer(UUID.fromString(uuidStr)); if (player.getName() != null) { - toFill[i] = Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SIGN_PLAYER_NAME_ON, - Placeholder.unparsed(MessageManager.PlaceHolder.PLAYER.getPlaceholder(), player.getName())); + toFill[i] = Padlock.getPlugin().getMessageManager().getLang(LangPath.SIGN_PLAYER_NAME_ON, + Placeholder.unparsed(PlaceHolder.PLAYER.getPlaceholder(), player.getName())); //we have written a line; back to main loop to get the next one! continue mainLoop; @@ -100,15 +101,12 @@ public static void updateDisplay(@NotNull Sign sign) { // first line is always just the lock line SignAccessType.AccessType accessType = SignAccessType.getAccessType(sign, false); linesToUpdate[0] = switch (accessType) { - case PRIVATE -> Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SIGN_LINE_PRIVATE); - case PUBLIC -> Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SIGN_LINE_PUBLIC); - case DONATION -> - Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SIGN_LINE_DONATION); - case DISPLAY -> Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SIGN_LINE_DISPLAY); - case SUPPLY -> - Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SIGN_LINE_SUPPLY_SIGN); - /*case null, // todo next java version*/ - default -> Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SIGN_LINE_ERROR); + case PRIVATE -> Padlock.getPlugin().getMessageManager().getLang(LangPath.SIGN_LINE_PRIVATE); + case PUBLIC -> Padlock.getPlugin().getMessageManager().getLang(LangPath.SIGN_LINE_PUBLIC); + case DONATION -> Padlock.getPlugin().getMessageManager().getLang(LangPath.SIGN_LINE_DONATION); + case DISPLAY -> Padlock.getPlugin().getMessageManager().getLang(LangPath.SIGN_LINE_DISPLAY); + case SUPPLY -> Padlock.getPlugin().getMessageManager().getLang(LangPath.SIGN_LINE_SUPPLY_SIGN); + case null -> Padlock.getPlugin().getMessageManager().getLang(LangPath.SIGN_LINE_ERROR); }; //special settings @@ -119,7 +117,7 @@ public static void updateDisplay(@NotNull Sign sign) { } if (SignPasswords.needsPasswordAccess(sign)) { - linesToUpdate[lastIndex] = Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SING_LINE_HAS_PASSWORD); + linesToUpdate[lastIndex] = Padlock.getPlugin().getMessageManager().getLang(LangPath.SING_LINE_HAS_PASSWORD); lastIndex--; } @@ -130,7 +128,7 @@ public static void updateDisplay(@NotNull Sign sign) { } if (shouldAddMoreUsers) { // this might overwrite the last name - linesToUpdate[lastIndex] = Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SIGN_MORE_USERS); + linesToUpdate[lastIndex] = Padlock.getPlugin().getMessageManager().getLang(LangPath.SIGN_MORE_USERS); } //got everything. Update. diff --git a/src/main/java/de/greensurvivors/padlock/impl/signdata/SignLock.java b/src/main/java/de/greensurvivors/padlock/impl/signdata/SignLock.java index c5f5f32..ef5529a 100644 --- a/src/main/java/de/greensurvivors/padlock/impl/signdata/SignLock.java +++ b/src/main/java/de/greensurvivors/padlock/impl/signdata/SignLock.java @@ -4,12 +4,9 @@ import com.google.gson.reflect.TypeToken; import de.greensurvivors.padlock.Padlock; import de.greensurvivors.padlock.PadlockAPI; -import de.greensurvivors.padlock.config.MessageManager; -import de.greensurvivors.padlock.impl.MiscUtils; import de.greensurvivors.padlock.impl.dataTypes.LazySignProperties; import de.greensurvivors.padlock.impl.openabledata.Openables; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; +import de.greensurvivors.padlock.language.LangPath; import org.apache.commons.collections4.set.ListOrderedSet; import org.bukkit.*; import org.bukkit.block.Block; @@ -50,7 +47,7 @@ public class SignLock { * @param sign sign to set invalid */ public static void setInvalid(@NotNull Sign sign) { - sign.getSide(Side.FRONT).line(0, Padlock.getPlugin().getMessageManager().getLang(MessageManager.LangPath.SIGN_LINE_INVALID)); + sign.getSide(Side.FRONT).line(0, Padlock.getPlugin().getMessageManager().getLang(LangPath.SIGN_LINE_INVALID)); sign.update(); } @@ -62,14 +59,6 @@ public static boolean isLockSign(@NotNull Sign sign) { return (SignAccessType.getAccessTypeFromComp(sign.getSide(Side.FRONT).line(0)) != null) || SignAccessType.getAccessType(sign, true) != null; } - /** - * Checks if a sign is a legacy additional sign of the Lockette(pro) plugin by comparing against the configured line in the lang file. - */ - @Deprecated(forRemoval = true) - public static boolean isAdditionalSign(@NotNull Sign sign) { - return Padlock.getPlugin().getMessageManager().isLegacySignComp(sign.getSide(Side.FRONT).line(0), MessageManager.LangPath.LEGACY_ADDITIONAL_SIGN); - } - /** * Check if a given uuid is a registered owner uuid of a lock sign. */ @@ -121,119 +110,6 @@ public static boolean isMember(final @NotNull Sign sign, final @NotNull UUID uui return set; } - /** - * Tries to get an offline player from a line of a sign - * by checking if it against possible other sign lines and if it could be a username at all. - * If everything checks out, get the offline player from bukkit and pray to god we got the right player. - * - * @return the offline player we found or null if this wasn't a valid name after all - */ - @Deprecated(forRemoval = true) - private static @Nullable OfflinePlayer tryGetPlayerJustFromNameComp(@NotNull Component component) { - String line = PlainTextComponentSerializer.plainText().serialize(component); - - if (SignAccessType.isLegacyEveryOneComp(component) || SignTimer.getTimerFromComp(component) != null) { - return null; - } else if (MiscUtils.isUserName(line)) { - return Bukkit.getOfflinePlayer(line); - } - - return null; - } - - /** - * transfer all data (should be only members, really) of an additional sign to the main lock sign - * and set the legacy sign invalid. - * Note: this depends on UUID being enabled on the former Lockette plugin. - */ - @Deprecated(forRemoval = true) - public static void updateSignFromAdditional(@NotNull Sign main, @NotNull Sign additional) { - Padlock.getPlugin().getLogger().fine("updating additional sign at " + additional.getLocation()); - PlainTextComponentSerializer plainedText = PlainTextComponentSerializer.plainText(); - for (int i = 1; i <= 3; i++) { - String line = plainedText.serialize(additional.getSide(Side.FRONT).line(i)); - - if (line.contains("#")) { - String[] splitted = line.split("#", 2); - - if (splitted[1].length() == 36) { // uuid valid check - try { - addPlayer(main, false, Bukkit.getOfflinePlayer(UUID.fromString(splitted[1]))); - } catch (IllegalArgumentException ignored) { - } - } - } else { - OfflinePlayer maybePlayer = tryGetPlayerJustFromNameComp(additional.getSide(Side.FRONT).line(i)); - - if (maybePlayer != null) { - addPlayer(main, false, maybePlayer); - } - } - } - - setInvalid(additional); - } - - /** - * updates a legacy lock sign by reading all the owner / member uuids and storing it into - * the PersistentDataContainer of this sign. - * Will not update the Display of the sign afterwarts to not overwrite other unimported data like timers - */ - @Deprecated(forRemoval = true) - public static void updateLegacyLock(@NotNull Sign sign) { - PersistentDataContainer container = sign.getPersistentDataContainer(); - - ListOrderedSet owners = container.get(storedOwnersUUIDKey, uuidSetDataType); - if (owners == null) { - owners = new ListOrderedSet<>(); - } - ListOrderedSet members = container.get(storedMembersUUIDKey, uuidSetDataType); - if (members == null) { - members = new ListOrderedSet<>(); - } - - PlainTextComponentSerializer plainedText = PlainTextComponentSerializer.plainText(); - - for (int i = 1; i <= 3; i++) { - String line = plainedText.serialize(sign.getSide(Side.FRONT).line(i)); - - if (line.contains("#")) { - String[] splitted = line.split("#", 2); - - if (splitted[1].length() == 36) { // uuid valid check - if (i == 1) { - owners.add(splitted[1]); - } else { - members.add(splitted[1]); - } - } - } else { - OfflinePlayer maybePlayer = tryGetPlayerJustFromNameComp(sign.getSide(Side.FRONT).line(i)); - - if (maybePlayer != null) { - if (i == 1) { - owners.add(maybePlayer.getUniqueId().toString()); - } else { - members.add(maybePlayer.getUniqueId().toString()); - } - } - } - } - - sign.getPersistentDataContainer().set(storedOwnersUUIDKey, uuidSetDataType, owners); - sign.getPersistentDataContainer().set(storedMembersUUIDKey, uuidSetDataType, members); - sign.update(); - } - - /** - * checks if the sign needs an update by checking - * if it has the owner set stored in its getPersistentDataContainer. - */ - @Deprecated(forRemoval = true) - public static boolean isLegacySign(@NotNull Sign sign) { - return !sign.getPersistentDataContainer().has(storedOwnersUUIDKey, uuidSetDataType); - } - /** * Add a player as owner (true) or member (false) of this lock sign. *

diff --git a/src/main/java/de/greensurvivors/padlock/impl/signdata/SignPasswords.java b/src/main/java/de/greensurvivors/padlock/impl/signdata/SignPasswords.java index 8104ae2..42acb0d 100644 --- a/src/main/java/de/greensurvivors/padlock/impl/signdata/SignPasswords.java +++ b/src/main/java/de/greensurvivors/padlock/impl/signdata/SignPasswords.java @@ -3,11 +3,12 @@ import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.impl.dataTypes.CacheSet; +import de.greensurvivors.padlock.language.LangPath; import de.mkammerer.argon2.Argon2Advanced; import de.mkammerer.argon2.Argon2Factory; import de.mkammerer.argon2.Argon2Version; +import net.kyori.adventure.text.logger.slf4j.ComponentLogger; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.NamespacedKey; @@ -23,7 +24,6 @@ import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.TimeUnit; -import java.util.logging.Logger; public final class SignPasswords { private final static NamespacedKey passwordHashKey = new NamespacedKey(Padlock.getPlugin(), "passwordHash"); @@ -59,9 +59,9 @@ public final class SignPasswords { * @throws IllegalArgumentException if the Argon2Parameters are invalid */ private static boolean matches(char[] rawPassword, String encodedOtherPassword) { - Logger logger = Padlock.getPlugin().getLogger(); + final @NotNull ComponentLogger logger = Padlock.getPlugin().getComponentLogger(); - String[] parts = encodedOtherPassword.split("\\$"); + final @NotNull String @NotNull [] parts = encodedOtherPassword.split("\\$"); if (parts.length >= 4) { int currentIndex = 1; final Argon2Advanced argon2 = switch (parts[currentIndex++]) { @@ -71,7 +71,7 @@ private static boolean matches(char[] rawPassword, String encodedOtherPassword) default -> null; }; if (argon2 != null) { - String currentPart = parts[currentIndex++]; + @NotNull String currentPart = parts[currentIndex++]; Argon2Version argon2Version = null; if (currentPart.startsWith("v=")) { int expectedVersion = Integer.parseInt(currentPart.substring(2)); @@ -108,28 +108,28 @@ private static boolean matches(char[] rawPassword, String encodedOtherPassword) return argon2.verifyAdvanced(iterations, memory, parallelism, encodedPassword, salt, null, null, expectedHash.length, argon2Version, expectedHash); } else { - logger.warning("Invalid parallelity parameter: " + performanceParams[1]); + logger.warn("Invalid parallelity parameter: " + performanceParams[1]); } } else { - logger.warning("Invalid iterations parameter: " + performanceParams[1]); + logger.warn("Invalid iterations parameter: " + performanceParams[1]); } } else { - logger.warning("Invalid memory parameter: " + performanceParams[0]); + logger.warn("Invalid memory parameter: " + performanceParams[0]); } } else { - logger.warning("Amount of performance parameters invalid: " + currentPart); + logger.warn("Amount of performance parameters invalid: " + currentPart); } } else { - logger.warning("invalid argon2 Version: " + currentPart); + logger.warn("invalid argon2 Version: " + currentPart); } } else { - logger.warning("invalid argon2 Version: " + currentPart); + logger.warn("invalid argon2 Version: " + currentPart); } } else { - logger.warning("Invalid algorithm type: " + parts[1]); + logger.warn("Invalid algorithm type: " + parts[1]); } } else { - logger.warning("Invalid encoded Argon2-hash: " + encodedOtherPassword); + logger.warn("Invalid encoded Argon2-hash: " + encodedOtherPassword); } return false; } @@ -151,10 +151,10 @@ private static void stopWaiting(@NotNull UUID uuid, @NotNull Location location) public static boolean isOnCooldown(@NotNull UUID uuid, @NotNull Location location) { if (waitForCmdGettingProcessed.contains(uuid)) { - Cache<@NotNull Location, @NotNull Integer> triesAtLocations = triesLast3Minutes.get(uuid); + final @Nullable Cache<@NotNull Location, @NotNull Integer> triesAtLocations = triesLast3Minutes.get(uuid); if (triesAtLocations != null) { - Integer tries = triesAtLocations.getIfPresent(location); + @Nullable Integer tries = triesAtLocations.getIfPresent(location); if (tries != null) { return tries > 10; @@ -165,10 +165,10 @@ public static boolean isOnCooldown(@NotNull UUID uuid, @NotNull Location locatio } public static void countTriesUp(@NotNull UUID uuid, @NotNull Location location) { - Cache<@NotNull Location, @NotNull Integer> triesAtLocations = triesLast3Minutes.get(uuid); + final @Nullable Cache<@NotNull Location, @NotNull Integer> triesAtLocations = triesLast3Minutes.get(uuid); if (triesAtLocations != null) { - Integer tries = triesAtLocations.getIfPresent(location); + @Nullable Integer tries = triesAtLocations.getIfPresent(location); if (tries != null) { tries++; @@ -183,12 +183,12 @@ public static void countTriesUp(@NotNull UUID uuid, @NotNull Location location) } } - private static void cacheAccess(@NotNull UUID uuid, @NotNull Location location) { + private static void cacheAccess(final @NotNull UUID uuid, final @NotNull Location location) { accessMap.computeIfAbsent(uuid, ignored -> new CacheSet<>(Caffeine.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES).maximumSize(20).build())); accessMap.get(uuid).add(location); } - public static boolean hasStillAccess(@NotNull UUID uuid, @NotNull Location location) { + public static boolean hasStillAccess(final @NotNull UUID uuid, final @NotNull Location location) { CacheSet cache = accessMap.get(uuid); if (cache != null) { @@ -202,13 +202,13 @@ public static boolean hasStillAccess(@NotNull UUID uuid, @NotNull Location locat return false; } - public static boolean needsPasswordAccess(@NotNull Sign sign) { + public static boolean needsPasswordAccess(final @NotNull Sign sign) { final String hash = sign.getPersistentDataContainer().get(passwordHashKey, PersistentDataType.STRING); return (hash != null && !hash.isEmpty()); } - public static void checkPasswordAndGrandAccess(@NotNull Sign sign, @NotNull Player player, char @NotNull [] password) { + public static void checkPasswordAndGrandAccess(final @NotNull Sign sign, final @NotNull Player player, final char @NotNull [] password) { final String hash = sign.getPersistentDataContainer().get(passwordHashKey, PersistentDataType.STRING); if (hash != null) { @@ -217,14 +217,14 @@ public static void checkPasswordAndGrandAccess(@NotNull Sign sign, @NotNull Play if (doesMatch) { cacheAccess(player.getUniqueId(), sign.getLocation()); - Padlock.getPlugin().getMessageManager().sendLang(player, MessageManager.LangPath.PASSWORD_ACCESS_GRANTED); + Padlock.getPlugin().getMessageManager().sendLang(player, LangPath.PASSWORD_ACCESS_GRANTED); } else { SignPasswords.countTriesUp(player.getUniqueId(), sign.getLocation()); - Padlock.getPlugin().getMessageManager().sendLang(player, MessageManager.LangPath.PASSWORD_WRONG_PASSWORD); + Padlock.getPlugin().getMessageManager().sendLang(player, LangPath.PASSWORD_WRONG_PASSWORD); } }); } else { // no password was set - Padlock.getPlugin().getMessageManager().sendLang(player, MessageManager.LangPath.PASSWORD_ACCESS_GRANTED); + Padlock.getPlugin().getMessageManager().sendLang(player, LangPath.PASSWORD_ACCESS_GRANTED); } // yes I know I invalidate the arrays at multiple places, but in terms of password safety it's better to be double and tripple safe then sorry. @@ -232,13 +232,13 @@ public static void checkPasswordAndGrandAccess(@NotNull Sign sign, @NotNull Play } // yes I know I invalidate the arrays at multiple places, but in terms of password safety it's better to be double and tripple safe then sorry. - private static void clearArray(char @Nullable [] newPassword) { + private static void clearArray(final char @Nullable [] newPassword) { if (newPassword != null) { Arrays.fill(newPassword, '*'); } } - public static void removeAccessOfLoc(@NotNull Location location) { + public static void removeAccessOfLoc(final @NotNull Location location) { for (CacheSet cache : accessMap.values()) { cache.remove(location); } @@ -251,7 +251,7 @@ public static void setPassword(final @NotNull Sign sign, final @NotNull Player p dataContainer.remove(passwordHashKey); sign.update(); removeAccessOfLoc(sign.getLocation()); - Padlock.getPlugin().getMessageManager().sendLang(player, MessageManager.LangPath.SET_PASSWORD_REMOVE_SUCCESS); + Padlock.getPlugin().getMessageManager().sendLang(player, LangPath.SET_PASSWORD_REMOVE_SUCCESS); SignPasswords.stopWaiting(player.getUniqueId(), sign.getLocation()); SignDisplay.updateDisplay(sign); @@ -264,7 +264,7 @@ public static void setPassword(final @NotNull Sign sign, final @NotNull Player p dataContainer.set(passwordHashKey, PersistentDataType.STRING, newHash); sign.update(); removeAccessOfLoc(sign.getLocation()); - Padlock.getPlugin().getMessageManager().sendLang(player, MessageManager.LangPath.SET_PASSWORD_SUCCESS); + Padlock.getPlugin().getMessageManager().sendLang(player, LangPath.SET_PASSWORD_SUCCESS); cacheAccess(player.getUniqueId(), sign.getLocation()); SignPasswords.stopWaiting(player.getUniqueId(), sign.getLocation()); @@ -297,7 +297,7 @@ public static void setPassword(final @NotNull Sign sign, final @NotNull Player p * {@link Argon2Parameters}. * @throws IllegalArgumentException if the encoded hash is malformed */ - private static String encode(final char[] password) { + private static @NotNull String encode(final char[] password) { final Argon2Advanced argon2 = Argon2Factory.createAdvanced(Argon2Factory.Argon2Types.ARGON2id); final byte[] salt = argon2.generateSalt(SALT_LENGTH); final byte[] hash = argon2.rawHash(ITERATIONS, MEMORY, PARALLELISM, password, StandardCharsets.UTF_8, salt); diff --git a/src/main/java/de/greensurvivors/padlock/impl/signdata/SignTimer.java b/src/main/java/de/greensurvivors/padlock/impl/signdata/SignTimer.java index 83aacf8..2c9b3a6 100644 --- a/src/main/java/de/greensurvivors/padlock/impl/signdata/SignTimer.java +++ b/src/main/java/de/greensurvivors/padlock/impl/signdata/SignTimer.java @@ -1,28 +1,24 @@ package de.greensurvivors.padlock.impl.signdata; import de.greensurvivors.padlock.Padlock; -import de.greensurvivors.padlock.PadlockAPI; -import de.greensurvivors.padlock.config.MessageManager; import de.greensurvivors.padlock.impl.MiscUtils; +import de.greensurvivors.padlock.language.LangPath; +import de.greensurvivors.padlock.language.PlaceHolder; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import org.bukkit.NamespacedKey; import org.bukkit.block.Sign; -import org.bukkit.block.sign.Side; import org.bukkit.persistence.PersistentDataType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.time.Duration; -import java.util.Set; -import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; -import java.util.stream.Collectors; /** - * A timer on a lock determines how many milliseconds it takes until the openable, + * A timer on a lock determines how long it takes until the openable, * the sign is attached to, toggles. * With other words, setting a timer on a sign of a chest does nothing but display a * somewhat pretty number. @@ -37,18 +33,13 @@ public class SignTimer { * casing should not matter and the placeholder should be a * group of any number to receive later */ - @Deprecated(forRemoval = true) - private final static Set legacyPatterns = Padlock.getPlugin().getMessageManager(). - getNakedLegacyText(MessageManager.LangPath.LEGACY_TIMER_SIGN).stream(). - map(s -> Pattern.compile(s.replace("[", "\\[(?i)"). - replace("