diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3016ed4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,104 @@ +# ---> JetBrains +# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio + +*.iml + +## Directory-based project format: +.idea/ +# if you remove the above rule, at least ignore the following: + +# User-specific stuff: +# .idea/workspace.xml +# .idea/tasks.xml +# .idea/dictionaries + +# Sensitive or high-churn files: +# .idea/dataSources.ids +# .idea/dataSources.xml +# .idea/sqlDataSources.xml +# .idea/dynamic.xml +# .idea/uiDesigner.xml + +# Gradle: +# .idea/gradle.xml +# .idea/libraries + +# Mongo Explorer plugin: +# .idea/mongoSettings.xml + +## File-based project format: +*.ipr +*.iws + +## Plugin-specific files: + +# IntelliJ +/out/ + +# mpeltonen/sbt-idea plugin +.idea_modules/ + +# JIRA plugin +atlassian-ide-plugin.xml + +# Crashlytics plugin (for Android Studio and IntelliJ) +com_crashlytics_export_strings.xml +crashlytics.properties +crashlytics-build.properties + +# ---> Eclipse +*.pydevproject +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.settings/ +.loadpath + +# Eclipse Core +.project + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# JDT-specific (Eclipse Java Development Tools) +.classpath + +# Java annotation processor (APT) +.factorypath + +# PDT-specific +.buildpath + +# sbteclipse plugin +.target + +# TeXlipse plugin +.texlipse + +# ---> Maven +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties + +# ---> Gradle +.gradle +build/ +target +run/ diff --git a/README.md b/README.md index 5a33340..5d92c83 100644 --- a/README.md +++ b/README.md @@ -1 +1 @@ -Rifle's Chairs +Rifle's Chairs - Greensurvivors Fork diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..eda991d --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,62 @@ +plugins { + `java-library` + id("io.papermc.paperweight.userdev") version "1.7.7" + id("xyz.jpenilla.run-paper") version "2.3.1" // Adds runServer and runMojangMappedServer tasks for testing +} + +group = "com.rifledluffy.chairs" +version = "7.0.1-SNAPSHOT" +description = "Chairs but Rifle's way." +val mcVersion by extra("1.21.3") +paperweight.reobfArtifactConfiguration = io.papermc.paperweight.userdev.ReobfArtifactConfiguration.MOJANG_PRODUCTION + +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(21)) +} + +repositories { + mavenLocal() + + //paper + maven { + url = uri("https://repo.papermc.io/repository/maven-public/") + } + //world guard + maven { + url = uri("https://maven.enginehub.org/repo/") + } +} + +dependencies { + paperweight.paperDevBundle("$mcVersion-R0.1-SNAPSHOT") + compileOnly("com.sk89q.worldguard:worldguard-bukkit:7.1.0-SNAPSHOT") + compileOnly("org.jetbrains:annotations:26.0.1") + implementation("com.github.ben-manes.caffeine:caffeine:3.1.8") // caches + implementation("org.bstats:bstats-bukkit:3.1.0") +} + +tasks { + compileJava { + 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(21) + } + + processResources { + filteringCharset = Charsets.UTF_8.name() // We want UTF-8 for everything + + expand("version" to project.version, + "description" to project.description, + "apiVersion" to mcVersion) + } + + runServer { + downloadPlugins { + modrinth("worldguard", "7.0.13-beta-1") + modrinth("worldedit", "Bu1zaaoc") + } + } +} \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..e2847c8 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..f5feea6 --- /dev/null +++ b/gradlew @@ -0,0 +1,252 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..fa39065 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,8 @@ +pluginManagement { + repositories { + gradlePluginPortal() + } +} + + +rootProject.name = "RFChairs" diff --git a/src/com/rifledluffy/chairs/ChairManager.java b/src/com/rifledluffy/chairs/ChairManager.java deleted file mode 100644 index f2c2bd4..0000000 --- a/src/com/rifledluffy/chairs/ChairManager.java +++ /dev/null @@ -1,629 +0,0 @@ -package com.rifledluffy.chairs; - -import com.rifledluffy.chairs.chairs.BlockFilter; -import com.rifledluffy.chairs.chairs.Chair; -import com.rifledluffy.chairs.config.ConfigManager; -import com.rifledluffy.chairs.events.ChairCheckEvent; -import com.rifledluffy.chairs.events.ChairLeaveEvent; -import com.rifledluffy.chairs.events.ChairReplaceEvent; -import com.rifledluffy.chairs.events.ChairSitEvent; -import com.rifledluffy.chairs.events.ChairTossEvent; -import com.rifledluffy.chairs.messages.MessageConstruct; -import com.rifledluffy.chairs.messages.MessageEvent; -import com.rifledluffy.chairs.messages.MessageType; -import com.rifledluffy.chairs.utility.Util; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPistonExtendEvent; -import org.bukkit.event.block.BlockPistonRetractEvent; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.PlayerDeathEvent; -import org.bukkit.event.player.PlayerGameModeChangeEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.event.player.PlayerJoinEvent; -import org.bukkit.event.player.PlayerMoveEvent; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.projectiles.ProjectileSource; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; -import org.spigotmc.event.entity.EntityDismountEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import java.util.stream.Collectors; - -public class ChairManager implements Listener { - - private RFChairs plugin = RFChairs.getPlugin(RFChairs.class); - private ConfigManager configManager = plugin.getConfigManager(); - private FileConfiguration config = configManager.getConfig(); - - private Map chairMap = new HashMap<>(); - public List chairs = new ArrayList<>(); - private List fakeSeats = new ArrayList<>(); - private List leaving = new ArrayList<>(); - private List orienting = new ArrayList<>(); - private Map tossed = new HashMap<>(); - - public List toggled = new ArrayList<>(); - - private PotionEffect regenEffect = new PotionEffect(PotionEffectType.REGENERATION, 655200, config.getInt("regen-potency", 0), false, false); - private boolean regenWhenSitting; - - //Update related - private boolean disableCurrentUpdate; - private boolean disableUpdates; - - //Kick them off their seat if they take damage - private boolean canLaunch; - - //Toss them off their seat if they take damage - private boolean canToss; - //The minimum damage needed for a player to be tossed - private double minDamage; - - //Toss Configuration - private boolean faceAttacker; - private double tossVelocity; - private boolean scaleVelocity; - private double scaleAmount; - - //Maximum amount of items on hand that they can have when trying to sit - private int maxItemSit; - private double maxDistance; - private boolean checkForSigns; - private boolean priorityIfHasPerm; - private boolean trapSeats; - private boolean requireEmptyHand; - - //Mostly buggy, probably going to remove soon. - private boolean exitWhereFacing; - - public Vector stairSeatingPosition; - public Vector slabSeatingPosition; - public Vector carpetSeatingPosition; - - private List disabledWorlds = new ArrayList<>(); - - public void reload(RFChairs plugin) { - configManager = plugin.getConfigManager(); - config = configManager.getConfig(); - - regenEffect = new PotionEffect(PotionEffectType.REGENERATION, 655200, config.getInt("regen-potency", 0), false, false); - regenWhenSitting = config.getBoolean("regen-when-sitting", true); - - disableCurrentUpdate = config.getBoolean("disable-update-message-if-on-latest", false); - disableUpdates = config.getBoolean("disable-update-messages", false); - - faceAttacker = config.getBoolean("face-attacker-when-ejected", false); - canToss = config.getBoolean("toss-player", false); - tossVelocity = config.getDouble("toss-velocity", 0.5D); - scaleVelocity = config.getBoolean("scale-toss-velocity", true); - scaleAmount = config.getDouble("velocity-scale-factor", 2D); - canLaunch = config.getBoolean("eject-player-on-damage", true); - minDamage = config.getDouble("minimum-eject-damage", 2D); - exitWhereFacing = config.getBoolean("exit-seat-where-facing", false); - maxItemSit = config.getInt("max-item-count-to-sit", -1); - maxDistance = config.getDouble("max-distance", 2D); - checkForSigns = config.getBoolean("require-signs-at-end", false); - priorityIfHasPerm = config.getBoolean("priority-on-if-has-perm", true); - trapSeats = config.getBoolean("allow-trap-door-chairs", true); - requireEmptyHand = config.getBoolean("require-empty-hand", false); - - try { - String[] vectorString = Objects.requireNonNull(config.getString("stair-seating-position", "0.5,0.3,0.5")).split(","); - stairSeatingPosition = new Vector(Double.parseDouble(vectorString[0]), Double.parseDouble(vectorString[1]), Double.parseDouble(vectorString[2])); - } catch (NumberFormatException e) { - stairSeatingPosition = new Vector(0.5D,0.3D,0.5); - } - - try { - String[] vectorString = Objects.requireNonNull(config.getString("slab-seating-position", "0.5,0.3,0.5")).split(","); - slabSeatingPosition = new Vector(Double.parseDouble(vectorString[0]), Double.parseDouble(vectorString[1]), Double.parseDouble(vectorString[2])); - } catch (NumberFormatException e) { - slabSeatingPosition= new Vector(0.5,0.3D,0.5); - } - - try { - String[] vectorString = Objects.requireNonNull(config.getString("carpet-seating-position", "0.5,-0.15,0.5")).split(","); - carpetSeatingPosition = new Vector(Double.parseDouble(vectorString[0]), Double.parseDouble(vectorString[1]), Double.parseDouble(vectorString[2])); - } catch (NumberFormatException e) { - carpetSeatingPosition= new Vector(0.5,-0.15D,0.5); - } - - disabledWorlds = config.getStringList("disabled-worlds").stream() - .map(Bukkit::getWorld) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - } - - @EventHandler - public void onChairSit(ChairSitEvent event) { - Chair chair = event.getChair(); - if (chair == null) return; - if (chair.getLocation() == null) return; - if (event.getPlayer() == null) return; - - if (plugin.hasWorldGuard()) if (!plugin.getWorldGuardManager().validateSeating(chair, event.getPlayer())) { - Util.callEvent(new MessageEvent(MessageType.WORLDGUARD, event.getPlayer())); - return; - } - - Player player = event.getPlayer(); - - if (Util.playerIsSeated(player.getUniqueId(), chairMap)) clearPlayer(player); - boolean done = sitPlayer(chair, player); - if (!done) return; - chairs.add(chair); - chairMap.put(player.getUniqueId(), chair); - if (regenWhenSitting) player.addPotionEffect(regenEffect); - } - - @EventHandler - public void onChairLeave(ChairLeaveEvent event) { - Chair chair = event.getChair(); - if (chair == null) return; - if (chair.getLocation() == null) return; - - Block block = chair.getLocation().getBlock(); - Player player = event.getPlayer(); - boolean flag = event.exitWhereFacing(); - - Location exit = block.getLocation(); - - clearPlayer(player); - player.removePotionEffect(PotionEffectType.REGENERATION); - if (flag) exit = findExitPoint(player.getLocation(), block).getLocation(); - if (Util.surroundedBlock(block) || Util.nearLiquid(player.getLocation().getBlock())) exit = block.getRelative(BlockFace.UP).getLocation(); - exit.setDirection(player.getEyeLocation().getDirection()); - exit.add(0.5,0,0.5); - player.teleport(exit); - if (!flag) { - Vector v = player.getEyeLocation().getDirection(); - v.setY(0); - v.normalize(); - v.setY(1); - player.setVelocity(v.multiply(0.25)); - } - } - - @EventHandler - public void onToss(ChairTossEvent event) { - Chair chair = event.getChair(); - if (chair == null) return; - if (chair.getLocation() == null) return; - - Block block = chair.getBlock(); - Player player = event.getPlayer(); - Entity attacker = event.getAttacker(); - TargetInfo info = event.getInfo(); - boolean silent = event.isSilent(); - - ChairLeaveEvent leaveEvent = new ChairLeaveEvent(chair, player, false); - Util.callEvent(leaveEvent); - - if (!silent) { - MessageEvent messageEvent; - MessageEvent otherEvent = null; - if (attacker instanceof Player) { - Player playerEntity = (Player) attacker; - if (info != null && !info.isSprinting()) messageEvent = new MessageEvent(MessageType.TOSSED, MessageConstruct.DEFENSIVE, player, playerEntity); - else messageEvent = new MessageEvent(MessageType.TOSSEDSPEED, MessageConstruct.DEFENSIVE, player, playerEntity); - - if (info != null && !info.isSprinting()) otherEvent = new MessageEvent(MessageType.TOSSING, MessageConstruct.OFFENSIVE, playerEntity, player); - else otherEvent = new MessageEvent(MessageType.TOSSINGSPEED, MessageConstruct.OFFENSIVE, playerEntity, player); - } - else messageEvent = new MessageEvent(MessageType.TOSSED, player, attacker); - Util.callEvent(messageEvent); - if (otherEvent != null) Util.callEvent(otherEvent); - } - - if (canToss) ejectPlayer(block, player, attacker); - } - - @EventHandler - public void onChairReplace(ChairReplaceEvent event) { - Chair chair = event.getChair(); - if (chair == null) return; - if (chair.getLocation() == null) return; - - Block block = chair.getBlock(); - Player player = event.getPlayer(); - Player seated = event.getReplaced(); - - if (player.getUniqueId() == seated.getUniqueId()) return; - - ChairTossEvent tossEvent = new ChairTossEvent(chair, seated, player, null, true); - Util.callEvent(tossEvent); - - MessageEvent tossed = new MessageEvent(MessageType.TOSSED, MessageConstruct.DEFENSIVE, seated, player); - Util.callEvent(tossed); - - ChairSitEvent sitEvent = new ChairSitEvent(new Chair(player, block.getLocation()), player); - Util.callEvent(sitEvent); - - MessageEvent tosser = new MessageEvent(MessageType.TOSSING, MessageConstruct.OFFENSIVE, player, seated); - Util.callEvent(tosser); - } - - @EventHandler - public void onChairCheck(ChairCheckEvent event) { - Player player = event.getPlayer(); - ItemStack item = player.getInventory().getItemInMainHand(); - Block block = event.getBlock(); - - if (!player.hasPermission("rfchairs.use")) { - Util.callEvent(new MessageEvent(MessageType.NOPERMS, player)); - return; - } - - if (player.getLocation().distance(block.getLocation().add(0.5, 0, 0.5)) >= maxDistance) { - Util.callEvent(new MessageEvent(MessageType.TOOFAR, player)); - return; - } - - if (maxItemSit > 0 && item.getAmount() > maxItemSit) { - Util.callEvent(new MessageEvent(MessageType.TOOMANYITEMS, player)); - return; - } - - if (!Util.blockIsChair(block, chairs)) { - ChairSitEvent sitEvent = new ChairSitEvent(new Chair(player, block.getLocation()), player); - Util.callEvent(sitEvent); - } else { - Chair chair = Util.getChairFromBlock(block, chairs); - if (chair == null) return; - if (chair.getFakeSeat() != null && chair.getFakeSeat().getPassengers().size() == 0) { - chair.setPlayer(player); - chair.getFakeSeat().addPassenger(player); - if (regenWhenSitting) player.addPotionEffect(regenEffect); - return; - } - if (player.hasPermission("rfchairs.priority") && priorityIfHasPerm) { - ChairReplaceEvent replaceEvent = new ChairReplaceEvent(chair, chair.getPlayer(), player); - Util.callEvent(replaceEvent); - return; - } - if (chair.getPlayer() == null) return; - if (player.getUniqueId().equals(chair.getPlayer().getUniqueId())) { - orienting.add(player.getUniqueId()); - Location loc = chair.getFakeSeat().getLocation(); - loc.setDirection(player.getEyeLocation().getDirection().setY(0)); - chair.getFakeSeat().remove(); - ArmorStand newFakeSeat = Util.generateFakeSeatDir(chair, loc.getDirection()); - chair.setFakeSeat(newFakeSeat); - chair.getFakeSeat().addPassenger(player); - } else { - MessageEvent occupied = new MessageEvent(MessageType.OCCUPIED, MessageConstruct.OFFENSIVE, player, chair.getPlayer()); - Util.callEvent(occupied); - } - } - } - - @EventHandler - public void onRightClick(PlayerInteractEvent event) { - if (disabledWorlds.size() > 0 && disabledWorlds.contains(event.getPlayer().getWorld())) return; - if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; - if (event.getPlayer().isSneaking()) return; - if (event.getHand() != EquipmentSlot.HAND) return; - if (toggled.contains(event.getPlayer().getUniqueId())) return; - - Block block = event.getClickedBlock(); - Player player = event.getPlayer(); - ItemStack item = event.getItem(); - if (block == null) return; - - if (requireEmptyHand && item != null) return; - - if (item != null && item.getType() != Material.AIR) { - if (item.getType().isBlock()) return; - } - - if (!BlockFilter.isStairsBlock(block.getType()) - && !BlockFilter.isCarpetBlock(block.getType()) - && !BlockFilter.isSlabBlock(block.getType())) return; - - if (BlockFilter.isStairsBlock(block.getType())) { - if (!Util.validStair(block)) return; - else { - if (checkForSigns) { - if (!Util.validCouch(block)) { - if (!trapSeats) return; - if (!Util.throneChair(block)) { - Util.callEvent(new MessageEvent(MessageType.NOSIGNS, player)); - return; - } - } else if (block.getRelative(BlockFace.UP).getType() != Material.AIR) return; - } - if (trapSeats && block.getRelative(BlockFace.UP).getType() != Material.AIR) { - if (!Util.throneChair(block)) return; - } - } - } else if (block.getRelative(BlockFace.UP).getType() != Material.AIR) return; - - if (BlockFilter.isSlabBlock(block.getType())) if (!Util.validSlab(block)) return; - - if (BlockFilter.isCarpetBlock(block.getType())) if (!Util.validCarpet(block)) return; - - if (event.getBlockFace() == BlockFace.DOWN) return; - - if (!player.hasPermission("rfchairs.use")) { - Util.callEvent(new MessageEvent(MessageType.NOPERMS, player)); - return; - } - - Util.callEvent(new ChairCheckEvent(block, player)); - } - - @EventHandler - public void onChangeGameMode(PlayerGameModeChangeEvent event) { - if (event.isCancelled()) return; - GameMode gameMode = event.getNewGameMode(); - Chair chair = chairMap.get(event.getPlayer().getUniqueId()); - if (gameMode == GameMode.SPECTATOR && chair != null) clearChair(chair); - } - - @EventHandler - public void onDismount(EntityDismountEvent event) { - if (!(event.getEntity() instanceof Player)) return; - Player player = (Player) event.getEntity(); - Chair chair = chairMap.get(player.getUniqueId()); - event.getDismounted(); - if (chair == null || event.getDismounted().getType() != EntityType.ARMOR_STAND) return; - if (leaving.contains(player.getUniqueId())) return; - if (orienting.contains(player.getUniqueId())) { - orienting.remove(player.getUniqueId()); - return; - } - if (tossed.containsKey(player.getUniqueId())) { - TargetInfo info = tossed.get(player.getUniqueId()); - Entity attacker = info.getEntity(); - if (info.hasSource() && info.livingSource()) attacker = info.getLivingSource(); - - ChairTossEvent tossEvent = new ChairTossEvent(chairMap.get(player.getUniqueId()), player, attacker, info, false); - Util.callEvent(tossEvent); - tossed.remove(player.getUniqueId()); - return; - } - leaving.add(player.getUniqueId()); - } - - @EventHandler - public void onMove(PlayerMoveEvent event) { - Player player = event.getPlayer(); - if (leaving.contains(player.getUniqueId())) { - ChairLeaveEvent leaveEvent = new ChairLeaveEvent(chairMap.get(player.getUniqueId()), player, exitWhereFacing); - Util.callEvent(leaveEvent); - leaving.remove(player.getUniqueId()); - } - } - - @EventHandler - public void takeDamage(EntityDamageByEntityEvent event) { - if (event.isCancelled()) return; - if (!(event.getEntity() instanceof Player)) return; - - Player player = (Player) event.getEntity(); - Entity attacker = event.getDamager(); - ProjectileSource source = null; - if (attacker instanceof Projectile) source = ((Projectile) attacker).getShooter(); - Chair chair = chairMap.get(player.getUniqueId()); - if (chair == null) return; - - if (event.getDamage() >= minDamage && canLaunch) { - TargetInfo info; - if (source == null) info = new TargetInfo(attacker, event.getDamage()); - else info = new TargetInfo(source, attacker, event.getDamage()); - tossed.put(player.getUniqueId(), info); - if (chair.getFakeSeat() != null) chair.getFakeSeat().removePassenger(player); - } - } - - @EventHandler - public void onBlockBreak(BlockBreakEvent event) { - if (event.isCancelled()) return; - chairs.stream() - .filter(Objects::nonNull) - .filter(c -> c.getLocation() != null) - .filter(c -> Util.samePosition(event.getBlock(), c.getBlock())) - .findAny() - .ifPresent(c -> { - if (!event.getPlayer().hasPermission("rfchairs.break")) event.setCancelled(true); - }); - } - - @EventHandler(priority = EventPriority.LOWEST) - public void quit(PlayerQuitEvent event) { - Player player = event.getPlayer(); - Chair chair = chairMap.get(player.getUniqueId()); - ChairLeaveEvent leaveEvent = new ChairLeaveEvent(chair, player, exitWhereFacing); - Util.callEvent(leaveEvent); - } - - @EventHandler - public void pistonExtend(BlockPistonExtendEvent event) { - for (Block block : event.getBlocks()) { - for (Chair chair: chairs) { - if (chair == null) continue; - if (chair.getLocation() == null) continue; - if (Util.samePosition(block, chair.getBlock())) { - event.setCancelled(true); - break; - } - } - } - } - - @EventHandler - public void pistonRetract(BlockPistonRetractEvent event) { - for (Block block : event.getBlocks()) { - for (Chair chair: chairs) { - if (chair == null) continue; - if (chair.getLocation() == null) continue; - if (Util.samePosition(block, chair.getBlock())) { - event.setCancelled(true); - break; - } - } - } - } - - @EventHandler - public void onDeath(PlayerDeathEvent event) { - Player player = event.getEntity(); - Chair chair = chairMap.get(player.getUniqueId()); - ChairLeaveEvent leaveEvent = new ChairLeaveEvent(chair, player); - Util.callEvent(leaveEvent); - } - - /* - * Sitting and Ejection Methods - */ - - private boolean sitPlayer(Chair chair, Player player) { - if (player == null) return false; - if (chair == null || chair.isOccupied()) return false; - - ArmorStand fakeSeat = chair.getFakeSeat(); - if (fakeSeat == null) fakeSeat = Util.generateFakeSeat(chair); - - fakeSeat.addPassenger(player); - chair.setFakeSeat(fakeSeat); - fakeSeats.add(fakeSeat.getUniqueId().toString()); - configManager.getData().set("UUIDs", fakeSeats); - return true; - } - - private void ejectPlayer(Block block, Player player, Entity entity) { - Block exit = block; - - if (exitWhereFacing) exit = findExitPoint(entity.getLocation(), block); - - Location exitLoc = exit.getLocation().add(0.5,0.5,0.5); - - if (!canToss) return; - - if (!faceAttacker) { - exitLoc.setPitch(player.getLocation().getPitch()); - exitLoc.setYaw(player.getLocation().getYaw()); - } else { - exitLoc.setDirection(Util.getVectorDir(player.getLocation(), entity.getLocation())); - } - - if (tossVelocity != 0) { - double finalVelocity = tossVelocity; - if (scaleVelocity && entity instanceof Player) { - if (((Player)entity).isSprinting()) finalVelocity = tossVelocity * scaleAmount; - } - player.setVelocity(exitLoc.getDirection().multiply(finalVelocity)); - } - } - - private Block findExitPoint(Location entity, Block block) { - Block blockToCheck = Util.getBlockFromDirection(block, Util.getCardinalDirection(entity)); - boolean foundValidExit = Util.canFitPlayer(blockToCheck) && Util.safePlace(blockToCheck); - - String[] directions = {"north", "east", "south", "west"}; - for (String direction: directions) { - if (foundValidExit) break; - blockToCheck = Util.getBlockFromDirection(block, direction); - foundValidExit = Util.canFitPlayer(blockToCheck) && Util.safePlace(blockToCheck); - } - if (!foundValidExit) blockToCheck = block.getRelative(BlockFace.UP); - return blockToCheck; - } - - /* - * Cleaning and Clearing - */ - - void saveToggled() { - List ids = new ArrayList<>(); - if (toggled == null || toggled.size() == 0) configManager.getData().set("Toggled", new ArrayList()); - for (UUID id : toggled) ids.add(id.toString()); - plugin.getServer().getLogger().info("[RFChairs] Saving " + ids.size() + " Players that had toggled off."); - configManager.getData().set("Toggled", ids); - } - - void loadToggled() { - List toggled = configManager.getData().getStringList("Toggled"); - if (toggled.size() == 0) return; - plugin.getServer().getLogger().info("[RFChairs] " + toggled.size() + " Players had toggled off. Adding Them..."); - - toggled.stream() - .map(UUID::fromString) - .forEach(id -> this.toggled.add(id)); - - configManager.getData().set("Toggled", new ArrayList()); - } - - void shutdown() { - clearChairs(); - clearFakeSeats(); - } - - private void clearChair(Chair chair) { - if (chair == null) return; - if (chair.getPlayer() != null) chair.getPlayer().removePotionEffect(PotionEffectType.REGENERATION); - chair.clear(); - } - - private void clearChairs() { - for (Chair chair: chairs) clearChair(chair); - } - - private void clearPlayer(Player player) { - Chair chair = chairMap.get(player.getUniqueId()); - if (chair == null) return; - chairMap.remove(player.getUniqueId()); - chairs.remove(chair); - chair.clear(); - } - - public void clearFakeSeats() { - for (Chair chair : chairs) clearChair(chair); - } - - public void clearFakeSeatsFromFile(JavaPlugin plugin) { - List fakes = configManager.getData().getStringList("UUIDs"); - int leftoverFakes = fakes.size(); - if (leftoverFakes >= 1) { - plugin.getServer().getLogger().info("[RFChairs] Detected " + fakes.size() + " leftover seats! Removing..."); - for (String fake: fakes) { - UUID id = UUID.fromString(fake); - Entity armorStand = plugin.getServer().getEntity(id); - if (armorStand == null) continue; - armorStand.remove(); - } - configManager.getData().set("UUIDs", new ArrayList()); - } else { - plugin.getServer().getLogger().info("[RFChairs] No fake seats remaining! Proceeding"); - } - } - -} diff --git a/src/com/rifledluffy/chairs/ConfigManager.java b/src/com/rifledluffy/chairs/ConfigManager.java deleted file mode 100644 index 84d113a..0000000 --- a/src/com/rifledluffy/chairs/ConfigManager.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.rifledluffy.chairs; - -import java.io.File; -import java.io.IOException; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.plugin.java.JavaPlugin; - -public class ConfigManager { - - private JavaPlugin plugin = RFChairs.getPlugin(RFChairs.class); - - /* - * Configuration Files - */ - - FileConfiguration config; - File configFile; - - FileConfiguration fake; - File fakeFile; - - public void setup() { - configFile = new File(plugin.getDataFolder(), "config.yml"); - config = plugin.getConfig(); - config.options().copyDefaults(true); - saveConfig(); - - if (!plugin.getDataFolder().exists()) { - plugin.getDataFolder().mkdir(); - } - - fakeFile = new File(plugin.getDataFolder(), "fakes.yml"); - - if (!fakeFile.exists()) { - try { - fakeFile.createNewFile(); - } - catch (IOException e) { - Bukkit.getServer().getLogger().info("[Rifle's Chairs] Could not create fakes.yml!"); - } - } - - fake = YamlConfiguration.loadConfiguration(fakeFile); - } - - public FileConfiguration getData() { - return fake; - } - - public void saveData() { - try { - fake.save(fakeFile); - } - catch (IOException e) { - Bukkit.getServer().getLogger().info("[Rifle's Chairs] Could not save fakes.yml!"); - } - } - - public void reloadData() { - fake = YamlConfiguration.loadConfiguration(fakeFile); - } - - public FileConfiguration getConfig() { - return config; - } - - public void saveConfig() { - try { - config.save(configFile); - } - catch (IOException e) { - Bukkit.getServer().getLogger().info("[Rifle's Chairs] Could not save config.yml!"); - } - } - - public void reloadConfig() { - config = YamlConfiguration.loadConfiguration(configFile); - } - - public PluginDescriptionFile getDesc() { - return plugin.getDescription(); - } -} diff --git a/src/com/rifledluffy/chairs/MessageManager.java b/src/com/rifledluffy/chairs/MessageManager.java deleted file mode 100644 index f85343e..0000000 --- a/src/com/rifledluffy/chairs/MessageManager.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.rifledluffy.chairs; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.scheduler.BukkitRunnable; - -import com.rifledluffy.chairs.config.ConfigManager; -import com.rifledluffy.chairs.messages.MessageConstruct; -import com.rifledluffy.chairs.messages.MessageEvent; -import com.rifledluffy.chairs.messages.MessageType; -import com.rifledluffy.chairs.messages.Messages; -import com.rifledluffy.chairs.utility.Util; - -public class MessageManager implements Listener { - - private RFChairs plugin = RFChairs.getPlugin(RFChairs.class); - private ConfigManager configManager = plugin.getConfigManager(); - public FileConfiguration messages = configManager.getMessages(); - private boolean allowMessages; - private int tempMuteDuration; - - public List muted = new ArrayList(); - private List tempMute = new ArrayList(); - - public void reload(RFChairs plugin) { - configManager = plugin.getConfigManager(); - messages = configManager.getMessages(); - allowMessages = configManager.getConfig().getBoolean("allow-custom-messages", true); - tempMuteDuration = messages.getInt("temp-mute-duration", 0); - } - - private void tempMute(Player player) { - int duration = tempMuteDuration; - tempMute.add(player.getUniqueId()); - BukkitRunnable runnable = new BukkitRunnable() { - @Override - public void run() { - if (tempMuted(player)) tempMute.remove(player.getUniqueId()); - } - }; - runnable.runTaskLater(plugin, duration); - } - - private boolean tempMuted(Player player) { - return tempMute.contains(player.getUniqueId()); - } - - @EventHandler - public void onMessage(MessageEvent event) { - Player player = event.getPlayer(); - if (tempMute.contains(player.getUniqueId())) event.setCancelled(true); - if (event.isCancelled()) return; - if (tempMuteDuration > 0) tempMute(player); - if (allowMessages && !muted.contains(player.getUniqueId())) { - String string = processString(event); - if (!string.isEmpty()) player.sendMessage(string); - } - } - - private String processString(MessageEvent event) { - MessageType type = event.getType(); - MessageConstruct construct = event.getConstruct(); - String string; - - String stringOutput = Messages.getMessage(type); - if (stringOutput == null) { - string = Messages.getDefault(type); - } else { - string = stringOutput; - } - - string = messages.getString(string); - - String finalString = ""; - - if (construct == MessageConstruct.SINGLE) finalString = Util.replaceMessage(event.getPlayer(), string); - else if (construct == MessageConstruct.DEFENSIVE) finalString = Util.replaceMessage(event.getEntity(), event.getPlayer(), string); - else if (construct == MessageConstruct.OFFENSIVE && event.getEntity() instanceof Player) finalString = Util.replaceMessage(event.getPlayer(),(Player) event.getEntity(), string); - return finalString; - } - - void saveMuted() { - List ids = new ArrayList(); - if (muted == null || muted.size() == 0) configManager.getData().set("Muted", new ArrayList()); - for (UUID id : muted) ids.add(id.toString()); - plugin.getServer().getLogger().info("[RFChairs] Saving " + ids.size() + " Players that had events muted."); - configManager.getData().set("Muted", ids); - } - - void loadMuted() { - List muted = configManager.getData().getStringList("Muted"); - if (muted == null || muted.size() == 0) return; - plugin.getServer().getLogger().info("[RFChairs] " + muted.size() + " Players had events muted off. Adding Them..."); - for (String toggler : muted) { - UUID id = UUID.fromString(toggler); - this.muted.add(id); - } - configManager.getData().set("Muted", new ArrayList()); - } - -} diff --git a/src/com/rifledluffy/chairs/RFChairs.java b/src/com/rifledluffy/chairs/RFChairs.java deleted file mode 100644 index 5f55f69..0000000 --- a/src/com/rifledluffy/chairs/RFChairs.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.rifledluffy.chairs; - -import java.io.IOException; - -import org.bukkit.Bukkit; -import org.bukkit.plugin.java.JavaPlugin; - -import com.rifledluffy.chairs.chairs.BlockFilter; -import com.rifledluffy.chairs.command.CommandManager; -import com.rifledluffy.chairs.config.ConfigManager; -import com.rifledluffy.chairs.managers.WorldGuardManager; -import com.rifledluffy.chairs.metrics.MetricsLite; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -public class RFChairs extends JavaPlugin { - - private static RFChairs instance; - public CommandManager commandManager; - public ConfigManager cfgManager; - public ChairManager chairManager; - public MessageManager messageManager; - public WorldGuardManager worldGuardManager; - - @Override - public void onLoad() { - setInstance(this); - loadWorldGuard(); - } - - private void loadWorldGuard() { - try { - Class.forName("com.sk89q.worldguard.WorldGuard"); - Class.forName("com.sk89q.worldedit.WorldEdit"); - Class.forName("com.sk89q.worldedit.math.BlockVector3"); - worldGuardManager = new WorldGuardManager(); - worldGuardManager.setup(); - getLogger().info("Found WorldGuard && WorldEdit! Applying Custom Flag..."); - } catch (ClassNotFoundException e) { - getLogger().info("Missing either WorldGuard or WorldEdit! Disabling Custom Flag Features..."); - getLogger().info("Latest WorldGuard/WorldEdit features could be missing. Please Update!"); - } - - if (worldGuardManager != null) worldGuardManager.register(); - } - - @Override - public void onEnable() { - - @SuppressWarnings("unused") - MetricsLite metrics = new MetricsLite(this); - - commandManager = new CommandManager(); - commandManager.setup(); - - loadConfigManager(); - - chairManager = new ChairManager(); - chairManager.clearFakeSeatsFromFile(this); - chairManager.loadToggled(); - - messageManager = new MessageManager(); - messageManager.loadMuted(); - - BlockFilter.reload(); - chairManager.reload(this); - messageManager.reload(this); - getServer().getPluginManager().registerEvents(chairManager, this); - getServer().getPluginManager().registerEvents(messageManager, this); - - getLogger().info("Rifle's Chairs has been enabled!"); - } - - @Override - public void onDisable() { - chairManager.saveToggled(); - messageManager.saveMuted(); - - chairManager.shutdown(); - - getLogger().info("Saving Configuration Files!"); - cfgManager.saveData(); - - Bukkit.getOnlinePlayers().forEach(p -> { - PotionEffect regen = p.getPotionEffect(PotionEffectType.REGENERATION); - if (regen == null) return; - if (regen.getDuration() > 1000) p.removePotionEffect(PotionEffectType.REGENERATION); - }); - - getLogger().info("Rifle's Chairs has been disabled!"); - } - - public void loadConfigManager() { - cfgManager = new ConfigManager(); - try { - cfgManager.setup(); - } catch (IOException e) { - e.printStackTrace(); - } - cfgManager.reloadConfig(); - } - - public ConfigManager getConfigManager() { - return cfgManager; - } - - public void setConfigManager(ConfigManager configManager) { - this.cfgManager = configManager; - } - - public static RFChairs getInstance() { - return instance; - } - - public WorldGuardManager getWorldGuardManager() { - return this.worldGuardManager; - } - - private static void setInstance(RFChairs instance) { - RFChairs.instance = instance; - } - - public void log(String string) { - getLogger().info(string); - } - - boolean hasWorldGuard() { - return worldGuardManager != null; - } - -} diff --git a/src/com/rifledluffy/chairs/TargetInfo.java b/src/com/rifledluffy/chairs/TargetInfo.java deleted file mode 100644 index cd1f28b..0000000 --- a/src/com/rifledluffy/chairs/TargetInfo.java +++ /dev/null @@ -1,61 +0,0 @@ -package com.rifledluffy.chairs; - -import org.bukkit.block.Block; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.projectiles.BlockProjectileSource; -import org.bukkit.projectiles.ProjectileSource; - -public class TargetInfo { - - Player player; - Entity attacker; - ProjectileSource source; - Double damage; - boolean sprinting = false; - - TargetInfo(ProjectileSource source, Entity attacker, Double damage) { - this.source = source; - this.attacker = attacker; - this.damage = damage; - } - - TargetInfo(Entity attacker, Double damage) { - this.source = null; - if (attacker instanceof Player) { - player = (Player) attacker; - sprinting = player.isSprinting(); - } - this.attacker = attacker; - this.damage = damage; - } - - Entity getEntity() { - return attacker; - } - - LivingEntity getLivingSource() { - return (LivingEntity) source; - } - - Block getBlockSource() { - return ((BlockProjectileSource)source).getBlock(); - } - - Double getDamage() { - return damage; - } - - boolean isSprinting() { - return this.sprinting; - } - - boolean hasSource() { - return source != null; - } - - boolean livingSource() { - return source != null && source instanceof LivingEntity; - } -} diff --git a/src/com/rifledluffy/chairs/chairs/BlockFilter.java b/src/com/rifledluffy/chairs/chairs/BlockFilter.java deleted file mode 100644 index c222bf2..0000000 --- a/src/com/rifledluffy/chairs/chairs/BlockFilter.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.rifledluffy.chairs.chairs; - -import com.rifledluffy.chairs.RFChairs; -import org.bukkit.Material; -import org.bukkit.configuration.file.FileConfiguration; - -import java.util.*; - -public class BlockFilter { - - private static Set whitelist, blacklist; - private static Set carpetTypeSet, slabTypeSet, stairsTypeSet; - - static { - carpetTypeSet = EnumSet.noneOf(Material.class); - slabTypeSet = EnumSet.noneOf(Material.class); - stairsTypeSet = EnumSet.noneOf(Material.class); - - Arrays.stream(Material.values()) - .filter(m -> !m.name().startsWith("LEGACY_")) - .forEach(m -> { - String name = m.name(); - if (name.endsWith("_CARPET")) - carpetTypeSet.add(m); - else if (name.endsWith("_SLAB")) - slabTypeSet.add(m); - else if (name.endsWith("_STAIRS")) - stairsTypeSet.add(m); - }); - } - - public static void reload() { - FileConfiguration config = RFChairs.getInstance().getConfig(); - whitelist = new HashSet<>(config.getStringList("allowed-chairs")); - blacklist = new HashSet<>(config.getStringList("blacklisted-chairs")); - } - - public static boolean isWhitelisted(Material type, String category) { - if (whitelist.contains("ALL_" + category)) return true; - return whitelist.contains(type.name()); - } - - public static boolean isBlacklisted(Material type, String category) { - if (blacklist.contains("ALL_" + category)) return true; - return blacklist.contains(type.name()); - } - - // validate - - public static boolean validateCarpet(Material type) { - return isWhitelisted(type, "CARPETS") && !isBlacklisted(type, "CARPET"); - } - - public static boolean validateSlab(Material type) { - return isWhitelisted(type, "SLABS") && !isBlacklisted(type, "SLAB"); - } - - public static boolean validateStairs(Material type) { - return isWhitelisted(type, "STAIRS") && !isBlacklisted(type, "STAIRS"); - } - - // check - - public static boolean isCarpetBlock(Material type) { - return carpetTypeSet.contains(type); - } - - public static boolean isSlabBlock(Material type) { - return slabTypeSet.contains(type); - } - - public static boolean isStairsBlock(Material type) { - return stairsTypeSet.contains(type); - } -} diff --git a/src/com/rifledluffy/chairs/chairs/Chair.java b/src/com/rifledluffy/chairs/chairs/Chair.java deleted file mode 100644 index 6653b99..0000000 --- a/src/com/rifledluffy/chairs/chairs/Chair.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.rifledluffy.chairs.chairs; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.BlockState; -import org.bukkit.block.data.BlockData; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Player; -import org.bukkit.material.Stairs; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitRunnable; - -import com.rifledluffy.chairs.RFChairs; -import com.rifledluffy.chairs.utility.Util; - -public class Chair { - - private BukkitRunnable clear; - private int clearID; - - private Location location; - private Block chair; - private ArmorStand fakeSeat = null; - private Player player; - - public Chair(Player player, Location location) { - this.location = location; - this.player = player; - this.chair = location.getBlock(); - - clear = new BukkitRunnable() { - - @Override - public void run() { - if (fakeSeat == null) { - clear(); - return; - } - if (fakeSeat.getPassengers().size() == 0) clear(); - } - - }; - clearID = clear.runTaskTimer(RFChairs.getInstance(), 20, 20).getTaskId(); - } - - /* - * Getters - */ - - public ArmorStand getFakeSeat() { - return fakeSeat; - } - - public Player getPlayer() { - return player; - } - - public Block getBlock() { - return location.getBlock(); - } - - public BlockState getBlockState() { - return chair.getState(); - } - - public BlockData getBlockData() { - return chair.getState().getBlockData(); - } - - public BlockFace getFacing() { - if (!BlockFilter.isStairsBlock(chair.getType())) return null; - return ((Stairs)chair.getState().getData()).getFacing(); - } - - public Location getLocation() { - return location; - } - - public boolean isOccupied() { - return !(fakeSeat == null) && !fakeSeat.isEmpty(); - } - - /* - * Setters - */ - - public void setPlayer(Player player) { - this.player = player; - } - - /* - * Methods - */ - - public void setFakeSeat(ArmorStand armorStand) { - fakeSeat = armorStand; - } - - public void clear() { - if (fakeSeat != null) fakeSeat.remove(); - if (player != null) player.removePotionEffect(PotionEffectType.REGENERATION); - chair = null; - location = null; - fakeSeat = null; - player = null; - if (Bukkit.getScheduler().isCurrentlyRunning(clearID)) clear.cancel(); - } - -} diff --git a/src/com/rifledluffy/chairs/command/CommandManager.java b/src/com/rifledluffy/chairs/command/CommandManager.java deleted file mode 100644 index b6c50b4..0000000 --- a/src/com/rifledluffy/chairs/command/CommandManager.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.rifledluffy.chairs.command; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; - -import com.rifledluffy.chairs.RFChairs; -import com.rifledluffy.chairs.command.commands.HelpCommand; -import com.rifledluffy.chairs.command.commands.InfoCommand; -import com.rifledluffy.chairs.command.commands.MuteCommand; -import com.rifledluffy.chairs.command.commands.ReloadCommand; -import com.rifledluffy.chairs.command.commands.ResetCommand; -import com.rifledluffy.chairs.command.commands.SubCommand; -import com.rifledluffy.chairs.command.commands.ToggleCommand; - -import net.md_5.bungee.api.ChatColor; - -public class CommandManager implements CommandExecutor { - - private ArrayList commands = new ArrayList(); - private RFChairs plugin = RFChairs.getInstance(); - - public CommandManager(){} - - //Sub Commands - public String main = "rfchairs"; - public String help = "help"; - public String info = "info"; - public String reload = "reload"; - public String reset = "reset"; - public String toggle = "toggle"; - public String mute = "mute"; - - public void setup() { - plugin.getCommand(main).setExecutor(this); - - this.commands.add(new HelpCommand()); - this.commands.add(new InfoCommand()); - this.commands.add(new ReloadCommand()); - this.commands.add(new ResetCommand()); - this.commands.add(new ToggleCommand()); - this.commands.add(new MuteCommand()); - } - - public boolean onCommand(CommandSender sender, Command command, String s, String[] args) { - - if (command.getName().equalsIgnoreCase(main)) { - if (args.length == 0) { - sender.sendMessage(ChatColor.RED + "Missing Arguments. Type /rfchairs help for info"); - return true; - } - - SubCommand target = this.get(args[0]); - - if (target == null) { - sender.sendMessage(ChatColor.RED + "Invalid subcommand"); - return true; - } - - ArrayList arrayList = new ArrayList(); - - arrayList.addAll(Arrays.asList(args)); - arrayList.remove(0); - - try{ - target.onCommand(sender,args); - }catch (Exception e){ - sender.sendMessage(ChatColor.RED + "An error has occurred."); - - e.printStackTrace(); - } - } - - return true; - } - - private SubCommand get(String name) { - Iterator subcommands = this.commands.iterator(); - - while (subcommands.hasNext()) { - SubCommand sc = (SubCommand) subcommands.next(); - - if (sc.name().equalsIgnoreCase(name)) { - return sc; - } - - String[] aliases; - int length = (aliases = sc.aliases()).length; - - for (int var5 = 0; var5 < length; ++var5) { - String alias = aliases[var5]; - if (name.equalsIgnoreCase(alias)) { - return sc; - } - - } - } - return null; -} - -} diff --git a/src/com/rifledluffy/chairs/command/commands/CommandManager.java b/src/com/rifledluffy/chairs/command/commands/CommandManager.java deleted file mode 100644 index 2c87600..0000000 --- a/src/com/rifledluffy/chairs/command/commands/CommandManager.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.rifledluffy.chairs.command.commands; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; - -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import com.rifledluffy.chairs.RFChairs; - -import net.md_5.bungee.api.ChatColor; - -public class CommandManager implements CommandExecutor { - - private ArrayList commands = new ArrayList(); - private RFChairs plugin = RFChairs.getInstance(); - - public CommandManager(){} - - //Sub Commands - public String main = "rfchairs"; - public String info = "info"; - public String reload = "reload"; - public String reset = "reset"; - - public void setup() { - plugin.getCommand(main).setExecutor(this); - - this.commands.add(new HelpCommand()); - this.commands.add(new InfoCommand()); - this.commands.add(new ReloadCommand()); - this.commands.add(new ResetCommand()); - } - - public boolean onCommand(CommandSender sender, Command command, String s, String[] args) { - - if (!(sender instanceof Player)) { - sender.sendMessage(ChatColor.RED + "Only players can use commands for this plugin."); - return true; - } - - Player player = (Player) sender; - - if (command.getName().equalsIgnoreCase(main)) { - if (args.length == 0) { - player.sendMessage(ChatColor.RED + "Missing Arguments. Type /rfchairs help for info"); - return true; - } - - SubCommand target = this.get(args[0]); - - if (target == null) { - player.sendMessage(ChatColor.RED + "Invalid subcommand"); - return true; - } - - ArrayList arrayList = new ArrayList(); - - arrayList.addAll(Arrays.asList(args)); - arrayList.remove(0); - - try{ - target.onCommand(player,args); - }catch (Exception e){ - player.sendMessage(ChatColor.RED + "An error has occurred."); - - e.printStackTrace(); - } - } - - return true; - } - - private SubCommand get(String name) { - Iterator subcommands = this.commands.iterator(); - - while (subcommands.hasNext()) { - SubCommand sc = (SubCommand) subcommands.next(); - - if (sc.name().equalsIgnoreCase(name)) { - return sc; - } - - String[] aliases; - int length = (aliases = sc.aliases()).length; - - for (int var5 = 0; var5 < length; ++var5) { - String alias = aliases[var5]; - if (name.equalsIgnoreCase(alias)) { - return sc; - } - - } - } - return null; - } - - } diff --git a/src/com/rifledluffy/chairs/command/commands/HelpCommand.java b/src/com/rifledluffy/chairs/command/commands/HelpCommand.java deleted file mode 100644 index 657607f..0000000 --- a/src/com/rifledluffy/chairs/command/commands/HelpCommand.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.rifledluffy.chairs.command.commands; - -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.Player; - -import com.rifledluffy.chairs.RFChairs; - -import net.md_5.bungee.api.ChatColor; - -public class HelpCommand extends SubCommand { - - private RFChairs plugin = RFChairs.getInstance(); - - @Override - public void onCommand(CommandSender sender, String[] args) { - if (sender instanceof Player) { - onCommand((Player) sender, args); - } else if (sender instanceof ConsoleCommandSender) { - onCommand((ConsoleCommandSender) sender, args); - } else return; - } - - @Override - public void onCommand(ConsoleCommandSender sender, String[] args) { - sender.sendMessage(ChatColor.YELLOW + "--------------" + ChatColor.DARK_GRAY + "[" + ChatColor.DARK_GREEN + "Available Commands" + ChatColor.DARK_GRAY + "]" + ChatColor.YELLOW + "--------------"); - sender.sendMessage(ChatColor.GOLD + "/rfc or /rfchairs" + ChatColor.GRAY + " is the main command"); - sender.sendMessage(ChatColor.GOLD + "/rfchairs reload" + ChatColor.DARK_GRAY + " | " + ChatColor.GRAY + "Reloads the config and messages [Console Can Cast]"); - sender.sendMessage(ChatColor.GOLD + "/rfchairs reset" + ChatColor.DARK_GRAY + " | " + ChatColor.GRAY + "Resets all chairs [Console Can Cast]"); - sender.sendMessage(ChatColor.GOLD + "/rfchairs toggle" + ChatColor.DARK_GRAY + " | " + ChatColor.GRAY + "Disables seating on chairs for the executor [Player Only]"); - sender.sendMessage(ChatColor.GOLD + "/rfchairs mute" + ChatColor.DARK_GRAY + " | " + ChatColor.GRAY + "Mutes event messages from the plugin for the executor [Player Only]"); - sender.sendMessage(ChatColor.GOLD + "/rfchairs update" + ChatColor.DARK_GRAY + " | " + ChatColor.GRAY + "Runs a check on their current version [Console Can Cast]"); - sender.sendMessage(ChatColor.YELLOW + "------------------------------------------------"); - } - - @Override - public void onCommand(Player player, String[] args) { - player.sendMessage(ChatColor.YELLOW + "--------------" + ChatColor.DARK_GRAY + "[" + ChatColor.DARK_GREEN + "Available Commands" + ChatColor.DARK_GRAY + "]" + ChatColor.YELLOW + "--------------"); - player.sendMessage(ChatColor.GOLD + "/rfc or /rfchairs" + ChatColor.GRAY + " is the main command"); - player.sendMessage(ChatColor.GOLD + "/rfchairs reload" + ChatColor.DARK_GRAY + " | " + ChatColor.GRAY + "Reloads the config and messages"); - player.sendMessage(ChatColor.GOLD + "/rfchairs reset" + ChatColor.DARK_GRAY + " | " + ChatColor.GRAY + "Resets all chairs"); - player.sendMessage(ChatColor.GOLD + "/rfchairs toggle" + ChatColor.DARK_GRAY + " | " + ChatColor.GRAY + "Disables seating on chairs for the executor"); - player.sendMessage(ChatColor.GOLD + "/rfchairs mute" + ChatColor.DARK_GRAY + " | " + ChatColor.GRAY + "Mutes event messages from the plugin for the executor"); - player.sendMessage(ChatColor.GOLD + "/rfchairs update" + ChatColor.DARK_GRAY + " | " + ChatColor.GRAY + "Runs a check on their current version"); - player.sendMessage(ChatColor.YELLOW + "------------------------------------------------"); - } - - @Override - public String name() { - return plugin.commandManager.help; - } - - @Override - public String info() { - return null; - } - - @Override - public String[] aliases() { - return new String[0]; - } -} \ No newline at end of file diff --git a/src/com/rifledluffy/chairs/command/commands/InfoCommand.java b/src/com/rifledluffy/chairs/command/commands/InfoCommand.java deleted file mode 100644 index b1435b5..0000000 --- a/src/com/rifledluffy/chairs/command/commands/InfoCommand.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.rifledluffy.chairs.command.commands; - -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.Player; - -import com.rifledluffy.chairs.RFChairs; - -public class InfoCommand extends SubCommand { - - private RFChairs plugin = RFChairs.getInstance(); - - @Override - public void onCommand(CommandSender sender, String[] args) { - if (sender instanceof Player) { - onCommand((Player) sender, args); - } else if (sender instanceof ConsoleCommandSender) { - onCommand((ConsoleCommandSender) sender, args); - } else return; - } - - @Override - public void onCommand(ConsoleCommandSender sender, String[] args) { - sender.sendMessage("§cOnly players can use commands for this plugin."); - } - - @Override - public void onCommand(Player player, String[] args) { - } - - @Override - public String name() { - return plugin.commandManager.info; - } - - @Override - public String info() { - return ""; - } - - @Override - public String[] aliases() { - return new String[0]; - } - -} \ No newline at end of file diff --git a/src/com/rifledluffy/chairs/command/commands/MuteCommand.java b/src/com/rifledluffy/chairs/command/commands/MuteCommand.java deleted file mode 100644 index c93036a..0000000 --- a/src/com/rifledluffy/chairs/command/commands/MuteCommand.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.rifledluffy.chairs.command.commands; - -import java.util.List; -import java.util.UUID; - -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.Player; - -import com.rifledluffy.chairs.MessageManager; -import com.rifledluffy.chairs.RFChairs; -import com.rifledluffy.chairs.messages.MessageEvent; -import com.rifledluffy.chairs.messages.MessageType; -import com.rifledluffy.chairs.utility.Util; - -public class MuteCommand extends SubCommand { - - private RFChairs plugin = RFChairs.getInstance(); - - @Override - public void onCommand(CommandSender sender, String[] args) { - if (sender instanceof Player) { - onCommand((Player) sender, args); - } else if (sender instanceof ConsoleCommandSender) { - onCommand((ConsoleCommandSender) sender, args); - } else return; - } - - @Override - public void onCommand(ConsoleCommandSender sender, String[] args) { - sender.sendMessage("�cOnly players can use commands for this plugin."); - } - - @Override - public void onCommand(Player player, String[] args) { - MessageManager messageManager = plugin.messageManager; - List muted = messageManager.muted; - String message; - if (!player.hasPermission("rfchairs.mute")) return; - if (muted.contains(player.getUniqueId())) { - String string = messageManager.messages.getString("mute-message-enabled", "&8[&6Rifle's Chairs&8] &7Event Messaging is now &cDisabled!"); - message = Util.replaceMessage(player, string); - player.sendMessage(message); - muted.remove(player.getUniqueId()); - } - else { - String string = messageManager.messages.getString("mute-message-disabled", "&8[&6Rifle's Chairs&8] &7Event Messaging is now &aEnabled!"); - message = Util.replaceMessage(player, string); - player.sendMessage(message); - muted.add(player.getUniqueId()); - } - } - - @Override - public String name() { - return plugin.commandManager.mute; - } - - @Override - public String info() { - return ""; - } - - @Override - public String[] aliases() { - return new String[0]; - } - -} diff --git a/src/com/rifledluffy/chairs/command/commands/ReloadCommand.java b/src/com/rifledluffy/chairs/command/commands/ReloadCommand.java deleted file mode 100644 index 082a544..0000000 --- a/src/com/rifledluffy/chairs/command/commands/ReloadCommand.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.rifledluffy.chairs.command.commands; - -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.Player; - -import com.rifledluffy.chairs.RFChairs; -import com.rifledluffy.chairs.chairs.BlockFilter; -import com.rifledluffy.chairs.config.ConfigManager; - -import net.md_5.bungee.api.ChatColor; - -public class ReloadCommand extends SubCommand { - - private RFChairs plugin = RFChairs.getInstance(); - - @Override - public void onCommand(CommandSender sender, String[] args) { - if (sender instanceof Player) { - onCommand((Player) sender, args); - } else if (sender instanceof ConsoleCommandSender) { - onCommand((ConsoleCommandSender) sender, args); - } else return; - } - - @Override - public void onCommand(ConsoleCommandSender sender, String[] args) { - ConfigManager newConfig = plugin.getConfigManager(); - newConfig.reloadConfig(); - newConfig.reloadMessages(); - plugin.setConfigManager(newConfig); - plugin.chairManager.reload(plugin); - plugin.messageManager.reload(plugin); - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "Rifle's Chairs" + ChatColor.DARK_GRAY + "] " + ChatColor.GREEN + "Config Reloaded"); - } - - @Override - public void onCommand(Player player, String[] args) { - if (!player.hasPermission("rfchairs.reload") && !player.hasPermission("rfchairs.manage")) return; - ConfigManager newConfig = plugin.getConfigManager(); - newConfig.reloadConfig(); - newConfig.reloadMessages(); - plugin.setConfigManager(newConfig); - BlockFilter.reload(); - plugin.chairManager.reload(plugin); - plugin.messageManager.reload(plugin); - player.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "Rifle's Chairs" + ChatColor.DARK_GRAY + "] " + ChatColor.GREEN + "Config Reloaded"); - } - - @Override - public String name() { - return plugin.commandManager.reload; - } - - @Override - public String info() { - return "Reloads the config and messages"; - } - - @Override - public String[] aliases() { - return new String[0]; - } - -} diff --git a/src/com/rifledluffy/chairs/command/commands/ResetCommand.java b/src/com/rifledluffy/chairs/command/commands/ResetCommand.java deleted file mode 100644 index e68ac18..0000000 --- a/src/com/rifledluffy/chairs/command/commands/ResetCommand.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.rifledluffy.chairs.command.commands; - -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.Player; - -import com.rifledluffy.chairs.RFChairs; - -import net.md_5.bungee.api.ChatColor; - -public class ResetCommand extends SubCommand { - - private RFChairs plugin = RFChairs.getInstance(); - - @Override - public void onCommand(CommandSender sender, String[] args) { - if (sender instanceof Player) { - onCommand((Player) sender, args); - } else if (sender instanceof ConsoleCommandSender) { - onCommand((ConsoleCommandSender) sender, args); - } else return; - } - - @Override - public void onCommand(ConsoleCommandSender sender, String[] args) { - plugin.chairManager.clearFakeSeats(); - plugin.chairManager.clearFakeSeatsFromFile(plugin); - plugin.getLogger().info("Chairs Reset!"); - sender.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "Rifle's Chairs" + ChatColor.DARK_GRAY + "] " + ChatColor.GREEN + "Chairs Reset"); - } - - @Override - public void onCommand(Player player, String[] args) { - if (!player.hasPermission("rfchairs.reset") && !player.hasPermission("rfchairs.manage")) return; - plugin.chairManager.clearFakeSeats(); - plugin.chairManager.clearFakeSeatsFromFile(plugin); - plugin.getLogger().info("Chairs Reset!"); - player.sendMessage(ChatColor.DARK_GRAY + "[" + ChatColor.GOLD + "Rifle's Chairs" + ChatColor.DARK_GRAY + "] " + ChatColor.GREEN + "Chairs Reset"); - } - - @Override - public String name() { - return plugin.commandManager.reset; - } - - @Override - public String info() { - return "Resets all chairs"; - } - - @Override - public String[] aliases() { - return new String[0]; - } - -} \ No newline at end of file diff --git a/src/com/rifledluffy/chairs/command/commands/SubCommand.java b/src/com/rifledluffy/chairs/command/commands/SubCommand.java deleted file mode 100644 index 881fa20..0000000 --- a/src/com/rifledluffy/chairs/command/commands/SubCommand.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.rifledluffy.chairs.command.commands; - -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.Player; - -public abstract class SubCommand { - - /* - / args[0] args[1] - */ - - public SubCommand() {} - - public abstract void onCommand(CommandSender sender, String[] args); - - public abstract void onCommand(ConsoleCommandSender sender, String[] args); - - public abstract void onCommand(Player player, String[] args); - - public abstract String name(); - - public abstract String info(); - - public abstract String[] aliases(); -} diff --git a/src/com/rifledluffy/chairs/command/commands/ToggleCommand.java b/src/com/rifledluffy/chairs/command/commands/ToggleCommand.java deleted file mode 100644 index c04a575..0000000 --- a/src/com/rifledluffy/chairs/command/commands/ToggleCommand.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.rifledluffy.chairs.command.commands; - -import java.util.List; -import java.util.UUID; - -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.Player; - -import com.rifledluffy.chairs.MessageManager; -import com.rifledluffy.chairs.RFChairs; -import com.rifledluffy.chairs.messages.MessageEvent; -import com.rifledluffy.chairs.messages.MessageType; -import com.rifledluffy.chairs.utility.Util; - -public class ToggleCommand extends SubCommand { - - private RFChairs plugin = RFChairs.getInstance(); - - @Override - public void onCommand(CommandSender sender, String[] args) { - if (sender instanceof Player) { - onCommand((Player) sender, args); - } else if (sender instanceof ConsoleCommandSender) { - onCommand((ConsoleCommandSender) sender, args); - } else return; - } - - @Override - public void onCommand(ConsoleCommandSender sender, String[] args) { - sender.sendMessage("�cOnly players can use commands for this plugin."); - } - - @Override - public void onCommand(Player player, String[] args) { - MessageManager messageManager = plugin.messageManager; - List toggled = plugin.chairManager.toggled; - String message; - if (!player.hasPermission("rfchairs.toggle")) return; - if (toggled.contains(player.getUniqueId())) { - String string = messageManager.messages.getString("toggle-message-enabled", "&8[&6Rifle's Chairs&8] &7Seating is now &aEnabled!"); - message = Util.replaceMessage(player, string); - player.sendMessage(message); - toggled.remove(player.getUniqueId()); - } - else { - String string = messageManager.messages.getString("toggle-message-disabled", "&8[&6Rifle's Chairs&8] &7Seating is now &cDisabled!"); - message = Util.replaceMessage(player, string); - player.sendMessage(message); - toggled.add(player.getUniqueId()); - } - } - - @Override - public String name() { - return plugin.commandManager.toggle; - } - - @Override - public String info() { - return ""; - } - - @Override - public String[] aliases() { - return new String[0]; - } - -} diff --git a/src/com/rifledluffy/chairs/config/ConfigManager.java b/src/com/rifledluffy/chairs/config/ConfigManager.java deleted file mode 100644 index f3b269c..0000000 --- a/src/com/rifledluffy/chairs/config/ConfigManager.java +++ /dev/null @@ -1,117 +0,0 @@ -package com.rifledluffy.chairs.config; - -import java.io.File; -import java.io.IOException; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.PluginDescriptionFile; -import org.bukkit.plugin.java.JavaPlugin; - -import com.rifledluffy.chairs.RFChairs; - -public class ConfigManager { - - private JavaPlugin plugin = RFChairs.getPlugin(RFChairs.class); - - /* - * Configuration Files - */ - - FileConfiguration config; - File configFile; - - FileConfiguration fake; - File fakeFile; - - FileConfiguration message; - File messageFile; - - public void setup() throws IOException { - configFile = new File(plugin.getDataFolder(), "config.yml"); - config = plugin.getConfig(); - config.options().copyDefaults(true); - saveConfig(); - - if (!plugin.getDataFolder().exists()) { - plugin.getDataFolder().mkdir(); - } - - fakeFile = new File(plugin.getDataFolder(), "fakes.yml"); - - if (!fakeFile.exists()) { - try { - fakeFile.createNewFile(); - } - catch (IOException e) { - Bukkit.getServer().getLogger().info("[Rifle's Chairs] Could not create fakes.yml!"); - } - } - - messageFile = new File(plugin.getDataFolder(), "messages.yml"); - - if (!messageFile.exists()) { - messageFile.getParentFile().mkdirs(); - plugin.saveResource("messages.yml", false); - } - - fake = YamlConfiguration.loadConfiguration(fakeFile); - message = YamlConfiguration.loadConfiguration(messageFile); - } - - public FileConfiguration getData() { - return fake; - } - - public void saveData() { - try { - fake.save(fakeFile); - } - catch (IOException e) { - Bukkit.getServer().getLogger().info("[Rifle's Chairs] Could not save fakes.yml!"); - } - } - - public void reloadData() { - fake = YamlConfiguration.loadConfiguration(fakeFile); - } - - public FileConfiguration getMessages() { - return message; - } - - public void saveMessages() { - try { - message.save(messageFile); - } - catch (IOException e) { - plugin.getLogger().info("[Rifle's Chairs] Could not save messages.yml!"); - } - } - - public void reloadMessages() { - message = YamlConfiguration.loadConfiguration(messageFile); - } - - public FileConfiguration getConfig() { - return config; - } - - public void saveConfig() { - try { - config.save(configFile); - } - catch (IOException e) { - plugin.getLogger().info("[Rifle's Chairs] Could not save config.yml!"); - } - } - - public void reloadConfig() { - config = YamlConfiguration.loadConfiguration(configFile); - } - - public PluginDescriptionFile getDesc() { - return plugin.getDescription(); - } -} \ No newline at end of file diff --git a/src/com/rifledluffy/chairs/events/ChairCheckEvent.java b/src/com/rifledluffy/chairs/events/ChairCheckEvent.java deleted file mode 100644 index f04aa60..0000000 --- a/src/com/rifledluffy/chairs/events/ChairCheckEvent.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.rifledluffy.chairs.events; - -import org.bukkit.block.Block; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import com.rifledluffy.chairs.chairs.Chair; - -public class ChairCheckEvent extends Event { - - Chair chair; - Block block; - Player player; - - public ChairCheckEvent(Chair chair, Player player) { - this.chair = chair; - this.player = player; - } - - public ChairCheckEvent(Block block, Player player) { - this.block = block; - this.player = player; - } - - public Chair getChair() { - return this.chair; - } - - public Block getBlock() { - return this.block; - } - - public Player getPlayer() { - return this.player; - } - - private static final HandlerList handlers = new HandlerList(); - - @Override - public HandlerList getHandlers() { - return handlers; - } - - static public HandlerList getHandlerList() { - return handlers; - } -} diff --git a/src/com/rifledluffy/chairs/events/ChairLeaveEvent.java b/src/com/rifledluffy/chairs/events/ChairLeaveEvent.java deleted file mode 100644 index 720220b..0000000 --- a/src/com/rifledluffy/chairs/events/ChairLeaveEvent.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.rifledluffy.chairs.events; - -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import com.rifledluffy.chairs.chairs.Chair; - -public class ChairLeaveEvent extends Event { - - private Chair chair; - private Player player; - private boolean exitWhereFacing = false; - - public ChairLeaveEvent(Chair chair, Player player, boolean flag) { - this.chair = chair; - this.player = player; - this.exitWhereFacing = flag; - } - - public ChairLeaveEvent(Chair chair, Player player) { - this.chair = chair; - this.player = player; - } - - public Chair getChair() { - return this.chair; - } - - public Player getPlayer() { - return this.player; - } - - public boolean exitWhereFacing() { - return this.exitWhereFacing; - } - - private static final HandlerList handlers = new HandlerList(); - - @Override - public HandlerList getHandlers() { - return handlers; - } - - static public HandlerList getHandlerList() { - return handlers; - } -} diff --git a/src/com/rifledluffy/chairs/events/ChairReplaceEvent.java b/src/com/rifledluffy/chairs/events/ChairReplaceEvent.java deleted file mode 100644 index bc344fe..0000000 --- a/src/com/rifledluffy/chairs/events/ChairReplaceEvent.java +++ /dev/null @@ -1,43 +0,0 @@ -package com.rifledluffy.chairs.events; - -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import com.rifledluffy.chairs.chairs.Chair; - -public class ChairReplaceEvent extends Event { - - Chair chair; - Player replaced; - Player player; - - public ChairReplaceEvent(Chair chair, Player replaced, Player player) { - this.chair = chair; - this.replaced = replaced; - this.player = player; - } - - public Chair getChair() { - return this.chair; - } - - public Player getReplaced() { - return this.replaced; - } - - public Player getPlayer() { - return this.player; - } - - private static final HandlerList handlers = new HandlerList(); - - @Override - public HandlerList getHandlers() { - return handlers; - } - - static public HandlerList getHandlerList() { - return handlers; - } -} diff --git a/src/com/rifledluffy/chairs/events/ChairSitEvent.java b/src/com/rifledluffy/chairs/events/ChairSitEvent.java deleted file mode 100644 index 9266bc7..0000000 --- a/src/com/rifledluffy/chairs/events/ChairSitEvent.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.rifledluffy.chairs.events; - -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import com.rifledluffy.chairs.chairs.Chair; - -public class ChairSitEvent extends Event { - - Chair chair; - Player player; - - public ChairSitEvent(Chair chair, Player player) { - this.chair = chair; - this.player = player; - } - - public Chair getChair() { - return this.chair; - } - - public Player getPlayer() { - return this.player; - } - - private static final HandlerList handlers = new HandlerList(); - - @Override - public HandlerList getHandlers() { - return handlers; - } - - static public HandlerList getHandlerList() { - return handlers; - } -} diff --git a/src/com/rifledluffy/chairs/events/ChairTossEvent.java b/src/com/rifledluffy/chairs/events/ChairTossEvent.java deleted file mode 100644 index 0631297..0000000 --- a/src/com/rifledluffy/chairs/events/ChairTossEvent.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.rifledluffy.chairs.events; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import com.rifledluffy.chairs.TargetInfo; -import com.rifledluffy.chairs.chairs.Chair; - -public class ChairTossEvent extends Event { - - Chair chair; - Player player; - Entity attacker; - TargetInfo info; - boolean silent; - - public ChairTossEvent(Chair chair, Player player, Entity attacker, TargetInfo info, boolean flag) { - this.chair = chair; - this.player = player; - this.attacker = attacker; - this.info = info; - this.silent = flag; - } - - public Chair getChair() { - return this.chair; - } - - public Player getPlayer() { - return this.player; - } - - public Entity getAttacker() { - return this.attacker; - } - - public TargetInfo getInfo() { - return this.info; - } - - public boolean isSilent() { - return this.silent; - } - - private static final HandlerList handlers = new HandlerList(); - - @Override - public HandlerList getHandlers() { - return handlers; - } - - static public HandlerList getHandlerList() { - return handlers; - } -} diff --git a/src/com/rifledluffy/chairs/managers/GriefPreventionManager.java b/src/com/rifledluffy/chairs/managers/GriefPreventionManager.java deleted file mode 100644 index 415af47..0000000 --- a/src/com/rifledluffy/chairs/managers/GriefPreventionManager.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.rifledluffy.chairs.managers; - -import me.ryanhamshire.GriefPrevention.Claim; -import me.ryanhamshire.GriefPrevention.GriefPrevention; -import org.bukkit.Location; - -import java.util.HashMap; -import java.util.Map; - -public class GriefPreventionManager { - - private GriefPrevention instance; - - public GriefPreventionManager() {} - - public void setup() { - instance = GriefPrevention.instance; - } - - public boolean isAdminClaim(Location location) { - if (location == null) return false; - if (instance.dataStore == null) return false; - Claim claim = instance.dataStore.getClaimAt(location, true, null); - return claim.isAdminClaim(); - } - -} diff --git a/src/com/rifledluffy/chairs/managers/PlotSquaredManager.java b/src/com/rifledluffy/chairs/managers/PlotSquaredManager.java deleted file mode 100644 index 4f2050f..0000000 --- a/src/com/rifledluffy/chairs/managers/PlotSquaredManager.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.rifledluffy.chairs.managers; - -import com.github.intellectualsites.plotsquared.api.PlotAPI; -import com.github.intellectualsites.plotsquared.plot.flag.BooleanFlag; -import com.rifledluffy.chairs.chairs.Chair; -import com.github.intellectualsites.plotsquared.plot.object.Location; - -public class PlotSquaredManager { - - private PlotAPI api; - private BooleanFlag seating = new BooleanFlag("seating"); - - public PlotSquaredManager() {} - - public void setup() { - api = new PlotAPI(); - api.addFlag(seating); - } - - public boolean canSit(Chair chair) { - org.bukkit.Location location = chair.getLocation(); - Location loc = new Location(location.getWorld().getName(), location.getBlockX(), location.getBlockY(), location.getBlockZ()); - - return api.getAllPlots().stream() - .filter(plot -> plot.getArea().contains(loc)) - .noneMatch(plot -> plot.getFlag(seating).orElse(true)); - } - -} diff --git a/src/com/rifledluffy/chairs/managers/WorldGuardManager.java b/src/com/rifledluffy/chairs/managers/WorldGuardManager.java deleted file mode 100644 index fb0e90f..0000000 --- a/src/com/rifledluffy/chairs/managers/WorldGuardManager.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.rifledluffy.chairs.managers; - -import com.rifledluffy.chairs.RFChairs; -import com.rifledluffy.chairs.chairs.Chair; -import com.sk89q.worldedit.math.BlockVector3; -import com.sk89q.worldguard.LocalPlayer; -import com.sk89q.worldguard.WorldGuard; -import com.sk89q.worldguard.bukkit.WorldGuardPlugin; -import com.sk89q.worldguard.protection.ApplicableRegionSet; -import com.sk89q.worldguard.protection.flags.Flag; -import com.sk89q.worldguard.protection.flags.StateFlag; -import com.sk89q.worldguard.protection.flags.registry.FlagConflictException; -import com.sk89q.worldguard.protection.flags.registry.FlagRegistry; -import com.sk89q.worldguard.protection.regions.RegionContainer; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; - -import java.util.List; -import java.util.stream.Collectors; - -public class WorldGuardManager { - - private RFChairs plugin = RFChairs.getInstance(); - public WorldGuard worldGuard; - public WorldGuardPlugin worldGuardPlugin; - public RegionContainer container; - @SuppressWarnings("rawtypes") - public static Flag flag; - - public WorldGuardManager() {} - - public void setup() { - worldGuard = WorldGuard.getInstance(); - } - - public void register() { - flag = new StateFlag("allow-seating", true); - FlagRegistry registry = WorldGuard.getInstance().getFlagRegistry(); - try { - registry.register(flag); - plugin.log("Custom Flag Registered!"); - } catch (FlagConflictException e) { - plugin.log("Unable to register custom worldguard flag!"); - } - } - - public WorldGuardPlugin getWorldGuard() { - Plugin plugin = this.plugin.getServer().getPluginManager().getPlugin("WorldGuard"); - - if (!(plugin instanceof WorldGuardPlugin)) return null; - return (WorldGuardPlugin) plugin; - } - - public boolean validateSeating(Chair chair, Player player) { - double xPos = chair.getLocation().getX(); - double yPos = chair.getLocation().getY(); - double zPos = chair.getLocation().getZ(); - - WorldGuardManager worldManager = plugin.getWorldGuardManager(); - - LocalPlayer localPlayer = worldManager.getWorldGuard().wrapPlayer(player); - - BlockVector3 vector3 = BlockVector3.at(xPos, yPos, zPos); - - List regionSetList = getContainer().getLoaded().stream() - .map(manager -> manager.getApplicableRegions(vector3)) - .collect(Collectors.toList()); - - if (regionSetList.size() == 0) return true; - - return regionSetList.stream() - .allMatch(set -> set.testState(localPlayer, (StateFlag) worldManager.getFlag())); - } - - public RegionContainer getContainer() { - return worldGuard.getPlatform().getRegionContainer(); - } - - public Flag getFlag() { - return flag; - } - -} diff --git a/src/com/rifledluffy/chairs/messages/MessageConstruct.java b/src/com/rifledluffy/chairs/messages/MessageConstruct.java deleted file mode 100644 index 1fb298a..0000000 --- a/src/com/rifledluffy/chairs/messages/MessageConstruct.java +++ /dev/null @@ -1,6 +0,0 @@ -package com.rifledluffy.chairs.messages; - -public enum MessageConstruct { - - SINGLE, OFFENSIVE, DEFENSIVE -} diff --git a/src/com/rifledluffy/chairs/messages/MessageEvent.java b/src/com/rifledluffy/chairs/messages/MessageEvent.java deleted file mode 100644 index dab2391..0000000 --- a/src/com/rifledluffy/chairs/messages/MessageEvent.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.rifledluffy.chairs.messages; - -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -public class MessageEvent extends Event implements Cancellable { - - boolean cancelled; - - MessageType type; - MessageConstruct construct; - Player player; - Entity other; - - public MessageEvent(MessageType type, MessageConstruct construct, Player player, Player other) { - this.type = type; - this.construct = construct; - this.player = player; - this.other = other; - } - - public MessageEvent(MessageType type, Player player, Entity other) { - this.type = type; - this.construct = MessageConstruct.DEFENSIVE; - this.player = player; - this.other = other; - } - - public MessageEvent(MessageType type, Player player) { - this.type = type; - this.construct = MessageConstruct.SINGLE; - this.player = player; - this.other = null; - } - - public MessageType getType() { - return this.type; - } - - public MessageConstruct getConstruct() { - return this.construct; - } - - public Player getPlayer() { - return this.player; - } - - public Entity getEntity() { - return this.other; - } - - private static final HandlerList handlers = new HandlerList(); - - @Override - public HandlerList getHandlers() { - return handlers; - } - - static public HandlerList getHandlerList() { - return handlers; - } - - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancel) { - this.cancelled = cancel; - } -} diff --git a/src/com/rifledluffy/chairs/messages/MessageType.java b/src/com/rifledluffy/chairs/messages/MessageType.java deleted file mode 100644 index 18c82f4..0000000 --- a/src/com/rifledluffy/chairs/messages/MessageType.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.rifledluffy.chairs.messages; - -public enum MessageType { - - OCCUPIED,TOOFAR,NOPERMS,TOOMANYITEMS,TOSSED,TOSSEDSPEED,TOSSING,TOSSINGSPEED,PRIORITYTOSS,NOSIGNS,WORLDGUARD,PLOTSQUARED - -} diff --git a/src/com/rifledluffy/chairs/messages/Messages.java b/src/com/rifledluffy/chairs/messages/Messages.java deleted file mode 100644 index 362679c..0000000 --- a/src/com/rifledluffy/chairs/messages/Messages.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.rifledluffy.chairs.messages; - -public class Messages { - - private final static String occupied = "occupied-seat"; - private final static String tooFar = "too-far-from-seat"; - private final static String noPerms = "no-permission"; - private final static String tooMany = "too-many-items"; - private final static String tossed = "tossed-out-of-chair"; - private final static String tossedSpeed = "tossed-out-with-speed"; - private final static String tossing = "tossing-someone"; - private final static String tossingSpeed = "tossing-someone-with-speed"; - private final static String priority = "priority-replaced"; - private final static String noSigns = "no-sign-at-ends"; - private final static String worldGuard = "denied-by-worldguard"; - private final static String plotSquared = "denied-by-plotsquared"; - - private final static String defaultOccupied = "&8[&6Rifle's Chairs&8] &cCan't sit there &7%user%&a, my homie &7%seated%&c sits there."; - private final static String defaultTooFar = "&8[&6Rifle's Chairs&8] &cCan't sit there &7%user%&c. You are too far!"; - private final static String defaultNoPerms = "&8[&6Rifle's Chairs&8] &cCan't sit there &7%user%&c. I won't allow you!"; - private final static String defaultTooMany = "&8[&6Rifle's Chairs&8] &c&7%user%&c! You have quite a hefty stack of items on your hand. Remove them!"; - private final static String defaultTossed = "&8[&6Rifle's Chairs&8] &cTossed!... by &7%user%."; - private final static String defaultTossedSpeed = "&8[&6Rifle's Chairs&8] &cYou got chucked off your seat by &7%user%."; - private final static String defaultTossing = "&8[&6Rifle's Chairs&8] &cYou tossed &7%seated%&c off their seat!"; - private final static String defaultTossingSpeed = "&8[&6Rifle's Chairs&8] &cYou forcibly tossed &7%seated%&c off their seat!"; - private final static String defaultPriority = "&8[&6Rifle's Chairs&8] &cYou forcibly tossed to make space for &7%user%&c, &7%seated%"; - private final static String defaultNoSigns = "&8[&6Rifle's Chairs&8] &cThis seat &8[&7which is a stair&8]&c doesn't have signs on both its ends!"; - private final static String defaultWorldGuard = "&8[&6Rifle's Chairs&8] &cYou may not sit in this region!"; - private final static String defaultPlotSquared = "&8[&6Rifle's Chairs&8] &cYou may not sit in this plot!"; - - public static String getDefault(MessageType type) { - switch (type) { - default: - return null; - case OCCUPIED: - return Messages.defaultOccupied; - case TOOFAR: - return Messages.defaultTooFar; - case NOPERMS: - return Messages.defaultNoPerms; - case TOOMANYITEMS: - return Messages.defaultTooMany; - case TOSSED: - return Messages.defaultTossed; - case TOSSEDSPEED: - return Messages.defaultTossedSpeed; - case TOSSING: - return Messages.defaultTossing; - case TOSSINGSPEED: - return Messages.defaultTossingSpeed; - case PRIORITYTOSS: - return Messages.defaultPriority; - case NOSIGNS: - return Messages.defaultNoSigns; - case WORLDGUARD: - return Messages.defaultWorldGuard; - case PLOTSQUARED: - return Messages.defaultPlotSquared; - } - } - - public static String getMessage(MessageType type) { - switch (type) { - default: - return null; - case OCCUPIED: - return Messages.occupied; - case TOOFAR: - return Messages.tooFar; - case NOPERMS: - return Messages.noPerms; - case TOOMANYITEMS: - return Messages.tooMany; - case TOSSED: - return Messages.tossed; - case TOSSEDSPEED: - return Messages.tossedSpeed; - case TOSSING: - return Messages.tossing; - case TOSSINGSPEED: - return Messages.tossingSpeed; - case PRIORITYTOSS: - return Messages.priority; - case NOSIGNS: - return Messages.noSigns; - case WORLDGUARD: - return Messages.worldGuard; - case PLOTSQUARED: - return Messages.plotSquared; - } - } -} diff --git a/src/com/rifledluffy/chairs/metrics/MetricsLite.java b/src/com/rifledluffy/chairs/metrics/MetricsLite.java deleted file mode 100644 index b433772..0000000 --- a/src/com/rifledluffy/chairs/metrics/MetricsLite.java +++ /dev/null @@ -1,314 +0,0 @@ -package com.rifledluffy.chairs.metrics; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.RegisteredServiceProvider; -import org.bukkit.entity.Player; -import org.bukkit.plugin.ServicePriority; -import org.bukkit.plugin.java.JavaPlugin; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -import javax.net.ssl.HttpsURLConnection; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.File; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.net.URL; -import java.util.Collection; -import java.util.Timer; -import java.util.TimerTask; -import java.util.UUID; -import java.util.logging.Level; -import java.util.zip.GZIPOutputStream; - -/** - * bStats collects some data for plugin authors. - * - * Check out https://bStats.org/ to learn more about bStats! - */ -public class MetricsLite { - - static { - // You can use the property to disable the check in your test environment - if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { - // Maven's Relocate is clever and changes strings, too. So we have to use this little "trick" ... :D - final String defaultPackage = new String( - new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); - final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); - // We want to make sure nobody just copy & pastes the example and use the wrong package names - if (MetricsLite.class.getPackage().getName().equals(defaultPackage) || MetricsLite.class.getPackage().getName().equals(examplePackage)) { - throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); - } - } - } - - // The version of this bStats class - public static final int B_STATS_VERSION = 1; - - // The url to which the data is sent - private static final String URL = "https://bStats.org/submitData/bukkit"; - - // Should failed requests be logged? - private static boolean logFailedRequests; - - // The uuid of the server - private static String serverUUID; - - // The plugin - private final JavaPlugin plugin; - - /** - * Class constructor. - * - * @param plugin The plugin which stats should be submitted. - */ - public MetricsLite(JavaPlugin plugin) { - if (plugin == null) { - throw new IllegalArgumentException("Plugin cannot be null!"); - } - this.plugin = plugin; - - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - - // Check if the config file exists - if (!config.isSet("serverUuid")) { - - // Add default values - config.addDefault("enabled", true); - // Every server gets it's unique random id. - config.addDefault("serverUuid", UUID.randomUUID().toString()); - // Should failed request be logged? - config.addDefault("logFailedRequests", false); - - // Inform the server owners about bStats - config.options().header( - "bStats collects some data for plugin authors like how many servers are using their plugins.\n" + - "To honor their work, you should not disable it.\n" + - "This has nearly no effect on the server performance!\n" + - "Check out https://bStats.org/ to learn more :)" - ).copyDefaults(true); - try { - config.save(configFile); - } catch (IOException ignored) { } - } - - // Load the data - serverUUID = config.getString("serverUuid"); - logFailedRequests = config.getBoolean("logFailedRequests", false); - if (config.getBoolean("enabled", true)) { - boolean found = false; - // Search for all other bStats Metrics classes to see if we are the first one - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - found = true; // We aren't the first - break; - } catch (NoSuchFieldException ignored) { } - } - // Register our service - Bukkit.getServicesManager().register(MetricsLite.class, this, plugin, ServicePriority.Normal); - if (!found) { - // We are the first! - startSubmitting(); - } - } - } - - /** - * Starts the Scheduler which submits our data every 30 minutes. - */ - private void startSubmitting() { - final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - if (!plugin.isEnabled()) { // Plugin was disabled - timer.cancel(); - return; - } - // Nevertheless we want our code to run in the Bukkit main thread, so we have to use the Bukkit scheduler - // Don't be afraid! The connection to the bStats server is still async, only the stats collection is sync ;) - Bukkit.getScheduler().runTask(plugin, new Runnable() { - @Override - public void run() { - submitData(); - } - }); - } - }, 1000*60*5, 1000*60*30); - // Submit the data every 30 minutes, first time after 5 minutes to give other plugins enough time to start - // WARNING: Changing the frequency has no effect but your plugin WILL be blocked/deleted! - // WARNING: Just don't do it! - } - - /** - * Gets the plugin specific data. - * This method is called using Reflection. - * - * @return The plugin specific data. - */ - @SuppressWarnings("unchecked") - public JSONObject getPluginData() { - JSONObject data = new JSONObject(); - - String pluginName = plugin.getDescription().getName(); - String pluginVersion = plugin.getDescription().getVersion(); - - data.put("pluginName", pluginName); // Append the name of the plugin - data.put("pluginVersion", pluginVersion); // Append the version of the plugin - JSONArray customCharts = new JSONArray(); - data.put("customCharts", customCharts); - - return data; - } - - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - @SuppressWarnings("unchecked") - private JSONObject getServerData() { - // Minecraft specific data - int playerAmount; - try { - // Around MC 1.8 the return type was changed to a collection from an array, - // This fixes java.lang.NoSuchMethodError: org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; - Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); - playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) - ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() - : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } catch (Exception e) { - playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed - } - int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; - String bukkitVersion = Bukkit.getVersion(); - bukkitVersion = bukkitVersion.substring(bukkitVersion.indexOf("MC: ") + 4, bukkitVersion.length() - 1); - - // OS/Java specific data - String javaVersion = System.getProperty("java.version"); - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); - - JSONObject data = new JSONObject(); - - data.put("serverUUID", serverUUID); - - data.put("playerAmount", playerAmount); - data.put("onlineMode", onlineMode); - data.put("bukkitVersion", bukkitVersion); - - data.put("javaVersion", javaVersion); - data.put("osName", osName); - data.put("osArch", osArch); - data.put("osVersion", osVersion); - data.put("coreCount", coreCount); - - return data; - } - - /** - * Collects the data and sends it afterwards. - */ - @SuppressWarnings("unchecked") - private void submitData() { - final JSONObject data = getServerData(); - - JSONArray pluginData = new JSONArray(); - // Search for all other bStats Metrics classes to get their plugin data - for (Class service : Bukkit.getServicesManager().getKnownServices()) { - try { - service.getField("B_STATS_VERSION"); // Our identifier :) - - for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { - try { - pluginData.add(provider.getService().getMethod("getPluginData").invoke(provider.getProvider())); - } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { - } - } - } catch (NoSuchFieldException ignored) { } - } - - data.put("plugins", pluginData); - - // Create a new thread for the connection to the bStats server - new Thread(new Runnable() { - @Override - public void run() { - try { - // Send the data - sendData(data); - } catch (Exception e) { - // Something went wrong! :( - if (logFailedRequests) { - plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); - } - } - } - }).start(); - } - - /** - * Sends the data to the bStats server. - * - * @param data The data to send. - * @throws Exception If the request failed. - */ - private static void sendData(JSONObject data) throws Exception { - if (data == null) { - throw new IllegalArgumentException("Data cannot be null!"); - } - if (Bukkit.isPrimaryThread()) { - throw new IllegalAccessException("This method must not be called from the main thread!"); - } - HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); - - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); - - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - - // Send data - connection.setDoOutput(true); - DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); - outputStream.write(compressedData); - outputStream.flush(); - outputStream.close(); - - connection.getInputStream().close(); // We don't care about the response - Just send our data :) - } - - /** - * Gzips the given String. - * - * @param str The string to gzip. - * @return The gzipped String. - * @throws IOException If the compression failed. - */ - private static byte[] compress(final String str) throws IOException { - if (str == null) { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - GZIPOutputStream gzip = new GZIPOutputStream(outputStream); - gzip.write(str.getBytes("UTF-8")); - gzip.close(); - return outputStream.toByteArray(); - } - -} diff --git a/src/com/rifledluffy/chairs/utility/Util.java b/src/com/rifledluffy/chairs/utility/Util.java deleted file mode 100644 index d0c03e3..0000000 --- a/src/com/rifledluffy/chairs/utility/Util.java +++ /dev/null @@ -1,316 +0,0 @@ -package com.rifledluffy.chairs.utility; - -import com.rifledluffy.chairs.RFChairs; -import com.rifledluffy.chairs.chairs.BlockFilter; -import com.rifledluffy.chairs.chairs.Chair; -import com.rifledluffy.chairs.config.ConfigManager; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.block.data.Bisected; -import org.bukkit.block.data.Directional; -import org.bukkit.block.data.Levelled; -import org.bukkit.block.data.type.Slab; -import org.bukkit.block.data.type.Stairs; -import org.bukkit.block.data.type.TrapDoor; -import org.bukkit.block.data.type.WallSign; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.bukkit.util.Vector; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; - -public class Util { - - private static RFChairs plugin = RFChairs.getPlugin(RFChairs.class); - private static ConfigManager configManager = plugin.getConfigManager(); - - public static ConfigManager getConfigManager() { - return configManager; - } - - public static void debug(String message) { - for (Player player : plugin.getServer().getOnlinePlayers()) player.sendMessage(message); - } - - public static void debug(Object message) { - debug(message.toString()); - } - - public static void debug(List messages) { - messages.forEach(Util::debug); - } - - public static String replaceMessage(Player player, String string) { - string = ChatColor.translateAlternateColorCodes('&',string); - string = string.replace("%user%", player.getDisplayName()); - return string; - } - - public static String replaceMessage(Entity entity, Player target, String string) { - if (entity instanceof LivingEntity) return replaceMessage((LivingEntity)entity, target, string); - - string = ChatColor.translateAlternateColorCodes('&',string); - string = string.replace("%user%", entity.getName()); - string = string.replace("%seated%", target.getName()); - return string; - } - - public static String replaceMessage(LivingEntity entity, Player target, String string) { - if (entity instanceof Player) return replaceMessage((Player)entity, target, string); - - string = ChatColor.translateAlternateColorCodes('&',string); - string = string.replace("%user%", entity.getName()); - string = string.replace("%seated%", target.getName()); - return string; - } - - public static String replaceMessage(Player player, Player target, String string) { - string = ChatColor.translateAlternateColorCodes('&',string); - string = string.replace("%user%", player.getDisplayName()); - string = string.replace("%seated%", target.getName()); - return string; - } - - public static boolean validStair(Block block) { - if (!BlockFilter.validateStairs(block.getType())) return false; - Stairs stair = (Stairs) block.getState().getBlockData(); - return stair.getHalf() != Bisected.Half.TOP; - } - - public static boolean validSlab(Block block) { - if (!BlockFilter.validateSlab(block.getType())) return false; - Slab slab = (Slab) block.getState().getBlockData(); - return slab.getType() == Slab.Type.BOTTOM; - } - - public static boolean validCarpet(Block block) { - return BlockFilter.validateCarpet(block.getType()); - } - - private static boolean validatedChair(Block block) { - return BlockFilter.isStairsBlock(block.getType()) && validStair(block); - } - - public static boolean playerIsSeated(UUID uuid, Map chairMap) { - Chair chair = chairMap.get(uuid); - return chair != null; - } - - public static boolean nearLiquid(Block block) { - return isLiqiudOrMagma(block.getRelative(BlockFace.NORTH)) - || isLiqiudOrMagma(block.getRelative(BlockFace.EAST)) - || isLiqiudOrMagma(block.getRelative(BlockFace.SOUTH)) - || isLiqiudOrMagma(block.getRelative(BlockFace.WEST)); - } - - public static boolean surroundedBlock(Block block) { - return !validExit(block.getRelative(BlockFace.NORTH)) - && !validExit(block.getRelative(BlockFace.EAST)) - && !validExit(block.getRelative(BlockFace.SOUTH)) - && !validExit(block.getRelative(BlockFace.WEST)); - } - - private static boolean validExit(Block block) { - Material type = block.getType(); - return type == Material.AIR || type.name().equals("WALL_SIGN") || type.name().endsWith("_WALL_SIGN"); - } - - public static boolean isLiqiudOrMagma(Block block) { - return block.getBlockData() instanceof Levelled || block.getRelative(BlockFace.DOWN).getType() == Material.MAGMA_BLOCK; - } - - public static boolean validCouch(Block block) { - int validSides = 0; - if (!validatedChair(block)) return false; - Stairs stair = (Stairs) block.getState().getBlockData(); - - Set blockFaces = stair.getFaces(); - List faces = new ArrayList(blockFaces); - faces.remove(stair.getFacing()); - faces.remove(stair.getFacing().getOppositeFace()); - faces.remove(BlockFace.DOWN); - faces.remove(BlockFace.UP); - - BlockFace side = faces.get(0); - BlockFace otherSide = faces.get(1); - - if (block.getRelative(BlockFace.UP).getType() != Material.AIR) return false; - - if (validatedChair(block.getRelative(side))) if (validSeat(block.getRelative(side), side, block)) validSides++; - if (validatedChair(block.getRelative(otherSide))) if (validSeat(block.getRelative(otherSide), otherSide, block)) validSides++; - - if (!validatedChair(block.getRelative(side))) if (validSeat(block, side, block)) validSides++; - if (!validatedChair(block.getRelative(otherSide))) if (validSeat(block, otherSide, block)) validSides++; - return validSides == 2; - } - - public static boolean validSeat(Block block, BlockFace side, Block original) { - Stairs stair = (Stairs) block.getState().getBlockData(); - Stairs first = (Stairs) original.getState().getBlockData(); - if (stair.getFacing() != first.getFacing()) return false; - if (block.getRelative(side).getBlockData() instanceof WallSign || block.getRelative(side).getBlockData() instanceof TrapDoor) { - Directional sign =((Directional)block.getRelative(side).getBlockData()); - return sign.getFacing() == side; - } - else if (validatedChair(block.getRelative(side))) return validSeat(block.getRelative(side), side, original); - return false; - } - - public static boolean sameSeat(Player player, Block block, Map chairMap) { - Chair chair = chairMap.get(player.getUniqueId()); - if (chair == null) return false; - return chair.getLocation().equals(block.getLocation()); - } - - public static boolean samePosition(Block block, Block target) { - return block.getX() == target.getX() && block.getY() == target.getY() && block.getZ() == target.getZ(); - } - - public static boolean throneChair(Block block) { - if (!(block.getBlockData() instanceof Stairs)) return false; - if (block.getRelative(BlockFace.UP).getBlockData() instanceof TrapDoor) { - TrapDoor trapDoor = (TrapDoor) block.getRelative(BlockFace.UP).getBlockData(); - if (!trapDoor.isOpen()) return false; - return trapDoor.getFacing().getOppositeFace() == ((Stairs) block.getBlockData()).getFacing(); - } - return false; - } - - public static boolean blockIsChair(Block block, List chairs) { - for (Chair chair: chairs) { - if (chair == null) continue; - if (chair.getLocation() == null) continue; - if (samePosition(block, chair.getBlock())) return true; - } - return false; - } - - public static Chair getChairFromBlock(Block block, List chairs) { - for (Chair chair : chairs) { - if (chair == null) continue; - if (chair.getLocation() == null) continue; - if (samePosition(chair.getBlock(), block)) return chair; - } - return null; - } - - public static ArmorStand generateFakeSeat(Chair chair) { - if (chair == null) return null; - Vector seatingPosition = new Vector(0.5,0.3D,0.5); - Location seat = chair.getLocation(); - BlockFace facing = null; - if (BlockFilter.isStairsBlock(chair.getBlock().getType())) facing = ((Stairs)chair.getBlock().getState().getBlockData()).getFacing(); - Location playerLoc = chair.getPlayer().getEyeLocation(); - playerLoc.setPitch(0); - Vector vector; - if (facing != null) vector = getVectorFromFace(chair.getBlock(), facing.getOppositeFace()); - else vector = getVectorFromNearBlock(chair.getBlock(), playerLoc.getBlock()); - - if (BlockFilter.isStairsBlock(chair.getBlock().getType())) seatingPosition = plugin.chairManager.stairSeatingPosition; - if (BlockFilter.isCarpetBlock(chair.getBlock().getType())) seatingPosition = plugin.chairManager.carpetSeatingPosition; - if (BlockFilter.isSlabBlock(chair.getBlock().getType())) seatingPosition = plugin.chairManager.slabSeatingPosition; - - //Thank you VicenteRD and carlpoole! - return seat.getWorld().spawn( - seat.clone().add(seatingPosition).setDirection(vector), - ArmorStand.class, - stand -> { - stand.setVisible(false); - stand.setGravity(false); - stand.setInvulnerable(true); - stand.setMarker(true); - stand.setCollidable(false); - }); - } - - public static ArmorStand generateFakeSeatDir(Chair chair, Vector dir) { - if (chair == null) return null; - Vector seatingPosition = new Vector(0.5,0.3D,0.5); - Location seat = chair.getLocation(); - Location playerLoc = chair.getPlayer().getEyeLocation(); - playerLoc.setPitch(0); - - if (BlockFilter.isStairsBlock(chair.getBlock().getType())) seatingPosition = plugin.chairManager.stairSeatingPosition; - if (BlockFilter.isCarpetBlock(chair.getBlock().getType())) seatingPosition = plugin.chairManager.carpetSeatingPosition; - if (BlockFilter.isSlabBlock(chair.getBlock().getType())) seatingPosition = plugin.chairManager.slabSeatingPosition; - - //Thank you VicenteRD and carlpoole! - return seat.getWorld().spawn( - seat.clone().add(seatingPosition).setDirection(dir), - ArmorStand.class, - stand -> { - stand.setVisible(false); - stand.setGravity(false); - stand.setInvulnerable(true); - stand.setMarker(true); - stand.setCollidable(false); - }); - } - - public static float getAbsoluteAngle(Location loc) { - float y = loc.getYaw(); - if (y < 0) y += 360; - y %= 360; - if (y <= 45 || y >= 315) return 0; - if (y >= 45 && y <= 135) return 90; - if (y >= 135 && y <= 225) return 180; - return 270; - } - - public static String getCardinalDirection(Location loc) { - float y = loc.getYaw(); - if (y < 0) y += 360; - y %= 360; - if (y <= 45 || y >= 315) return "south"; - if (y >= 45 && y <= 135) return "west"; - if (y >= 135 && y <= 225) return "north"; - return "east"; - } - - public static Block getBlockFromDirection(Block block, String direction) { - if (direction.equalsIgnoreCase("north")) return block.getRelative(BlockFace.NORTH); - else if (direction.equalsIgnoreCase("west")) return block.getRelative(BlockFace.WEST); - else if (direction.equalsIgnoreCase("east")) return block.getRelative(BlockFace.EAST); - else if (direction.equalsIgnoreCase("south")) return block.getRelative(BlockFace.SOUTH); - else if (direction.equalsIgnoreCase("down")) return block.getRelative(BlockFace.DOWN); - else if (direction.equalsIgnoreCase("up")) return block.getRelative(BlockFace.UP); - return block; - } - - public static boolean canFitPlayer(Block block) { - return block.getType() == Material.AIR && block.getRelative(BlockFace.UP).getType() == Material.AIR; - } - - public static boolean safePlace(Block block) { - return block.getRelative(BlockFace.DOWN).getType() != Material.AIR; - } - - public static Vector getVectorDir(Location caster, Location target) { - return target.clone().subtract(caster.toVector()).toVector(); - } - - public static Vector getVectorFromFace(Block block, BlockFace face) { - Location blockLoc = block.getLocation(); - Location faceLoc = block.getRelative(face).getLocation(); - return getVectorDir(blockLoc, faceLoc); - } - - public static Vector getVectorFromNearBlock(Block block, Block target) { - return target.getLocation().toVector().subtract(block.getLocation().toVector()); - } - - public static void callEvent(Event event) { - plugin.getServer().getPluginManager().callEvent(event); - } - -} diff --git a/src/main/java/com/rifledluffy/chairs/ChairManager.java b/src/main/java/com/rifledluffy/chairs/ChairManager.java new file mode 100644 index 0000000..ed6efa4 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/ChairManager.java @@ -0,0 +1,675 @@ +package com.rifledluffy.chairs; + +import com.rifledluffy.chairs.chairs.BlockFilter; +import com.rifledluffy.chairs.chairs.Chair; +import com.rifledluffy.chairs.events.*; +import com.rifledluffy.chairs.messages.MessageEvent; +import com.rifledluffy.chairs.messages.MessagePath; +import com.rifledluffy.chairs.messages.PlaceHolder; +import com.rifledluffy.chairs.utility.Util; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.*; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.block.BlockPistonExtendEvent; +import org.bukkit.event.block.BlockPistonRetractEvent; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDismountEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerGameModeChangeEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.projectiles.ProjectileSource; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.NotNull; + +import java.util.*; +import java.util.stream.Collectors; + +public class ChairManager implements Listener { + private final @NotNull RFChairs plugin; + private final @NotNull Map<@NotNull UUID, @NotNull Chair> chairMap = new HashMap<>(); + private final @NotNull List<@NotNull String> fakeSeats = new ArrayList<>(); + private final @NotNull List<@NotNull UUID> leaving = new ArrayList<>(); + private final @NotNull List<@NotNull UUID> orienting = new ArrayList<>(); + private final @NotNull Map<@NotNull UUID, @NotNull TargetInfo> tossed = new HashMap<>(); + private final @NotNull List<@NotNull Chair> chairs = new ArrayList<>(); + private final @NotNull List<@NotNull UUID> toggled = new ArrayList<>(); + private Vector stairSeatingPosition; + private Vector slabSeatingPosition; + private Vector carpetSeatingPosition; + private PotionEffect regenEffect; + private boolean regenWhenSitting; + //Update related + //private boolean disableCurrentUpdate; //todo + //private boolean disableUpdates; //todo + //Kick them off their seat if they take damage + private boolean canLaunch; + //Toss them off their seat if they take damage + private boolean canToss; + //The minimum damage needed for a player to be tossed + private double minDamage; + //Toss Configuration + private boolean faceAttacker; + private double tossVelocity; + private boolean scaleVelocity; + private double scaleAmount; + //Maximum amount of items on hand that they can have when trying to sit + private int maxItemSit; + private double maxDistance; + private boolean checkForSigns; + private boolean priorityIfHasPerm; + private boolean trapSeats; + private boolean requireEmptyHand; + //Mostly buggy, probably going to remove soon. + private boolean exitWhereFacing; + private @NotNull List<@NotNull World> disabledWorlds = new ArrayList<>(); + + public ChairManager(@NotNull RFChairs plugin) { + this.plugin = plugin; + this.regenEffect = new PotionEffect(PotionEffectType.REGENERATION, 655200, plugin.getConfigManager().getConfig().getInt("regen-potency", 0), false, false); + } + + public void reload() { + FileConfiguration config = plugin.getConfigManager().getConfig(); + + regenEffect = new PotionEffect(PotionEffectType.REGENERATION, 655200, config.getInt("regen-potency", 0), false, false); + regenWhenSitting = config.getBoolean("regen-when-sitting", true); + + //disableCurrentUpdate = config.getBoolean("disable-update-message-if-on-latest", false); + //disableUpdates = config.getBoolean("disable-update-messages", false); + + faceAttacker = config.getBoolean("face-attacker-when-ejected", false); + canToss = config.getBoolean("toss-player", false); + tossVelocity = config.getDouble("toss-velocity", 0.5D); + scaleVelocity = config.getBoolean("scale-toss-velocity", true); + scaleAmount = config.getDouble("velocity-scale-factor", 2D); + canLaunch = config.getBoolean("eject-player-on-damage", true); + minDamage = config.getDouble("minimum-eject-damage", 2D); + exitWhereFacing = config.getBoolean("exit-seat-where-facing", false); + maxItemSit = config.getInt("max-item-count-to-sit", -1); + maxDistance = config.getDouble("max-distance", 2D); + checkForSigns = config.getBoolean("require-signs-at-end", false); + priorityIfHasPerm = config.getBoolean("priority-on-if-has-perm", true); + trapSeats = config.getBoolean("allow-trap-door-chairs", true); + requireEmptyHand = config.getBoolean("require-empty-hand", false); + + try { + String[] vectorString = Objects.requireNonNull(config.getString("stair-seating-position", "0.5,0.3,0.5")).split(","); + stairSeatingPosition = new Vector(Double.parseDouble(vectorString[0]), Double.parseDouble(vectorString[1]), Double.parseDouble(vectorString[2])); + } catch (NumberFormatException e) { + stairSeatingPosition = new Vector(0.5D, 0.3D, 0.5); + } + + try { + String[] vectorString = Objects.requireNonNull(config.getString("slab-seating-position", "0.5,0.3,0.5")).split(","); + slabSeatingPosition = new Vector(Double.parseDouble(vectorString[0]), Double.parseDouble(vectorString[1]), Double.parseDouble(vectorString[2])); + } catch (NumberFormatException e) { + slabSeatingPosition = new Vector(0.5, 0.3D, 0.5); + } + + try { + String[] vectorString = Objects.requireNonNull(config.getString("carpet-seating-position", "0.5,-0.15,0.5")).split(","); + carpetSeatingPosition = new Vector(Double.parseDouble(vectorString[0]), Double.parseDouble(vectorString[1]), Double.parseDouble(vectorString[2])); + } catch (NumberFormatException e) { + carpetSeatingPosition = new Vector(0.5, -0.15D, 0.5); + } + + disabledWorlds = config.getStringList("disabled-worlds").stream() + .map(Bukkit::getWorld) + .filter(Objects::nonNull) + .collect(Collectors.toList()); + } + + @EventHandler + private void onChairSit(@NotNull ChairSitEvent event) { + Chair chair = event.getChair(); + if (chair.getLocation() == null) return; + + if (plugin.hasWorldGuard()) if (!plugin.getWorldGuardManager().validateSeating(chair, event.getPlayer())) { + new MessageEvent(MessagePath.WORLDGUARD, event.getPlayer()).callEvent(); + return; + } + + Player player = event.getPlayer(); + + if (Util.playerIsSeated(player.getUniqueId(), chairMap)) clearPlayer(player); + boolean done = sitPlayer(chair, player); + if (!done) return; + chairs.add(chair); + chairMap.put(player.getUniqueId(), chair); + if (regenWhenSitting) player.addPotionEffect(regenEffect); + } + + @EventHandler + private void onChairLeave(@NotNull ChairLeaveEvent event) { + Chair chair = event.getChair(); + if (chair.getLocation() == null) return; + + Block block = chair.getLocation().getBlock(); + Player player = event.getPlayer(); + boolean flag = event.exitWhereFacing(); + + Location exit = block.getLocation(); + + clearPlayer(player); + player.removePotionEffect(PotionEffectType.REGENERATION); + if (flag) exit = findExitPoint(player.getLocation(), block).getLocation(); + if (Util.surroundedBlock(block) || Util.nearLiquid(player.getLocation().getBlock())) + exit = block.getRelative(BlockFace.UP).getLocation(); + exit.setDirection(player.getEyeLocation().getDirection()); + exit.add(0.5, 0, 0.5); + player.teleport(exit); + if (!flag) { + Vector v = player.getEyeLocation().getDirection(); + v.setY(0); + v.normalize(); + v.setY(1); + player.setVelocity(v.multiply(0.25)); + } + } + + @EventHandler + private void onToss(@NotNull ChairTossEvent event) { + Chair chair = event.getChair(); + if (chair.getLocation() == null) return; + + Block block = chair.getBlock(); + Player player = event.getPlayer(); + Entity attacker = event.getAttacker(); + TargetInfo info = event.getInfo(); + boolean silent = event.isSilent(); + + ChairLeaveEvent leaveEvent = new ChairLeaveEvent(chair, player, false); + leaveEvent.callEvent(); + + if (!silent) { + MessageEvent tossedMessageEvent; + MessageEvent tosserMessageEvent = null; + if (attacker instanceof Player playerEntity) { + if (info != null && !info.isSprinting()) { + tossedMessageEvent = new MessageEvent(MessagePath.TOSSED, player, + Placeholder.component(PlaceHolder.PLAYER.getPlaceholder(), playerEntity.displayName())); + + tosserMessageEvent = new MessageEvent(MessagePath.TOSSING, playerEntity, + Placeholder.component(PlaceHolder.SEATED.getPlaceholder(), player.displayName())); + } else { + tossedMessageEvent = new MessageEvent(MessagePath.TOSSEDSPEED, player, + Placeholder.component(PlaceHolder.PLAYER.getPlaceholder(), playerEntity.displayName())); + + tosserMessageEvent = new MessageEvent(MessagePath.TOSSINGSPEED, playerEntity, + Placeholder.component(PlaceHolder.SEATED.getPlaceholder(), player.displayName())); + } + } else { + Component attackerName = attacker.customName(); + if (attackerName == null) { + attackerName = Component.text(attacker.getName()); + } + + tossedMessageEvent = new MessageEvent(MessagePath.TOSSED, player, + Placeholder.component(PlaceHolder.PLAYER.getPlaceholder(), attackerName)); + } + tossedMessageEvent.callEvent(); + if (tosserMessageEvent != null) { + tosserMessageEvent.callEvent(); + } + } + + if (canToss) { // todo shouldn't this check be higher up? + tossPlayer(block, player, attacker); + } + } + + @EventHandler + private void onChairReplace(@NotNull ChairReplaceEvent event) { + Chair chair = event.getChair(); + if (chair.getLocation() == null) return; + + Block block = chair.getBlock(); + Player player = event.getPlayer(); + Player seated = event.getReplaced(); + + if (player.getUniqueId() == seated.getUniqueId()) return; + + ChairTossEvent tossEvent = new ChairTossEvent(chair, seated, player, null, true); + tossEvent.callEvent(); + + MessageEvent tossed = new MessageEvent(MessagePath.TOSSED, seated, + Placeholder.component(PlaceHolder.PLAYER.getPlaceholder(), player.displayName())); + tossed.callEvent(); + + ChairSitEvent sitEvent = new ChairSitEvent(new Chair(player, block.getLocation()), player); + sitEvent.callEvent(); + + MessageEvent tosser = new MessageEvent(MessagePath.TOSSING, player, + Placeholder.component(PlaceHolder.SEATED.getPlaceholder(), seated.displayName())); + tosser.callEvent(); + } + + @EventHandler + private void onChairCheck(@NotNull ChairCheckEvent event) { + Player player = event.getPlayer(); + ItemStack item = player.getInventory().getItemInMainHand(); + Block block = event.getBlock(); + + if (!player.hasPermission("rfchairs.use")) { + new MessageEvent(MessagePath.SEAT_NOPERMS, player).callEvent(); + return; + } + + if (player.getLocation().distance(block.getLocation().add(0.5, 0, 0.5)) >= maxDistance) { + new MessageEvent(MessagePath.TOOFAR, player).callEvent(); + return; + } + + if (maxItemSit > 0 && item.getAmount() > maxItemSit) { + new MessageEvent(MessagePath.TOOMANYITEMS, player).callEvent(); + return; + } + + if (!Util.blockIsChair(block, chairs)) { + ChairSitEvent sitEvent = new ChairSitEvent(new Chair(player, block.getLocation()), player); + sitEvent.callEvent(); + } else { + Chair chair = Util.getChairFromBlock(block, chairs); + if (chair == null) return; + if (chair.getFakeSeat() != null && chair.getFakeSeat().getPassengers().isEmpty()) { + chair.setPlayer(player); + chair.getFakeSeat().addPassenger(player); + if (regenWhenSitting) { + player.addPotionEffect(regenEffect); + } + return; + } + if (player.hasPermission("rfchairs.priority") && priorityIfHasPerm) { + ChairReplaceEvent replaceEvent = new ChairReplaceEvent(chair, chair.getPlayer(), player); + replaceEvent.callEvent(); + return; + } + if (chair.getPlayer() == null) { + return; + } + if (player.getUniqueId().equals(chair.getPlayer().getUniqueId())) { + orienting.add(player.getUniqueId()); + Location loc = chair.getFakeSeat().getLocation(); + loc.setDirection(player.getEyeLocation().getDirection().setY(0)); + chair.getFakeSeat().remove(); + ArmorStand newFakeSeat = Util.generateFakeSeatDir(chair, loc.getDirection()); + chair.setFakeSeat(newFakeSeat); + chair.getFakeSeat().addPassenger(player); + } else { + MessageEvent occupied = new MessageEvent(MessagePath.OCCUPIED, player, + Placeholder.component(PlaceHolder.PLAYER.getPlaceholder(), player.displayName()), + Placeholder.component(PlaceHolder.SEATED.getPlaceholder(), chair.getPlayer().displayName())); + occupied.callEvent(); + } + } + } + + @EventHandler + private void onRightClick(@NotNull PlayerInteractEvent event) { + if (!disabledWorlds.isEmpty() && disabledWorlds.contains(event.getPlayer().getWorld())) return; + if (event.getAction() != Action.RIGHT_CLICK_BLOCK) return; + if (event.getPlayer().isSneaking()) return; + if (event.getHand() != EquipmentSlot.HAND) return; + if (toggled.contains(event.getPlayer().getUniqueId())) return; + + Block block = event.getClickedBlock(); + Player player = event.getPlayer(); + ItemStack item = event.getItem(); + if (block == null) return; + + if (requireEmptyHand && item != null) return; + + if (item != null && item.getType() != Material.AIR) { + if (item.getType().isBlock()) return; + } + + if (BlockFilter.isStairsBlock(block.getType()) + || BlockFilter.isCarpetBlock(block.getType()) + || BlockFilter.isSlabBlock(block.getType())) { + if (BlockFilter.isStairsBlock(block.getType())) { + if (!Util.validStair(block)) return; + else { + if (checkForSigns) { + if (!Util.validCouch(block)) { + if (!trapSeats) return; + if (!Util.throneChair(block)) { + new MessageEvent(MessagePath.NOSIGNS, player).callEvent(); + return; + } + } else if (block.getRelative(BlockFace.UP).getType() != Material.AIR) { + return; + } + } + if (trapSeats && block.getRelative(BlockFace.UP).getType() != Material.AIR) { + if (!Util.throneChair(block)) return; + } + } + } else if (block.getRelative(BlockFace.UP).getType() != Material.AIR) return; + + if (BlockFilter.isSlabBlock(block.getType())) { + if (!Util.validSlab(block)) { + return; + } + } + + if (BlockFilter.isCarpetBlock(block.getType())) { + if (!Util.validCarpet(block)) { + return; + } + } + + if (event.getBlockFace() == BlockFace.DOWN) return; + + if (!player.hasPermission("rfchairs.use")) { + new MessageEvent(MessagePath.SEAT_NOPERMS, player).callEvent(); + return; + } + + new ChairCheckEvent(block, player).callEvent(); + } + } + + @EventHandler + private void onChangeGameMode(@NotNull PlayerGameModeChangeEvent event) { + if (event.isCancelled()) return; + GameMode gameMode = event.getNewGameMode(); + Chair chair = chairMap.get(event.getPlayer().getUniqueId()); + if (gameMode == GameMode.SPECTATOR && chair != null) { + clearChair(chair); + } + } + + @EventHandler + private void onDismount(@NotNull EntityDismountEvent event) { + if (!(event.getEntity() instanceof Player player)) return; + Chair chair = chairMap.get(player.getUniqueId()); + + if (chair == null || event.getDismounted().getType() != EntityType.ARMOR_STAND) return; + if (leaving.contains(player.getUniqueId())) return; + if (orienting.contains(player.getUniqueId())) { + orienting.remove(player.getUniqueId()); + return; + } + + if (tossed.containsKey(player.getUniqueId())) { + TargetInfo info = tossed.get(player.getUniqueId()); + Entity attacker = info.getAttacker(); + if (info.hasSource() && info.livingSource()) { + attacker = info.getLivingSource(); + } + + ChairTossEvent tossEvent = new ChairTossEvent(chair, player, attacker, info, false); + tossEvent.callEvent(); + tossed.remove(player.getUniqueId()); + return; + } + leaving.add(player.getUniqueId()); + } + + @EventHandler + private void onMove(@NotNull PlayerMoveEvent event) { + Player player = event.getPlayer(); + if (leaving.contains(player.getUniqueId())) { + ChairLeaveEvent leaveEvent = new ChairLeaveEvent(chairMap.get(player.getUniqueId()), player, exitWhereFacing); + leaveEvent.callEvent(); + leaving.remove(player.getUniqueId()); + } + } + + @EventHandler + private void takeDamage(@NotNull EntityDamageByEntityEvent event) { + if (event.isCancelled()) return; + if (!(event.getEntity() instanceof Player player)) return; + + Entity attacker = event.getDamager(); + ProjectileSource source = null; + if (attacker instanceof Projectile projectile) { + source = projectile.getShooter(); + } + Chair chair = chairMap.get(player.getUniqueId()); + if (chair == null) { + return; + } + + if (event.getDamage() >= minDamage && canLaunch) { + TargetInfo info; + if (source == null) { + info = new TargetInfo(attacker, event.getDamage()); + } else { + info = new TargetInfo(source, attacker, event.getDamage()); + } + tossed.put(player.getUniqueId(), info); + if (chair.getFakeSeat() != null) { + chair.getFakeSeat().removePassenger(player); + } + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + // we want to act after the event may was canceled by protection plugins + private void onBlockBreak(@NotNull BlockBreakEvent event) { + chairs.stream() + .filter(chair -> chair.getLocation() != null) + .filter(chair -> Util.samePosition(event.getBlock(), chair.getLocation())) + .findAny() + .ifPresent(chair -> { + if (!event.getPlayer().hasPermission("rfchairs.break")) { + event.setCancelled(true); + } else { // eject player if block was broken. Note: the dismount event will handle the rest. + if (chair.getFakeSeat() != null) { + chair.getFakeSeat().removePassenger(event.getPlayer()); + } + } + }); + } + + @EventHandler(priority = EventPriority.LOWEST) + private void quit(@NotNull PlayerQuitEvent event) { + Player player = event.getPlayer(); + Chair chair = chairMap.get(player.getUniqueId()); + if (chair != null) { + ChairLeaveEvent leaveEvent = new ChairLeaveEvent(chair, player, exitWhereFacing); + leaveEvent.callEvent(); + } + } + + @EventHandler + private void pistonExtend(@NotNull BlockPistonExtendEvent event) { + for (Block block : event.getBlocks()) { + for (Chair chair : chairs) { + if (chair.getLocation() == null) continue; + if (Util.samePosition(block, chair.getLocation())) { + event.setCancelled(true); + break; + } + } + } + } + + @EventHandler + private void pistonRetract(@NotNull BlockPistonRetractEvent event) { + for (Block block : event.getBlocks()) { + for (Chair chair : chairs) { + if (chair.getLocation() == null) continue; + if (Util.samePosition(block, chair.getLocation())) { + event.setCancelled(true); + break; + } + } + } + } + + @EventHandler + private void onDeath(@NotNull PlayerDeathEvent event) { + Player player = event.getEntity(); + Chair chair = chairMap.get(player.getUniqueId()); + if (chair != null) { + ChairLeaveEvent leaveEvent = new ChairLeaveEvent(chair, player); + leaveEvent.callEvent(); + } + } + + /* + * Sitting and Ejection Methods + */ + + private boolean sitPlayer(@NotNull Chair chair, @NotNull Player player) { + if (chair.isOccupied()) return false; + + ArmorStand fakeSeat = chair.getFakeSeat(); + if (fakeSeat == null) fakeSeat = Util.generateFakeSeat(chair); + + fakeSeat.addPassenger(player); + chair.setFakeSeat(fakeSeat); + fakeSeats.add(fakeSeat.getUniqueId().toString()); + plugin.getConfigManager().getData().set("UUIDs", fakeSeats); + return true; + } + + private void tossPlayer(@NotNull Block block, @NotNull Player player, @NotNull Entity entity) { + Block exit = block; + + if (exitWhereFacing) { + exit = findExitPoint(entity.getLocation(), block); + } + + Location exitLoc = exit.getLocation().add(0.5, 0.5, 0.5); + + if (!canToss) { + return; + } + + if (!faceAttacker) { + exitLoc.setPitch(player.getLocation().getPitch()); + exitLoc.setYaw(player.getLocation().getYaw()); + } else { + exitLoc.setDirection(Util.getVectorDir(player.getLocation(), entity.getLocation())); + } + + if (tossVelocity != 0) { + double finalVelocity = tossVelocity; + if (scaleVelocity && entity instanceof Player) { + if (((Player) entity).isSprinting()) finalVelocity = tossVelocity * scaleAmount; + } + player.setVelocity(exitLoc.getDirection().multiply(finalVelocity)); + } + } + + private Block findExitPoint(Location entity, Block block) { + Block blockToCheck = Util.getBlockFromDirection(block, Util.getCardinalDirection(entity)); + boolean foundValidExit = Util.canFitPlayer(blockToCheck) && Util.safePlace(blockToCheck); + + String[] directions = {"north", "east", "south", "west"}; + for (String direction : directions) { + if (foundValidExit) break; + blockToCheck = Util.getBlockFromDirection(block, direction); + foundValidExit = Util.canFitPlayer(blockToCheck) && Util.safePlace(blockToCheck); + } + if (!foundValidExit) blockToCheck = block.getRelative(BlockFace.UP); + return blockToCheck; + } + + /* + * Cleaning and Clearing + */ + + void saveToggled() { + List ids = new ArrayList<>(); + if (toggled.isEmpty()) { + plugin.getConfigManager().getData().set("Toggled", new ArrayList()); + } + for (UUID id : toggled) { + ids.add(id.toString()); + } + plugin.getLogger().info("Saving " + ids.size() + " Players that had toggled off."); + plugin.getConfigManager().getData().set("Toggled", ids); + } + + void loadToggled() { + List toggled = plugin.getConfigManager().getData().getStringList("Toggled"); + if (toggled.isEmpty()) return; + plugin.getLogger().info(toggled.size() + " Players had toggled off. Adding Them..."); + + toggled.stream() + .map(UUID::fromString) + .forEach(this.toggled::add); + + plugin.getConfigManager().getData().set("Toggled", new ArrayList()); + } + + void shutdown() { + clearChairs(); + clearFakeSeats(); + } + + private void clearChair(Chair chair) { + if (chair == null) return; + if (chair.getPlayer() != null) chair.getPlayer().removePotionEffect(PotionEffectType.REGENERATION); + chair.clear(); + } + + private void clearChairs() { + for (Chair chair : chairs) clearChair(chair); + } + + private void clearPlayer(@NotNull Player player) { + Chair chair = chairMap.get(player.getUniqueId()); + if (chair == null) return; + chairMap.remove(player.getUniqueId()); + chairs.remove(chair); + chair.clear(); + } + + public void clearFakeSeats() { + for (Chair chair : chairs) clearChair(chair); + } + + public void clearFakeSeatsFromFile() { + List fakes = plugin.getConfigManager().getData().getStringList("UUIDs"); + int leftoverFakes = fakes.size(); + if (leftoverFakes >= 1) { + plugin.getLogger().info("Detected " + fakes.size() + " leftover seats! Removing..."); + for (String fake : fakes) { + UUID id = UUID.fromString(fake); + Entity armorStand = plugin.getServer().getEntity(id); + if (armorStand != null) { + armorStand.remove(); + } + } + plugin.getConfigManager().getData().set("UUIDs", new ArrayList()); + } else { + plugin.getLogger().info("No fake seats remaining! Proceeding"); + } + } + + public @NotNull List<@NotNull UUID> getToggled() { + return toggled; + } + + public Vector getStairSeatingPosition() { + return stairSeatingPosition; + } + + public Vector getSlabSeatingPosition() { + return slabSeatingPosition; + } + + public Vector getCarpetSeatingPosition() { + return carpetSeatingPosition; + } +} diff --git a/src/main/java/com/rifledluffy/chairs/MessageManager.java b/src/main/java/com/rifledluffy/chairs/MessageManager.java new file mode 100644 index 0000000..684ee28 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/MessageManager.java @@ -0,0 +1,325 @@ +package com.rifledluffy.chairs; + +import com.github.benmanes.caffeine.cache.Caffeine; +import com.github.benmanes.caffeine.cache.LoadingCache; +import com.rifledluffy.chairs.config.ConfigManager; +import com.rifledluffy.chairs.messages.MessageEvent; +import com.rifledluffy.chairs.messages.MessagePath; +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.ComponentLike; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; +import net.kyori.adventure.util.UTF8ResourceBundleControl; +import org.apache.commons.io.FileUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.jetbrains.annotations.NotNull; + +import java.io.*; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.charset.StandardCharsets; +import java.security.CodeSource; +import java.util.*; +import java.util.logging.Level; +import java.util.regex.Pattern; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +public class MessageManager implements Listener { + private final static @NotNull String BUNDLE_NAME = "messages"; + private final static @NotNull Pattern BUNDLE_FILE_NAME_PATTERN = Pattern.compile(BUNDLE_NAME + "(?:_.*)?.properties"); + private final @NotNull RFChairs plugin = RFChairs.getInstance(); + private final @NotNull List<@NotNull UUID> tempMute = new ArrayList<>(); + private final @NotNull List<@NotNull UUID> muted = new ArrayList<>(); + private ConfigManager configManager = plugin.getConfigManager(); + private boolean allowMessages; + private int tempMuteDuration; + private ResourceBundle messages; + /** + * caches every component without placeholder for faster access in future and loads missing values automatically + */ + private final LoadingCache langCache = Caffeine.newBuilder().build( + path -> MiniMessage.miniMessage().deserialize(getStringFromLang(path))); + + private String saveConvert(@NotNull String theString, boolean escapeSpace) { + int len = theString.length(); + int bufLen = len * 2; + if (bufLen < 0) { + bufLen = Integer.MAX_VALUE; + } + StringBuilder convertedStrBuilder = new StringBuilder(bufLen); + + for (int i = 0; i < theString.length(); i++) { + char aChar = theString.charAt(i); + // Handle common case first + if ((aChar > 61) && (aChar < 127)) { + if (aChar == '\\') { + if (i + 1 < theString.length()) { + final char bChar = theString.charAt(i + 1); + if (bChar == ' ' || bChar == 't' || bChar == 'n' || bChar == 'r' || + bChar == 'f' || bChar == '\\' || bChar == 'u' || bChar == '=' || + bChar == ':' || bChar == '#' || bChar == '!') { + // don't double escape already escaped chars + convertedStrBuilder.append(aChar); + convertedStrBuilder.append(bChar); + i++; + continue; + } else { + // any other char following + convertedStrBuilder.append('\\'); + } + } else { + // last char was a backslash. escape! + convertedStrBuilder.append('\\'); + } + } + convertedStrBuilder.append(aChar); + continue; + } + + // escape non escaped chars that have to get escaped + switch (aChar) { + case ' ' -> { + if (escapeSpace) { + convertedStrBuilder.append('\\'); + } + convertedStrBuilder.append(' '); + } + case '\t' -> convertedStrBuilder.append("\\t"); + case '\n' -> convertedStrBuilder.append("\\n"); + case '\r' -> convertedStrBuilder.append("\\r"); + case '\f' -> convertedStrBuilder.append("\\f"); + case '=', ':', '#', '!' -> { + convertedStrBuilder.append('\\'); + convertedStrBuilder.append(aChar); + } + default -> convertedStrBuilder.append(aChar); + } + } + + return convertedStrBuilder.toString(); + } + + /** + * saves all missing lang files from resources to the plugins data folder + */ + private void initLangFiles() { + CodeSource src = this.getClass().getProtectionDomain().getCodeSource(); + if (src != null) { + URL jarUrl = src.getLocation(); + try (ZipInputStream zipStream = new ZipInputStream(jarUrl.openStream())) { + ZipEntry zipEntry; + while ((zipEntry = zipStream.getNextEntry()) != null) { + if (zipEntry.isDirectory()) { + // already done with topmost layer + break; + } + + String entryName = zipEntry.getName(); + + if (BUNDLE_FILE_NAME_PATTERN.matcher(entryName).matches()) { + File langFile = new File(new File(plugin.getDataFolder(), BUNDLE_NAME), entryName); + if (!langFile.exists()) { // don't overwrite existing files + FileUtils.copyToFile(zipStream, langFile); + } else { // add defaults to file to expand in case there are key-value pairs missing + Properties defaults = new Properties(); + // don't close reader, since we need the stream to be still open for the next entry! + defaults.load(new InputStreamReader(zipStream, StandardCharsets.UTF_8)); + + Properties current = new Properties(); + try (InputStreamReader reader = new InputStreamReader(new FileInputStream(langFile), StandardCharsets.UTF_8)) { + current.load(reader); + } catch (Exception e) { + plugin.getLogger().log(Level.WARNING, "couldn't get current properties file for " + entryName + "!", e); + continue; + } + + try (FileWriter fw = new FileWriter(langFile, StandardCharsets.UTF_8, true); + // we are NOT using Properties#store since it gets rid of comments and doesn't guarantee ordering + BufferedWriter bw = new BufferedWriter(fw)) { + boolean updated = false; // only write comment once + for (Map.Entry translationPair : defaults.entrySet()) { + if (current.get(translationPair.getKey()) == null) { + if (!updated) { + bw.write("# New Values where added. Is everything else up to date? Time of update: " + new Date()); + bw.newLine(); + + plugin.getLogger().fine("Updated langfile \"" + entryName + "\". Might want to check the new translation strings out!"); + + updated = true; + } + + String key = saveConvert((String) translationPair.getKey(), true); + /* No need to escape embedded and trailing spaces for value, hence + * pass false to flag. + */ + String val = saveConvert((String) translationPair.getValue(), false); + bw.write((key + "=" + val)); + bw.newLine(); + } // current already knows the key + } // end of for + } // end of try + } // end of else (file exists) + } // doesn't match + } // end of elements + } catch (IOException e) { + plugin.getLogger().log(Level.WARNING, "Couldn't save lang files", e); + } + } else { + plugin.getLogger().warning("Couldn't save lang files: no CodeSource!"); + } + } + + public void reload() { + configManager = plugin.getConfigManager(); + allowMessages = configManager.getConfig().getBoolean("allow-custom-messages", true); + tempMuteDuration = configManager.getConfig().getInt("temp-mute-duration", 0); + + // get LanguageTag + String localeTag = configManager.getConfig().getString("language", "en"); + messages = null; // reset last bundle + + // save all missing keys + initLangFiles(); + + Locale locale = Locale.forLanguageTag(localeTag); + plugin.getLogger().info("Locale set to language: " + locale.toLanguageTag()); + File langDictionary = new File(plugin.getDataFolder(), BUNDLE_NAME); + + URL[] urls; + try { + urls = new URL[]{langDictionary.toURI().toURL()}; + messages = ResourceBundle.getBundle(BUNDLE_NAME, locale, new URLClassLoader(urls), UTF8ResourceBundleControl.get()); + + } catch (SecurityException | MalformedURLException e) { + plugin.getLogger().log(Level.WARNING, "Exception while reading lang bundle. Using internal", e); + } catch (MissingResourceException ignored) { // how? missing write access? + plugin.getLogger().log(Level.WARNING, "No translation file for " + UTF8ResourceBundleControl.get().toBundleName(BUNDLE_NAME, locale) + " found on disc. Using internal"); + } + + if (messages == null) { // fallback, since we are always trying to save defaults this never should happen + try { + messages = PropertyResourceBundle.getBundle(BUNDLE_NAME, locale, plugin.getClass().getClassLoader(), new UTF8ResourceBundleControl()); + } catch (MissingResourceException e) { + plugin.getLogger().log(Level.SEVERE, "Couldn't get Ressource bundle \"lang\" for locale \"" + locale.toLanguageTag() + "\". Messages WILL be broken!", e); + } + } + } + + private @NotNull String getStringFromLang(@NotNull MessagePath path) { + try { + return messages.getString(path.getPath()); + } catch (MissingResourceException | ClassCastException e) { + plugin.getLogger().log(Level.WARNING, "couldn't find path: \"" + path.getPath() + "\" in lang files using fallback.", e); + return path.getPath(); + } + } + + private void tempMute(@NotNull Player player) { + int duration = tempMuteDuration; + tempMute.add(player.getUniqueId()); + + Bukkit.getScheduler().runTaskLater(plugin, () -> { + if (tempMuted(player)) { + tempMute.remove(player.getUniqueId()); + } + }, duration); + } + + private boolean tempMuted(@NotNull Player player) { + return tempMute.contains(player.getUniqueId()); + } + + /** + * prepend the message with the plugins prefix before sending it to the audience. + */ + public void sendMessageWithoutPrefix(@NotNull Audience audience, @NotNull ComponentLike message) { + audience.sendMessage(message); + } + + /** + * send a component from the lang file to the audience, prefixed with this plugins prefix. + */ + public void sendLang(@NotNull Audience audience, @NotNull MessagePath path) { + audience.sendMessage(Component.text().append(langCache.get(MessagePath.PLUGIN_PREFIX)).appendSpace(). + append(langCache.get(path))); + } + + /** + * send a component from the lang file to the audience, prefixed with this plugins prefix and applying the given tag resolver. + * Note: might be slightly slower than {@link #sendLang(Audience, MessagePath)} since this can not use cache. + */ + public void sendLang(@NotNull Audience audience, @NotNull MessagePath path, @NotNull TagResolver... resolvers) { + audience.sendMessage(Component.text().append(langCache.get(MessagePath.PLUGIN_PREFIX)).appendSpace().append( + MiniMessage.miniMessage().deserialize(getStringFromLang(path), resolvers))); + } + + /** + * get a component from lang file and apply the given tag resolver. + * Note: might be slightly slower than {@link #getLang(MessagePath)} since this can not use cache. + */ + public @NotNull Component getLang(@NotNull MessagePath path, @NotNull TagResolver resolver) { + return MiniMessage.miniMessage().deserialize(getStringFromLang(path), resolver); + } + + /** + * get a component from lang file + */ + public @NotNull Component getLang(@NotNull MessagePath path) { + return langCache.get(path); + } + + @EventHandler(ignoreCancelled = true) + private void onMessage(@NotNull MessageEvent event) { + if (event.getAudience() instanceof Player player) { + if (tempMute.contains(player.getUniqueId())) { + event.setCancelled(true); + return; + } + + if (tempMuteDuration > 0) { + tempMute(player); + } + if (allowMessages && !muted.contains(player.getUniqueId())) { + sendLang(event.getAudience(), event.getType(), event.getResolvers()); + } + } else { // only players can be muted + sendLang(event.getAudience(), event.getType(), event.getResolvers()); + } + } + + void saveMuted() { + List ids = new ArrayList<>(); + if (muted.isEmpty()) { + configManager.getData().set("Muted", new ArrayList()); + } + + for (UUID id : muted) { + ids.add(id.toString()); + } + plugin.getLogger().info("Saving " + ids.size() + " Players that had events muted."); + configManager.getData().set("Muted", ids); + } + + void loadMuted() { + List muted = configManager.getData().getStringList("Muted"); + if (muted.isEmpty()) { + return; + } + plugin.getServer().getLogger().info(muted.size() + " Players had events muted off. Adding Them..."); + for (String toggler : muted) { + UUID id = UUID.fromString(toggler); + this.muted.add(id); + } + configManager.getData().set("Muted", new ArrayList()); + } + + public @NotNull List<@NotNull UUID> getMuted() { + return muted; + } +} diff --git a/src/main/java/com/rifledluffy/chairs/RFChairs.java b/src/main/java/com/rifledluffy/chairs/RFChairs.java new file mode 100644 index 0000000..85abf61 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/RFChairs.java @@ -0,0 +1,132 @@ +package com.rifledluffy.chairs; + +import com.rifledluffy.chairs.chairs.BlockFilter; +import com.rifledluffy.chairs.command.CommandManager; +import com.rifledluffy.chairs.config.ConfigManager; +import com.rifledluffy.chairs.dependencymanagers.WorldGuardManager; +import org.bstats.bukkit.Metrics; +import org.bukkit.Bukkit; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.jetbrains.annotations.NotNull; + +public class RFChairs extends JavaPlugin { + private static RFChairs instance; + private CommandManager commandManager; + private ConfigManager cfgManager; + private ChairManager chairManager; + private MessageManager messageManager; + private WorldGuardManager worldGuardManager; + + public static @NotNull RFChairs getInstance() { + return instance; + } + + private static void setInstance(@NotNull RFChairs instance) { + RFChairs.instance = instance; + } + + @Override + public void onLoad() { + setInstance(this); + loadWorldGuard(); + } + + private void loadWorldGuard() { + try { + Class.forName("com.sk89q.worldguard.WorldGuard"); + Class.forName("com.sk89q.worldedit.WorldEdit"); + Class.forName("com.sk89q.worldedit.math.BlockVector3"); + worldGuardManager = new WorldGuardManager(); + worldGuardManager.setup(); + getLogger().info("Found WorldGuard && WorldEdit! Applying Custom Flag..."); + } catch (ClassNotFoundException e) { + getLogger().info("Missing either WorldGuard or WorldEdit! Disabling Custom Flag Features..."); + getLogger().info("Latest WorldGuard/WorldEdit features could be missing. Please Update!"); + } + + if (worldGuardManager != null) { + worldGuardManager.register(); + } + } + + @Override + public void onEnable() { + @SuppressWarnings("unused") + Metrics metrics = new Metrics(this, 2979); + + commandManager = new CommandManager(); + commandManager.setup(); + + loadConfigManager(); + + chairManager = new ChairManager(this); + chairManager.clearFakeSeatsFromFile(); + chairManager.loadToggled(); + + messageManager = new MessageManager(); + messageManager.loadMuted(); + + BlockFilter.reload(); + chairManager.reload(); + messageManager.reload(); + getServer().getPluginManager().registerEvents(chairManager, this); + getServer().getPluginManager().registerEvents(messageManager, this); + + getLogger().info("Rifle's Chairs has been enabled!"); + } + + @Override + public void onDisable() { + chairManager.saveToggled(); + messageManager.saveMuted(); + + chairManager.shutdown(); + + getLogger().info("Saving Configuration Files!"); + cfgManager.saveData(); + + Bukkit.getOnlinePlayers().forEach(p -> { // todo just clearing regen from everyone is NOT right. should only clear sitting players + PotionEffect regen = p.getPotionEffect(PotionEffectType.REGENERATION); + if (regen == null) return; + if (regen.getDuration() > 1000) p.removePotionEffect(PotionEffectType.REGENERATION); + }); + + getLogger().info("Rifle's Chairs has been disabled!"); + } + + public void loadConfigManager() { + cfgManager = new ConfigManager(); + cfgManager.setup(); + cfgManager.reloadConfig(); + } + + public ConfigManager getConfigManager() { + return cfgManager; + } + + public void setConfigManager(ConfigManager configManager) { + this.cfgManager = configManager; + } + + public MessageManager getMessageManager() { + return messageManager; + } + + public ChairManager getChairManager() { + return chairManager; + } + + public CommandManager getCommandManager() { + return commandManager; + } + + public WorldGuardManager getWorldGuardManager() { + return this.worldGuardManager; + } + + boolean hasWorldGuard() { + return worldGuardManager != null; + } +} diff --git a/src/main/java/com/rifledluffy/chairs/RFChairsLoader.java b/src/main/java/com/rifledluffy/chairs/RFChairsLoader.java new file mode 100644 index 0000000..9d81f2e --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/RFChairsLoader.java @@ -0,0 +1,27 @@ +package com.rifledluffy.chairs; + +import io.papermc.paper.plugin.loader.PluginClasspathBuilder; +import io.papermc.paper.plugin.loader.PluginLoader; +import io.papermc.paper.plugin.loader.library.impl.MavenLibraryResolver; +import org.eclipse.aether.artifact.DefaultArtifact; +import org.eclipse.aether.graph.Dependency; +import org.eclipse.aether.repository.RemoteRepository; +import org.jetbrains.annotations.NotNull; + +@SuppressWarnings("UnstableApiUsage") +public class RFChairsLoader implements PluginLoader { + @Override + public void classloader(@NotNull PluginClasspathBuilder classpathBuilder) { + classpathBuilder.getContext().getLogger().info("loading RFChairs libraries!"); + + MavenLibraryResolver resolver = new MavenLibraryResolver(); + resolver.addRepository(new RemoteRepository.Builder("central", "default", "https://repo1.maven.org/maven2/").build()); + resolver.addRepository(new RemoteRepository.Builder("bstats", "default", "https://repo.codemc.org/repository/maven-public").build()); + + resolver.addDependency(new Dependency(new DefaultArtifact("org.bstats:bstats-bukkit:3.1.0"), null)); // todo insert versions + resolver.addDependency(new Dependency(new DefaultArtifact("com.github.ben-manes.caffeine:caffeine:3.1.8"), null)); + System.setProperty("bstats.relocatecheck", "false"); // bstats author is stubborn and only allows the use via relocation. + + classpathBuilder.addLibrary(resolver); + } +} diff --git a/src/main/java/com/rifledluffy/chairs/TargetInfo.java b/src/main/java/com/rifledluffy/chairs/TargetInfo.java new file mode 100644 index 0000000..6dd86df --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/TargetInfo.java @@ -0,0 +1,54 @@ +package com.rifledluffy.chairs; + +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.projectiles.ProjectileSource; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class TargetInfo { + private final @NotNull Entity attacker; + private final @Nullable ProjectileSource source; + private final double damage; + private boolean sprinting = false; + + protected TargetInfo(@NotNull ProjectileSource source, @NotNull Entity attacker, double damage) { + this.source = source; + this.attacker = attacker; + this.damage = damage; + } + + protected TargetInfo(@NotNull Entity attacker, double damage) { + this.source = null; + if (attacker instanceof Player player) { + sprinting = player.isSprinting(); + } + this.attacker = attacker; + this.damage = damage; + } + + protected @NotNull Entity getAttacker() { + return attacker; + } + + protected LivingEntity getLivingSource() { + return (LivingEntity) source; + } + + protected double getDamage() { + return damage; + } + + protected boolean isSprinting() { + return this.sprinting; + } + + protected boolean hasSource() { + return source != null; + } + + protected boolean livingSource() { + return source instanceof LivingEntity; + } +} diff --git a/src/main/java/com/rifledluffy/chairs/chairs/BlockFilter.java b/src/main/java/com/rifledluffy/chairs/chairs/BlockFilter.java new file mode 100644 index 0000000..c37a6a7 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/chairs/BlockFilter.java @@ -0,0 +1,82 @@ +package com.rifledluffy.chairs.chairs; + +import com.rifledluffy.chairs.RFChairs; +import org.bukkit.Material; +import org.bukkit.Tag; +import org.bukkit.configuration.file.FileConfiguration; +import org.jetbrains.annotations.NotNull; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class BlockFilter { + private static Set<@NotNull String> whitelist, blacklist; + + public static void reload() { + FileConfiguration config = RFChairs.getInstance().getConfig(); + whitelist = new HashSet<>(config.getStringList("whitelisted-chairs")); + + // dataFixerUpper + if (config.contains("allowed-chairs")) { + whitelist.addAll(config.getStringList("allowed-chairs")); + config.set("allowed-chairs", null); + config.set("whitelisted-chairs", List.copyOf(whitelist)); + RFChairs.getInstance().saveConfig(); + } + + blacklist = new HashSet<>(config.getStringList("blacklisted-chairs")); + } + + public static boolean isWhitelisted(@NotNull Material type, @NotNull ChairCategory category) { + return whitelist.contains(category.getConfigName()) || whitelist.contains(type.name()); + } + + public static boolean isBlacklisted(@NotNull Material type, @NotNull ChairCategory category) { + return blacklist.contains(category.getConfigName()) || blacklist.contains(type.name()); + } + + // validate + + public static boolean validateCarpet(@NotNull Material type) { + return isWhitelisted(type, ChairCategory.CARPETS) && !isBlacklisted(type, ChairCategory.CARPETS); + } + + public static boolean validateSlab(@NotNull Material type) { + return isWhitelisted(type, ChairCategory.SLABS) && !isBlacklisted(type, ChairCategory.SLABS); + } + + public static boolean validateStairs(@NotNull Material type) { + return isWhitelisted(type, ChairCategory.STAIRS) && !isBlacklisted(type, ChairCategory.STAIRS); + } + + // check + + public static boolean isCarpetBlock(@NotNull Material type) { + return Tag.WOOL_CARPETS.isTagged(type); + } + + public static boolean isSlabBlock(@NotNull Material type) { + return Tag.SLABS.isTagged(type); + } + + public static boolean isStairsBlock(@NotNull Material type) { + return Tag.STAIRS.isTagged(type); + } + + public enum ChairCategory { + SLABS("ALL_SLABS"), + STAIRS("ALL_STAIRS"), + CARPETS("ALL_CARPETS"); + + private final String configName; + + ChairCategory(String configName) { + this.configName = configName; + } + + public String getConfigName() { + return configName; + } + } +} diff --git a/src/main/java/com/rifledluffy/chairs/chairs/Chair.java b/src/main/java/com/rifledluffy/chairs/chairs/Chair.java new file mode 100644 index 0000000..8646fb8 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/chairs/Chair.java @@ -0,0 +1,131 @@ +package com.rifledluffy.chairs.chairs; + +import com.rifledluffy.chairs.RFChairs; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.BlockState; +import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.type.Stairs; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class Chair { + private final BukkitRunnable clear; + private final int clearID; + + private @Nullable Location location; + private @Nullable Block chair; + private ArmorStand fakeSeat = null; + private @Nullable Player player; + + public Chair(@NotNull Player player, @NotNull Location location) { + this.location = location; + this.player = player; + this.chair = location.getBlock(); + + clear = new BukkitRunnable() { + + @Override + public void run() { + if (fakeSeat == null) { + clear(); + return; + } + if (fakeSeat.getPassengers().isEmpty()) { + clear(); + } + } + + }; + clearID = clear.runTaskTimer(RFChairs.getInstance(), 20, 20).getTaskId(); + } + + /* + * Getters + */ + + public @Nullable ArmorStand getFakeSeat() { + return fakeSeat; + } + + public void setFakeSeat(@NotNull ArmorStand armorStand) { + fakeSeat = armorStand; + } + + public @Nullable Player getPlayer() { + return player; + } + + public void setPlayer(@NotNull Player player) { + this.player = player; + } + + public @Nullable Block getBlock() { + if (location == null) { + return null; + } else { + return location.getBlock(); + } + } + + public @Nullable BlockState getBlockState() { + if (chair == null) { + return null; + } else { + return chair.getState(); + } + } + + public @Nullable BlockData getBlockData() { + if (chair == null) { + return null; + } else { + return chair.getState().getBlockData(); + } + } + + public @Nullable BlockFace getFacing() { + if (chair != null && BlockFilter.isStairsBlock(chair.getType())) { + return ((Stairs) chair.getState().getBlockData()).getFacing(); + } + return null; + } + + /* + * Setters + */ + + public @Nullable Location getLocation() { + return location; + } + + /* + * Methods + */ + + public boolean isOccupied() { + return !(fakeSeat == null) && !fakeSeat.isEmpty(); + } + + public void clear() { + if (fakeSeat != null) { + fakeSeat.remove(); + } + if (player != null) { + player.removePotionEffect(PotionEffectType.REGENERATION); + } + chair = null; + location = null; + fakeSeat = null; + player = null; + if (Bukkit.getScheduler().isCurrentlyRunning(clearID)) { + clear.cancel(); + } + } +} diff --git a/src/main/java/com/rifledluffy/chairs/command/CommandManager.java b/src/main/java/com/rifledluffy/chairs/command/CommandManager.java new file mode 100644 index 0000000..e6f5471 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/command/CommandManager.java @@ -0,0 +1,124 @@ +package com.rifledluffy.chairs.command; + +import com.rifledluffy.chairs.RFChairs; +import com.rifledluffy.chairs.command.commands.*; +import com.rifledluffy.chairs.messages.MessagePath; +import com.rifledluffy.chairs.messages.PlaceHolder; +import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; +import org.bukkit.Location; +import org.bukkit.command.*; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class CommandManager extends Command { + private static final String MAIN_COMMAND = "rfchairs"; + private final @NotNull ArrayList<@NotNull SubCommand> subCommands = new ArrayList<>(); + + public CommandManager() { + super(MAIN_COMMAND, "The main prefix for other commands. Type /rfchairs help for more info", "/", List.of("rfc")); + } + + public static @NotNull String getMainCommand() { + return MAIN_COMMAND; + } + + public void setup() { + RFChairs.getInstance().getServer().getCommandMap().register("rfchairs", this); + + this.subCommands.add(new HelpCommand()); + //this.commands.add(new InfoCommand()); + this.subCommands.add(new ReloadCommand()); + this.subCommands.add(new ResetCommand()); + this.subCommands.add(new ToggleCommand()); + this.subCommands.add(new MuteCommand()); + } + + @Override + public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) { + if (args.length == 0) { + RFChairs.getInstance().getMessageManager().sendLang(sender, MessagePath.COMMAND_NOT_ENOUGH_ARGS); + return true; + } + + SubCommand target = this.getSubcommand(args[0]); + + if (target == null) { + RFChairs.getInstance().getMessageManager().sendLang(sender, MessagePath.COMMAND_INVALID_SUBCOMMAND, + Placeholder.unparsed(PlaceHolder.ARGUMENT.getPlaceholder(), args[0])); + return true; + } + + // clear args from subcommand + ArrayList subcommandArgList = new ArrayList<>(Arrays.asList(args)); + subcommandArgList.removeFirst(); + + if (target.checkPermission(sender)) { + if (target.needsPlayer()) { + if (sender instanceof Player player) { + target.onPlayerCommand(player, subcommandArgList); + } else { + RFChairs.getInstance().getMessageManager().sendLang(sender, MessagePath.COMMAND_NOT_PLAYER); + } + } else { + target.onCommand(sender, subcommandArgList); + } + } else { + RFChairs.getInstance().getMessageManager().sendLang(sender, MessagePath.COMMAND_NO_PERMISSION); + } + + return true; + } + + private @Nullable SubCommand getSubcommand(@NotNull String name) { + for (SubCommand sc : this.subCommands) { + if (sc.name().equalsIgnoreCase(name)) { + return sc; + } + + String[] aliases = sc.aliases(); + for (String alias : aliases) { + if (name.equalsIgnoreCase(alias)) { + return sc; + } + + } + } + return null; + } + + public @NotNull ArrayList<@NotNull SubCommand> getSubCommands() { + return subCommands; + } + + @Override + public @NotNull List tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args, @Nullable Location location) { + if (args.length == 1) { + List result = new ArrayList<>(); + + for (SubCommand subCommand : subCommands) { + if (subCommand.checkPermission(sender)) { + result.add(subCommand.name()); + } + } + + return result; + } else if (args.length > 1) { + SubCommand subCommand = this.getSubcommand(args[0]); + + if (subCommand != null && subCommand.checkPermission(sender)) { + // clear args from subcommand + ArrayList subcommandArgList = new ArrayList<>(Arrays.asList(args)); + subcommandArgList.removeFirst(); + + return subCommand.onTabComplete(sender, subcommandArgList); + } + } + + return List.of(); + } +} diff --git a/src/main/java/com/rifledluffy/chairs/command/commands/HelpCommand.java b/src/main/java/com/rifledluffy/chairs/command/commands/HelpCommand.java new file mode 100644 index 0000000..6975e26 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/command/commands/HelpCommand.java @@ -0,0 +1,75 @@ +package com.rifledluffy.chairs.command.commands; + +import com.rifledluffy.chairs.MessageManager; +import com.rifledluffy.chairs.RFChairs; +import com.rifledluffy.chairs.command.CommandManager; +import com.rifledluffy.chairs.messages.MessagePath; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.minimessage.MiniMessage; +import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.permissions.Permissible; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public class HelpCommand implements SubCommand { + + public void onCommand(@NotNull CommandSender sender, @NotNull List<@NotNull String> args) { + TextComponent.Builder builder = Component.text(); + MessageManager messageManager = RFChairs.getInstance().getMessageManager(); + String rawCommand = "/" + CommandManager.getMainCommand() + " | "; + + builder.append(messageManager.getLang(MessagePath.COMMAND_HELP_HEADER)).appendNewline(); + builder.append(messageManager.getLang(MessagePath.COMMAND_HELP_MAIN)).appendNewline(); + + + for (SubCommand subCommand : RFChairs.getInstance().getCommandManager().getSubCommands()) { + if (subCommand.checkPermission(sender)) { + builder.append(MiniMessage.miniMessage().deserialize(rawCommand, Placeholder.unparsed("cmd", subCommand.name()))). + append(subCommand.info().color(NamedTextColor.GRAY)).appendNewline(); + } + } + builder.append(messageManager.getLang(MessagePath.COMMAND_HELP_FOOTER)); + + messageManager.sendMessageWithoutPrefix(sender, builder); + } + + @Override + public void onPlayerCommand(@NotNull Player player, @NotNull List<@NotNull String> args) { + onCommand(player, args); + } + + @Override + public @NotNull String name() { + return "help"; + } + + @Override + public @NotNull Component info() { + return RFChairs.getInstance().getMessageManager().getLang(MessagePath.COMMAND_HELP_INFO); + } + + @Override + public @NotNull String @NotNull [] aliases() { + return new String[0]; + } + + @Override + public boolean needsPlayer() { + return false; + } + + @Override + public boolean checkPermission(@NotNull Permissible permissible) { + return true; + } + + @Override + public @NotNull List<@NotNull String> onTabComplete(@NotNull CommandSender sender, @NotNull List<@NotNull String> args) { + return List.of(); + } +} \ No newline at end of file diff --git a/src/main/java/com/rifledluffy/chairs/command/commands/InfoCommand.java b/src/main/java/com/rifledluffy/chairs/command/commands/InfoCommand.java new file mode 100644 index 0000000..e86bd28 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/command/commands/InfoCommand.java @@ -0,0 +1,51 @@ +package com.rifledluffy.chairs.command.commands; + +import net.kyori.adventure.text.Component; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.permissions.Permissible; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public class InfoCommand implements SubCommand { //todo + + @Override + public void onCommand(@NotNull CommandSender sender, @NotNull List<@NotNull String> args) { + + } + + @Override + public void onPlayerCommand(@NotNull Player player, @NotNull List<@NotNull String> args) { + } + + @Override + public @NotNull String name() { + return "info"; + } + + @Override + public @NotNull Component info() { + return Component.empty(); + } + + @Override + public String @NotNull [] aliases() { + return new String[0]; + } + + @Override + public boolean needsPlayer() { + return true; + } + + @Override + public boolean checkPermission(@NotNull Permissible permissible) { + return permissible.hasPermission("rfchairs.info"); + } + + @Override + public @NotNull List<@NotNull String> onTabComplete(@NotNull CommandSender sender, @NotNull List<@NotNull String> args) { + return List.of(); + } +} \ No newline at end of file diff --git a/src/main/java/com/rifledluffy/chairs/command/commands/MuteCommand.java b/src/main/java/com/rifledluffy/chairs/command/commands/MuteCommand.java new file mode 100644 index 0000000..9d17477 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/command/commands/MuteCommand.java @@ -0,0 +1,62 @@ +package com.rifledluffy.chairs.command.commands; + +import com.rifledluffy.chairs.MessageManager; +import com.rifledluffy.chairs.RFChairs; +import com.rifledluffy.chairs.messages.MessagePath; +import net.kyori.adventure.text.Component; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.permissions.Permissible; +import org.jetbrains.annotations.NotNull; + +import java.util.List; +import java.util.UUID; + +public class MuteCommand implements SubCommand { + + public void onCommand(@NotNull CommandSender sender, @NotNull List<@NotNull String> args) { + } + + @Override + public void onPlayerCommand(@NotNull Player player, @NotNull List<@NotNull String> args) { + MessageManager messageManager = RFChairs.getInstance().getMessageManager(); + List muted = messageManager.getMuted(); + if (muted.contains(player.getUniqueId())) { + messageManager.sendLang(player, MessagePath.COMMAND_MUTE_ENABLED); + muted.remove(player.getUniqueId()); + } else { + messageManager.sendLang(player, MessagePath.COMMAND_MUTE_DISABLED); + muted.add(player.getUniqueId()); + } + } + + @Override + public @NotNull String name() { + return "mute"; + } + + @Override + public @NotNull Component info() { + return RFChairs.getInstance().getMessageManager().getLang(MessagePath.COMMAND_MUTE_INFO); + } + + @Override + public String @NotNull [] aliases() { + return new String[0]; + } + + @Override + public boolean needsPlayer() { + return true; + } + + @Override + public boolean checkPermission(@NotNull Permissible permissible) { + return permissible.hasPermission("rfchairs.mute"); + } + + @Override + public @NotNull List<@NotNull String> onTabComplete(@NotNull CommandSender sender, @NotNull List<@NotNull String> args) { + return List.of(); + } +} diff --git a/src/main/java/com/rifledluffy/chairs/command/commands/ReloadCommand.java b/src/main/java/com/rifledluffy/chairs/command/commands/ReloadCommand.java new file mode 100644 index 0000000..83e4d26 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/command/commands/ReloadCommand.java @@ -0,0 +1,63 @@ +package com.rifledluffy.chairs.command.commands; + +import com.rifledluffy.chairs.RFChairs; +import com.rifledluffy.chairs.chairs.BlockFilter; +import com.rifledluffy.chairs.config.ConfigManager; +import com.rifledluffy.chairs.messages.MessagePath; +import net.kyori.adventure.text.Component; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.permissions.Permissible; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public class ReloadCommand implements SubCommand { + private final RFChairs plugin = RFChairs.getInstance(); + + @Override + public void onCommand(@NotNull CommandSender sender, @NotNull List<@NotNull String> args) { + ConfigManager newConfig = plugin.getConfigManager(); + newConfig.reloadConfig(); + plugin.setConfigManager(newConfig); + BlockFilter.reload(); + plugin.getChairManager().reload(); + plugin.getMessageManager().reload(); + plugin.getMessageManager().sendLang(sender, MessagePath.COMMAND_RELOAD_SUCCESS); + } + + @Override + public void onPlayerCommand(@NotNull Player player, @NotNull List<@NotNull String> args) { + onCommand(player, args); + } + + @Override + public @NotNull String name() { + return "reload"; + } + + @Override + public @NotNull Component info() { + return RFChairs.getInstance().getMessageManager().getLang(MessagePath.COMMAND_RELOAD_INFO); + } + + @Override + public String @NotNull [] aliases() { + return new String[0]; + } + + @Override + public boolean needsPlayer() { + return false; + } + + @Override + public boolean checkPermission(@NotNull Permissible permissible) { + return permissible.hasPermission("rfchairs.reload") || permissible.hasPermission("rfchairs.manage"); + } + + @Override + public @NotNull List<@NotNull String> onTabComplete(@NotNull CommandSender sender, @NotNull List<@NotNull String> args) { + return List.of(); + } +} diff --git a/src/main/java/com/rifledluffy/chairs/command/commands/ResetCommand.java b/src/main/java/com/rifledluffy/chairs/command/commands/ResetCommand.java new file mode 100644 index 0000000..985bfa3 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/command/commands/ResetCommand.java @@ -0,0 +1,58 @@ +package com.rifledluffy.chairs.command.commands; + +import com.rifledluffy.chairs.RFChairs; +import com.rifledluffy.chairs.messages.MessagePath; +import net.kyori.adventure.text.Component; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.permissions.Permissible; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +public class ResetCommand implements SubCommand { + private final RFChairs plugin = RFChairs.getInstance(); + + public void onCommand(@NotNull CommandSender sender, @NotNull List<@NotNull String> args) { + plugin.getChairManager().clearFakeSeats(); + plugin.getChairManager().clearFakeSeatsFromFile(); + plugin.getLogger().info("Chairs Reset!"); + + plugin.getMessageManager().sendLang(sender, MessagePath.COMMAND_RESET_SUCCESS); + } + + @Override + public void onPlayerCommand(@NotNull Player player, @NotNull List<@NotNull String> args) { + onCommand(player, args); + } + + @Override + public @NotNull String name() { + return "reset"; + } + + @Override + public @NotNull Component info() { + return plugin.getMessageManager().getLang(MessagePath.COMMAND_RESET_INFO); + } + + @Override + public @NotNull String @NotNull [] aliases() { + return new String[0]; + } + + @Override + public boolean needsPlayer() { + return false; + } + + @Override + public boolean checkPermission(@NotNull Permissible permissible) { + return permissible.hasPermission("rfchairs.reset") || permissible.hasPermission("rfchairs.manage"); + } + + @Override + public @NotNull List<@NotNull String> onTabComplete(@NotNull CommandSender sender, @NotNull List<@NotNull String> args) { + return List.of(); + } +} \ No newline at end of file diff --git a/src/main/java/com/rifledluffy/chairs/command/commands/SubCommand.java b/src/main/java/com/rifledluffy/chairs/command/commands/SubCommand.java new file mode 100644 index 0000000..58c7967 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/command/commands/SubCommand.java @@ -0,0 +1,31 @@ +package com.rifledluffy.chairs.command.commands; + +import net.kyori.adventure.text.Component; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.permissions.Permissible; +import org.jetbrains.annotations.NotNull; + +import java.util.List; + +/** + * / args[0] args[1] + */ +public interface SubCommand { + + void onCommand(@NotNull CommandSender sender, @NotNull List<@NotNull String> args); + + void onPlayerCommand(@NotNull Player player, @NotNull List<@NotNull String> args); + + @NotNull String name(); + + @NotNull Component info(); + + @NotNull String @NotNull [] aliases(); // funny thing: No subcommand defines an alias at time of writing this + + boolean needsPlayer(); + + boolean checkPermission(@NotNull Permissible permissible); + + @NotNull List<@NotNull String> onTabComplete(@NotNull CommandSender sender, @NotNull List<@NotNull String> args); +} diff --git a/src/main/java/com/rifledluffy/chairs/command/commands/ToggleCommand.java b/src/main/java/com/rifledluffy/chairs/command/commands/ToggleCommand.java new file mode 100644 index 0000000..84e6e6d --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/command/commands/ToggleCommand.java @@ -0,0 +1,67 @@ +package com.rifledluffy.chairs.command.commands; + +import com.rifledluffy.chairs.MessageManager; +import com.rifledluffy.chairs.RFChairs; +import com.rifledluffy.chairs.messages.MessagePath; +import com.rifledluffy.chairs.messages.PlaceHolder; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.permissions.Permissible; +import org.jetbrains.annotations.NotNull; + +import java.util.List; +import java.util.UUID; + +public class ToggleCommand implements SubCommand { + + public void onCommand(@NotNull CommandSender sender, @NotNull List<@NotNull String> args) { + } + + @Override + public void onPlayerCommand(@NotNull Player player, @NotNull List<@NotNull String> args) { + MessageManager messageManager = RFChairs.getInstance().getMessageManager(); + List toggled = RFChairs.getInstance().getChairManager().getToggled(); + + if (toggled.contains(player.getUniqueId())) { + messageManager.sendLang(player, MessagePath.COMMAND_TOGGLE_ENABLED, + Placeholder.component(PlaceHolder.PLAYER.getPlaceholder(), player.displayName())); + toggled.remove(player.getUniqueId()); + } else { + messageManager.sendLang(player, MessagePath.COMMAND_TOGGLE_DISABLED, + Placeholder.component(PlaceHolder.PLAYER.getPlaceholder(), player.displayName())); + toggled.add(player.getUniqueId()); + } + } + + @Override + public @NotNull String name() { + return "toggle"; + } + + @Override + public @NotNull Component info() { + return RFChairs.getInstance().getMessageManager().getLang(MessagePath.COMMAND_TOGGLE_INFO); + } + + @Override + public @NotNull String @NotNull [] aliases() { + return new String[0]; + } + + @Override + public boolean needsPlayer() { + return true; + } + + @Override + public boolean checkPermission(@NotNull Permissible permissible) { + return permissible.hasPermission("rfchairs.toggle"); + } + + @Override + public @NotNull List<@NotNull String> onTabComplete(@NotNull CommandSender sender, @NotNull List<@NotNull String> args) { + return List.of(); + } +} diff --git a/src/main/java/com/rifledluffy/chairs/config/ConfigManager.java b/src/main/java/com/rifledluffy/chairs/config/ConfigManager.java new file mode 100644 index 0000000..92818e8 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/config/ConfigManager.java @@ -0,0 +1,75 @@ +package com.rifledluffy.chairs.config; + +import com.rifledluffy.chairs.RFChairs; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.plugin.java.JavaPlugin; + +import java.io.File; +import java.io.IOException; + +public class ConfigManager { + private final JavaPlugin plugin = RFChairs.getPlugin(RFChairs.class); + private FileConfiguration config; + /* + * Configuration Files + */ + private File configFile; + private FileConfiguration fake; + private File fakeFile; + + public void setup() { + configFile = new File(plugin.getDataFolder(), "config.yml"); + config = plugin.getConfig(); + config.options().copyDefaults(true); + saveConfig(); + + if (!plugin.getDataFolder().exists()) { + plugin.getDataFolder().mkdir(); + } + + fakeFile = new File(plugin.getDataFolder(), "fakes.yml"); + + if (!fakeFile.exists()) { + try { + fakeFile.createNewFile(); + } catch (IOException e) { + plugin.getLogger().info("Could not create fakes.yml!"); + } + } + + fake = YamlConfiguration.loadConfiguration(fakeFile); + } + + public FileConfiguration getData() { + return fake; + } + + public void saveData() { + try { + fake.save(fakeFile); + } catch (IOException e) { + plugin.getLogger().info("Could not save fakes.yml!"); + } + } + + public void reloadData() { + fake = YamlConfiguration.loadConfiguration(fakeFile); + } + + public FileConfiguration getConfig() { + return config; + } + + public void saveConfig() { + try { + config.save(configFile); + } catch (IOException e) { + plugin.getLogger().info("[Rifle's Chairs] Could not save config.yml!"); + } + } + + public void reloadConfig() { + config = YamlConfiguration.loadConfiguration(configFile); + } +} \ No newline at end of file diff --git a/src/main/java/com/rifledluffy/chairs/dependencymanagers/WorldGuardManager.java b/src/main/java/com/rifledluffy/chairs/dependencymanagers/WorldGuardManager.java new file mode 100644 index 0000000..0e7293a --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/dependencymanagers/WorldGuardManager.java @@ -0,0 +1,76 @@ +package com.rifledluffy.chairs.dependencymanagers; + +import com.rifledluffy.chairs.RFChairs; +import com.rifledluffy.chairs.chairs.Chair; +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldguard.LocalPlayer; +import com.sk89q.worldguard.WorldGuard; +import com.sk89q.worldguard.bukkit.WorldGuardPlugin; +import com.sk89q.worldguard.protection.ApplicableRegionSet; +import com.sk89q.worldguard.protection.flags.StateFlag; +import com.sk89q.worldguard.protection.flags.registry.FlagConflictException; +import com.sk89q.worldguard.protection.flags.registry.FlagRegistry; +import com.sk89q.worldguard.protection.managers.RegionManager; +import com.sk89q.worldguard.protection.regions.RegionContainer; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class WorldGuardManager { + private static StateFlag flag; + private final RFChairs plugin = RFChairs.getInstance(); + private WorldGuard worldGuard; + + public WorldGuardManager() { + } + + public void setup() { + worldGuard = WorldGuard.getInstance(); + } + + public void register() { + flag = new StateFlag("allow-seating", true); + FlagRegistry registry = WorldGuard.getInstance().getFlagRegistry(); + try { + registry.register(flag); + plugin.getComponentLogger().info("Custom Flag Registered!"); + } catch (FlagConflictException | IllegalStateException e) { + plugin.getComponentLogger().warn("Unable to register custom worldguard flag!", e); + } + } + + public @Nullable WorldGuardPlugin getWorldGuard() { // todo cache the plugin + Plugin plugin = this.plugin.getServer().getPluginManager().getPlugin("WorldGuard"); + + if (plugin instanceof WorldGuardPlugin worldGuardPlugin) { + return worldGuardPlugin; + } else { + return null; + } + } + + public boolean validateSeating(@NotNull Chair chair, @NotNull Player player) { + RegionContainer container = getContainer(); + Location chairLocation = chair.getLocation(); + RegionManager regionManager = container.get(BukkitAdapter.adapt(chairLocation.getWorld())); + + if (regionManager != null) { + com.sk89q.worldedit.util.Location weLoc = BukkitAdapter.adapt(chairLocation); + LocalPlayer wgPlayer = getWorldGuard().wrapPlayer(player); + ApplicableRegionSet applicableRegions = regionManager.getApplicableRegions(weLoc.toVector().toBlockPoint()); + return applicableRegions.testState(wgPlayer, getFlag()); + } else { + return true; + } + } + + public RegionContainer getContainer() { + return worldGuard.getPlatform().getRegionContainer(); + } + + public @NotNull StateFlag getFlag() { + return flag; + } +} diff --git a/src/main/java/com/rifledluffy/chairs/events/ChairCheckEvent.java b/src/main/java/com/rifledluffy/chairs/events/ChairCheckEvent.java new file mode 100644 index 0000000..cbba584 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/events/ChairCheckEvent.java @@ -0,0 +1,49 @@ +package com.rifledluffy.chairs.events; + +import com.rifledluffy.chairs.chairs.Chair; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class ChairCheckEvent extends Event { + private static final @NotNull HandlerList handlers = new HandlerList(); + private final @Nullable Chair chair; + private final @Nullable Block block; + private final @NotNull Player player; + + public ChairCheckEvent(@NotNull Chair chair, @NotNull Player player) { + this.chair = chair; + this.block = null; + this.player = player; + } + + public ChairCheckEvent(@NotNull Block block, @NotNull Player player) { + this.chair = null; + this.block = block; + this.player = player; + } + + static public @NotNull HandlerList getHandlerList() { + return handlers; + } + + public @Nullable Chair getChair() { + return this.chair; + } + + public @Nullable Block getBlock() { + return this.block; + } + + public @NotNull Player getPlayer() { + return this.player; + } + + @Override + public @NotNull HandlerList getHandlers() { + return handlers; + } +} diff --git a/src/main/java/com/rifledluffy/chairs/events/ChairLeaveEvent.java b/src/main/java/com/rifledluffy/chairs/events/ChairLeaveEvent.java new file mode 100644 index 0000000..623cb0b --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/events/ChairLeaveEvent.java @@ -0,0 +1,46 @@ +package com.rifledluffy.chairs.events; + +import com.rifledluffy.chairs.chairs.Chair; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +public class ChairLeaveEvent extends Event { + private static final @NotNull HandlerList handlers = new HandlerList(); + private final @NotNull Chair chair; + private final @NotNull Player player; + private boolean exitWhereFacing = false; + + public ChairLeaveEvent(@NotNull Chair chair, @NotNull Player player, boolean flag) { + this.chair = chair; + this.player = player; + this.exitWhereFacing = flag; + } + + public ChairLeaveEvent(@NotNull Chair chair, @NotNull Player player) { + this.chair = chair; + this.player = player; + } + + static public @NotNull HandlerList getHandlerList() { + return handlers; + } + + public @NotNull Chair getChair() { + return this.chair; + } + + public @NotNull Player getPlayer() { + return this.player; + } + + public boolean exitWhereFacing() { + return this.exitWhereFacing; + } + + @Override + public @NotNull HandlerList getHandlers() { + return handlers; + } +} diff --git a/src/main/java/com/rifledluffy/chairs/events/ChairReplaceEvent.java b/src/main/java/com/rifledluffy/chairs/events/ChairReplaceEvent.java new file mode 100644 index 0000000..d88ea77 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/events/ChairReplaceEvent.java @@ -0,0 +1,41 @@ +package com.rifledluffy.chairs.events; + +import com.rifledluffy.chairs.chairs.Chair; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +public class ChairReplaceEvent extends Event { + private static final @NotNull HandlerList handlers = new HandlerList(); + private final @NotNull Chair chair; + private final @NotNull Player replaced; + private final @NotNull Player player; + + public ChairReplaceEvent(@NotNull Chair chair, @NotNull Player replaced, @NotNull Player player) { + this.chair = chair; + this.replaced = replaced; + this.player = player; + } + + static public @NotNull HandlerList getHandlerList() { + return handlers; + } + + public @NotNull Chair getChair() { + return this.chair; + } + + public @NotNull Player getReplaced() { + return this.replaced; + } + + public @NotNull Player getPlayer() { + return this.player; + } + + @Override + public @NotNull HandlerList getHandlers() { + return handlers; + } +} diff --git a/src/main/java/com/rifledluffy/chairs/events/ChairSitEvent.java b/src/main/java/com/rifledluffy/chairs/events/ChairSitEvent.java new file mode 100644 index 0000000..4c14e34 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/events/ChairSitEvent.java @@ -0,0 +1,35 @@ +package com.rifledluffy.chairs.events; + +import com.rifledluffy.chairs.chairs.Chair; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +public class ChairSitEvent extends Event { + private static final @NotNull HandlerList handlers = new HandlerList(); + private final @NotNull Chair chair; + private final @NotNull Player player; + + public ChairSitEvent(@NotNull Chair chair, @NotNull Player player) { + this.chair = chair; + this.player = player; + } + + static public @NotNull HandlerList getHandlerList() { + return handlers; + } + + public @NotNull Chair getChair() { + return this.chair; + } + + public @NotNull Player getPlayer() { + return this.player; + } + + @Override + public @NotNull HandlerList getHandlers() { + return handlers; + } +} diff --git a/src/main/java/com/rifledluffy/chairs/events/ChairTossEvent.java b/src/main/java/com/rifledluffy/chairs/events/ChairTossEvent.java new file mode 100644 index 0000000..f647825 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/events/ChairTossEvent.java @@ -0,0 +1,56 @@ +package com.rifledluffy.chairs.events; + +import com.rifledluffy.chairs.TargetInfo; +import com.rifledluffy.chairs.chairs.Chair; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class ChairTossEvent extends Event { + private static final @NotNull HandlerList handlers = new HandlerList(); + private final @NotNull Chair chair; + private final @NotNull Player player; + private final @NotNull Entity attacker; + private final @Nullable TargetInfo info; + private final boolean silent; + + public ChairTossEvent(@NotNull Chair chair, @NotNull Player player, @NotNull Entity attacker, @Nullable TargetInfo info, boolean flag) { + this.chair = chair; + this.player = player; + this.attacker = attacker; + this.info = info; + this.silent = flag; + } + + static public @NotNull HandlerList getHandlerList() { + return handlers; + } + + public @NotNull Chair getChair() { + return this.chair; + } + + public @NotNull Player getPlayer() { + return this.player; + } + + public @NotNull Entity getAttacker() { + return this.attacker; + } + + public @Nullable TargetInfo getInfo() { + return this.info; + } + + public boolean isSilent() { + return this.silent; + } + + @Override + public @NotNull HandlerList getHandlers() { + return handlers; + } +} diff --git a/src/main/java/com/rifledluffy/chairs/messages/MessageEvent.java b/src/main/java/com/rifledluffy/chairs/messages/MessageEvent.java new file mode 100644 index 0000000..5866247 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/messages/MessageEvent.java @@ -0,0 +1,62 @@ +package com.rifledluffy.chairs.messages; + +import net.kyori.adventure.audience.Audience; +import net.kyori.adventure.text.minimessage.tag.resolver.TagResolver; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public class MessageEvent extends Event implements Cancellable { + private static final @NotNull HandlerList handlers = new HandlerList(); + private final @NotNull MessagePath type; + private @NotNull TagResolver @Nullable [] resolvers; + private @NotNull Audience audience; + private boolean cancelled; + + public MessageEvent(@NotNull MessagePath type, @NotNull Audience audience, @NotNull TagResolver @Nullable ... resolvers) { + this.type = type; + this.audience = audience; + this.resolvers = resolvers; + } + + static public @NotNull HandlerList getHandlerList() { + return handlers; + } + + public @NotNull MessagePath getType() { + return this.type; + } + + @Override + public @NotNull HandlerList getHandlers() { + return handlers; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + public @NotNull Audience getAudience() { + return audience; + } + + public void setAudience(@NotNull Audience audience) { + this.audience = audience; + } + + public @NotNull TagResolver @Nullable [] getResolvers() { + return resolvers; + } + + public void setResolvers(@NotNull TagResolver @Nullable [] replacingResolvers) { + this.resolvers = replacingResolvers; + } +} diff --git a/src/main/java/com/rifledluffy/chairs/messages/MessagePath.java b/src/main/java/com/rifledluffy/chairs/messages/MessagePath.java new file mode 100644 index 0000000..82ae444 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/messages/MessagePath.java @@ -0,0 +1,46 @@ +package com.rifledluffy.chairs.messages; + +import org.jetbrains.annotations.NotNull; + +public enum MessagePath { + COMMAND_HELP_FOOTER("command.help.footer"), + COMMAND_HELP_HEADER("command.help.header"), + COMMAND_HELP_MAIN("command.help.main"), + COMMAND_INVALID_SUBCOMMAND("command.invalid_subcommand"), + COMMAND_MUTE_DISABLED("command.mute-message.disabled"), + COMMAND_MUTE_ENABLED("command.mute-message.enabled"), + COMMAND_NOT_ENOUGH_ARGS("command.not_enough_args"), + COMMAND_NOT_PLAYER("command.not_player"), + COMMAND_NO_PERMISSION("command.no-permission"), + COMMAND_RELOAD_SUCCESS("command.reload.success"), + COMMAND_RELOAD_INFO("command.reload.info"), + COMMAND_RESET_SUCCESS("command.reset.success"), + COMMAND_TOGGLE_DISABLED("command.toggle-disabled"), + COMMAND_TOGGLE_ENABLED("command.toggle-enabled"), + NOSIGNS("no-sign-at-ends"), + // PRIORITYTOSS("priority-replaced"), // todo? + OCCUPIED("occupied-seat"), + PLUGIN_PREFIX("pluginPrefix"), + SEAT_NOPERMS("no-permission"), + TOOFAR("too-far-from-seat"), + TOOMANYITEMS("too-many-items"), + TOSSED("tossed-out-of-chair"), + TOSSEDSPEED("tossed-out-with-speed"), + TOSSING("tossing-someone"), + TOSSINGSPEED("tossing-someone-with-speed"), + WORLDGUARD("denied-by-worldguard"), + COMMAND_RESET_INFO("command.reset.info"), + COMMAND_TOGGLE_INFO("command.toggle.info"), + COMMAND_MUTE_INFO("command.mute.info"), + COMMAND_HELP_INFO("command.help.info"); + + private final @NotNull String path; + + MessagePath(@NotNull String path) { + this.path = path; + } + + public @NotNull String getPath() { + return path; + } +} diff --git a/src/main/java/com/rifledluffy/chairs/messages/PlaceHolder.java b/src/main/java/com/rifledluffy/chairs/messages/PlaceHolder.java new file mode 100644 index 0000000..a22797a --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/messages/PlaceHolder.java @@ -0,0 +1,24 @@ +package com.rifledluffy.chairs.messages; + +import org.intellij.lang.annotations.Subst; + +public enum PlaceHolder { + ARGUMENT("argument"), + PLAYER("player"), + SEATED("seated"); + + private final String placeholder; + + PlaceHolder(String placeholder) { + this.placeholder = placeholder; + } + + /** + * Since this will be used in Mini-messages placeholder only the pattern "[!?#]?[a-z0-9_-]*" is valid. + * if used inside an unparsed text you have to add surrounding <> yourself. + */ + @Subst("name") // substitution; will be inserted if the IDE/compiler tests if input is valid. + public String getPlaceholder() { + return placeholder; + } +} \ No newline at end of file diff --git a/src/main/java/com/rifledluffy/chairs/utility/Util.java b/src/main/java/com/rifledluffy/chairs/utility/Util.java new file mode 100644 index 0000000..bc7ead3 --- /dev/null +++ b/src/main/java/com/rifledluffy/chairs/utility/Util.java @@ -0,0 +1,322 @@ +package com.rifledluffy.chairs.utility; + +import com.rifledluffy.chairs.RFChairs; +import com.rifledluffy.chairs.chairs.BlockFilter; +import com.rifledluffy.chairs.chairs.Chair; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Tag; +import org.bukkit.block.Block; +import org.bukkit.block.BlockFace; +import org.bukkit.block.data.Bisected; +import org.bukkit.block.data.Directional; +import org.bukkit.block.data.Levelled; +import org.bukkit.block.data.type.Slab; +import org.bukkit.block.data.type.Stairs; +import org.bukkit.block.data.type.TrapDoor; +import org.bukkit.block.data.type.WallSign; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.*; + +public class Util { + + public static boolean validStair(@NotNull Block block) { + if (!BlockFilter.validateStairs(block.getType())) return false; + Stairs stair = (Stairs) block.getState().getBlockData(); + return stair.getHalf() != Bisected.Half.TOP; + } + + public static boolean validSlab(@NotNull Block block) { + if (!BlockFilter.validateSlab(block.getType())) return false; + Slab slab = (Slab) block.getState().getBlockData(); + return slab.getType() == Slab.Type.BOTTOM; + } + + public static boolean validCarpet(@NotNull Block block) { + return BlockFilter.validateCarpet(block.getType()); + } + + private static boolean validatedChair(@NotNull Block block) { + return BlockFilter.isStairsBlock(block.getType()) && validStair(block); + } + + public static boolean playerIsSeated(@NotNull UUID uuid, @NotNull Map<@NotNull UUID, @NotNull Chair> chairMap) { + Chair chair = chairMap.get(uuid); + return chair != null; + } + + public static boolean nearLiquid(@NotNull Block block) { + return isLiquidOrMagma(block.getRelative(BlockFace.NORTH)) + || isLiquidOrMagma(block.getRelative(BlockFace.EAST)) + || isLiquidOrMagma(block.getRelative(BlockFace.SOUTH)) + || isLiquidOrMagma(block.getRelative(BlockFace.WEST)); + } + + public static boolean surroundedBlock(@NotNull Block block) { + return !validExit(block.getRelative(BlockFace.NORTH)) + && !validExit(block.getRelative(BlockFace.EAST)) + && !validExit(block.getRelative(BlockFace.SOUTH)) + && !validExit(block.getRelative(BlockFace.WEST)); + } + + private static boolean validExit(@NotNull Block block) { + Material type = block.getType(); + return type.isAir() || Tag.WALL_SIGNS.isTagged(type); + } + + public static boolean isLiquidOrMagma(@NotNull Block block) { + return block.getBlockData() instanceof Levelled || block.getRelative(BlockFace.DOWN).getType() == Material.MAGMA_BLOCK; + } + + public static boolean validCouch(@NotNull Block block) { + int validSides = 0; + if (!validatedChair(block)) return false; + Stairs stair = (Stairs) block.getState().getBlockData(); + + Set blockFaces = stair.getFaces(); + List faces = new ArrayList<>(blockFaces); + faces.remove(stair.getFacing()); + faces.remove(stair.getFacing().getOppositeFace()); + faces.remove(BlockFace.DOWN); + faces.remove(BlockFace.UP); + + BlockFace side = faces.get(0); + BlockFace otherSide = faces.get(1); + + if (!block.getRelative(BlockFace.UP).getType().isAir()) { + return false; + } + + if (validatedChair(block.getRelative(side))) { + if (validSeat(block.getRelative(side), side, block)) { + validSides++; + } + } + if (validatedChair(block.getRelative(otherSide))) { + if (validSeat(block.getRelative(otherSide), otherSide, block)) { + validSides++; + } + } + + if (!validatedChair(block.getRelative(side))) { + if (validSeat(block, side, block)) { + validSides++; + } + } + if (!validatedChair(block.getRelative(otherSide))) { + if (validSeat(block, otherSide, block)) { + validSides++; + } + } + return validSides == 2; + } + + public static boolean validSeat(@NotNull Block block, @NotNull BlockFace side, @NotNull Block original) { + Stairs stair = (Stairs) block.getState().getBlockData(); + Stairs first = (Stairs) original.getState().getBlockData(); + if (stair.getFacing() != first.getFacing()) { + return false; + } + if (block.getRelative(side).getBlockData() instanceof WallSign || block.getRelative(side).getBlockData() instanceof TrapDoor) { + Directional sign = ((Directional) block.getRelative(side).getBlockData()); + return sign.getFacing() == side; + } else if (validatedChair(block.getRelative(side))) { + return validSeat(block.getRelative(side), side, original); + } + return false; + } + + public static boolean sameSeat(@NotNull Player player, @NotNull Block block, @NotNull Map<@NotNull UUID, @NotNull Chair> chairMap) { + Chair chair = chairMap.get(player.getUniqueId()); + if (chair == null || chair.getLocation() == null) { + return false; + } + return chair.getLocation().equals(block.getLocation()); + } + + public static boolean samePosition(@NotNull Block block, @NotNull Location target) { + return block.getX() == target.getX() && block.getY() == target.getY() && block.getZ() == target.getZ(); + } + + public static boolean throneChair(@NotNull Block block) { + if (!(block.getBlockData() instanceof Stairs stairs)) { + return false; + } + if (block.getRelative(BlockFace.UP).getBlockData() instanceof TrapDoor trapDoor) { + if (!trapDoor.isOpen()) { + return false; + } + return trapDoor.getFacing().getOppositeFace() == stairs.getFacing(); + } + return false; + } + + public static boolean blockIsChair(@NotNull Block block, @NotNull List<@Nullable Chair> chairs) { + for (Chair chair : chairs) { + if (chair == null || chair.getLocation() == null) { + continue; + } + if (samePosition(block, chair.getLocation())) { + return true; + } + } + return false; + } + + public static @Nullable Chair getChairFromBlock(@NotNull Block block, @NotNull List<@Nullable Chair> chairs) { + for (Chair chair : chairs) { + if (chair == null || chair.getLocation() == null) { + continue; + } + if (samePosition(block, chair.getLocation())) { + return chair; + } + } + return null; + } + + @Contract("null -> null; !null -> !null") + public static @Nullable ArmorStand generateFakeSeat(@Nullable Chair chair) { + if (chair == null) { + return null; + } + Vector seatingPosition = new Vector(0.5, 0.3D, 0.5); + Location seat = chair.getLocation(); + BlockFace facing = null; + if (BlockFilter.isStairsBlock(chair.getBlock().getType())) { + facing = ((Stairs) chair.getBlock().getState().getBlockData()).getFacing(); + } + Location playerLoc = chair.getPlayer().getEyeLocation(); + playerLoc.setPitch(0); + Vector vector; + if (facing != null) { + vector = getVectorFromFace(chair.getBlock(), facing.getOppositeFace()); + } else { + vector = getVectorFromNearBlock(chair.getBlock(), playerLoc.getBlock()); + } + + if (BlockFilter.isStairsBlock(chair.getBlock().getType())) { + seatingPosition = RFChairs.getInstance().getChairManager().getStairSeatingPosition(); + } + if (BlockFilter.isCarpetBlock(chair.getBlock().getType())) { + seatingPosition = RFChairs.getInstance().getChairManager().getCarpetSeatingPosition(); + } + if (BlockFilter.isSlabBlock(chair.getBlock().getType())) { + seatingPosition = RFChairs.getInstance().getChairManager().getSlabSeatingPosition(); + } + + //Thank you VicenteRD and carlpoole! + return seat.getWorld().spawn( + seat.clone().add(seatingPosition).setDirection(vector), + ArmorStand.class, + stand -> { + stand.setVisible(false); + stand.setGravity(false); + stand.setInvulnerable(true); + stand.setMarker(true); + stand.setCollidable(false); + }); + } + + @Contract("null, _ -> null; !null, _ -> !null") + public static @Nullable ArmorStand generateFakeSeatDir(@Nullable Chair chair, @NotNull Vector dir) { + if (chair == null) { + return null; + } + Vector seatingPosition = new Vector(0.5, 0.3D, 0.5); + Location seat = chair.getLocation(); + Location playerLoc = chair.getPlayer().getEyeLocation(); + playerLoc.setPitch(0); + + if (BlockFilter.isStairsBlock(chair.getBlock().getType())) { + seatingPosition = RFChairs.getInstance().getChairManager().getStairSeatingPosition(); + } + if (BlockFilter.isCarpetBlock(chair.getBlock().getType())) { + seatingPosition = RFChairs.getInstance().getChairManager().getCarpetSeatingPosition(); + } + if (BlockFilter.isSlabBlock(chair.getBlock().getType())) { + seatingPosition = RFChairs.getInstance().getChairManager().getSlabSeatingPosition(); + } + + //Thank you VicenteRD and carlpoole! + return seat.getWorld().spawn( + seat.clone().add(seatingPosition).setDirection(dir), + ArmorStand.class, + stand -> { + stand.setVisible(false); + stand.setGravity(false); + stand.setInvulnerable(true); + stand.setMarker(true); + stand.setCollidable(false); + }); + } + + public static float getAbsoluteAngle(@NotNull Location loc) { + float y = loc.getYaw(); + if (y < 0) { + y += 360; + } + y %= 360; + if (y <= 45 || y >= 315) return 0; + if (y >= 45 && y <= 135) return 90; + if (y >= 135 && y <= 225) return 180; + return 270; + } + + public static @NotNull String getCardinalDirection(@NotNull Location loc) { + float y = loc.getYaw(); + if (y < 0) { + y += 360; + } + y %= 360; + if (y <= 45 || y >= 315) return "south"; + if (y >= 45 && y <= 135) return "west"; + if (y >= 135 && y <= 225) return "north"; + return "east"; + } + + public static Block getBlockFromDirection(@NotNull Block block, @NotNull String direction) { + if (direction.equalsIgnoreCase("north")) { + return block.getRelative(BlockFace.NORTH); + } else if (direction.equalsIgnoreCase("west")) { + return block.getRelative(BlockFace.WEST); + } else if (direction.equalsIgnoreCase("east")) { + return block.getRelative(BlockFace.EAST); + } else if (direction.equalsIgnoreCase("south")) { + return block.getRelative(BlockFace.SOUTH); + } else if (direction.equalsIgnoreCase("down")) { + return block.getRelative(BlockFace.DOWN); + } else if (direction.equalsIgnoreCase("up")) { + return block.getRelative(BlockFace.UP); + } + return block; + } + + public static boolean canFitPlayer(@NotNull Block block) { + return block.getType().isAir() && block.getRelative(BlockFace.UP).getType().isAir(); + } + + public static boolean safePlace(@NotNull Block block) { + return !block.getRelative(BlockFace.DOWN).getType().isAir(); + } + + public static Vector getVectorDir(@NotNull Location caster, @NotNull Location target) { + return target.clone().subtract(caster.toVector()).toVector(); + } + + public static Vector getVectorFromFace(@NotNull Block block, @NotNull BlockFace face) { + Location blockLoc = block.getLocation(); + Location faceLoc = block.getRelative(face).getLocation(); + return getVectorDir(blockLoc, faceLoc); + } + + public static Vector getVectorFromNearBlock(@NotNull Block block, @NotNull Block target) { + return target.getLocation().toVector().subtract(block.getLocation().toVector()); + } +} diff --git a/config.yml b/src/main/resources/config.yml similarity index 83% rename from config.yml rename to src/main/resources/config.yml index 0fb2e9b..6f9accb 100644 --- a/config.yml +++ b/src/main/resources/config.yml @@ -1,9 +1,9 @@ # Rifle's Chair plugin by Rifle D. Luffy # Version 6.0 # #=============[Seat Configuration]=============## -# stair-seating-position: The exact positions of where the armorstand spawns on a stair; default 0.35,0.3,0.5 -# slab-seating-position: The exact positions of where the armorstand spawns on a slab; default 0.5,0.3,0.5 -# carpet-seating-position: The exact positions of where the armorstand spawns on a carpet; default 0.5,-0.15,0.5 +# stair-seating-position: The exact positions of where the armorstand spawns on a stair; default 0.5,0.5,0.5 +# slab-seating-position: The exact positions of where the armorstand spawns on a slab; default 0.5,0.5,0.5 +# carpet-seating-position: The exact positions of where the armorstand spawns on a carpet; default 0.5,0.1,0.5 # be careful when playing around with this feature! # in the format x,y,z where... # x is forward @@ -31,12 +31,10 @@ # regen-when-sitting: players regenerate when sitting on chairs # regen-potency: the regen potion effect level where 0 is level 1 # allow-custom-messages: allow the use of custom messages when events are triggered -# allowed-chairs: The chairs that people are allowed to sit on -stair-seating-position: 0.5,0.3,0.5 -slab-seating-positiong: 0.5,0.3,0.5 -carpet-seating-position: 0.5,-0.15,0.5 -disable-update-message-if-on-latest: false -disable-update-messages: false +# whitelisted-chairs: The chairs that people are allowed to sit on +stair-seating-position: 0.5,0.5,0.5 +slab-seating-position: 0.5,0.5,0.5 +carpet-seating-position: 0.5,0.1,0.5 exit-seat-where-facing: false allow-trap-door-chairs: true require-empty-hand: false @@ -54,9 +52,11 @@ regen-when-sitting: true regen-potency: 0 allow-custom-messages: false priority-on-if-has-perm: true -allowed-chairs: - - STAIRS* - - SLAB* - - CARPET* -blacklisted-chairs: [] -disabled-worlds: [] \ No newline at end of file +whitelisted-chairs: + - ALL_STAIRS + - ALL_SLABS + - ALL_CARPETS +blacklisted-chairs: [ ] +disabled-worlds: [ ] +temp-mute-duration: 60 +language: 'en' \ No newline at end of file diff --git a/src/main/resources/messages.properties b/src/main/resources/messages.properties new file mode 100644 index 0000000..940b1d6 --- /dev/null +++ b/src/main/resources/messages.properties @@ -0,0 +1,63 @@ +# Certain events occur when users use this plugin. Here you can define what messages might be said. +# +# Use to refer to the user's name +# Use to refer to the seated's name +# +# General Events +# +# occupied-seat: Triggers when someone is already seated on the chair +# too-far-from-seat: Triggers when someone is too far to seat from their chair +# no-permission: Triggers when someone has no permission +# too-many-items: Triggers when someone sits with too large of an item stack +# +# Combat +# +# tossed-out-of-chair: Sends a message to the tossed player when they get tossed off +# Example: tossed you out of your seat! +# Output; if Rifle hit you: Rifle tossed you out of your seat! +# +# tossed-out-with-speed: Sends a message to the tossed player but the tosser was running +# Example: really knocked you of your seat! +# Output; if Rifle hit you: Rifle really knocked you of your seat! +# +# tossing-someone: Sends a message to the player that tossed someone off their chair +# Example: You tossed out of their chair! +# Output; if Rifle was sitting: You tossed Rifle out of their chair! +# +# tossing-someone-with-speed: Sends a message to the player that tossed someone off their chair with speed! +# Example: You really knocked out of their chair! +# Output; if Rifle was sitting: You really knocked Rifle out of their chair! +# +# Other Plugins +# +# denied-by-worldguard: called when worldguard blocks seating in a region. +# WorldGuard and WorldEdit must be enabled for these features to work! +command.help.footer=------------------------------------------------ +command.help.header=--------------[Available Commands]-------------- +command.help.info=Displays a list of all commands. +command.help.main=/rfc or /rfchairs is the main command +command.invalid_subcommand="" is not a valid subcommand. Type /rfchairs help for a list of them! +command.mute-message.disabled=Event Messaging is now Disabled! +command.mute-message.enabled=Event Messaging is now Enabled! +command.mute.info=Mutes event messages from the plugin for the executor [Player Only] +command.no-permission=You are not allowed to do that! +command.not_enough_args=Missing Arguments. Type /rfchairs help for info +command.not_player=You need to be a player to use this command! +command.reload.info=Reloads the config and messages [Console Can Cast] +command.reload.success=Config Reloaded +command.reset.info=Resets all chairs [Console Can Cast] +command.reset.success=Chairs Reset +command.toggle-disabled=Seating is now Disabled! +command.toggle-enabled=Seating is now Enabled! +command.toggle.info=Disables seating on chairs for the executor [Player Only] +denied-by-worldguard=You may not sit in this region! +no-permission=Can't sit there . I won't allow you! +no-sign-at-ends=This seat [which is a stair] doesn't have signs on both its ends! +occupied-seat=Can't sit there , my homie sits there. +pluginPrefix=[Rifle's Chairs] +too-far-from-seat=Can't sit there . You are too far! +too-many-items=! You have quite a hefty stack of items on your hand. Remove them! +tossed-out-of-chair=Tossed!... by . +tossed-out-with-speed=You got chucked off your seat by . +tossing-someone=You tossed off their seat! +tossing-someone-with-speed=You forcibly tossed off their seat! diff --git a/src/main/resources/messages_en.properties b/src/main/resources/messages_en.properties new file mode 100644 index 0000000..940b1d6 --- /dev/null +++ b/src/main/resources/messages_en.properties @@ -0,0 +1,63 @@ +# Certain events occur when users use this plugin. Here you can define what messages might be said. +# +# Use to refer to the user's name +# Use to refer to the seated's name +# +# General Events +# +# occupied-seat: Triggers when someone is already seated on the chair +# too-far-from-seat: Triggers when someone is too far to seat from their chair +# no-permission: Triggers when someone has no permission +# too-many-items: Triggers when someone sits with too large of an item stack +# +# Combat +# +# tossed-out-of-chair: Sends a message to the tossed player when they get tossed off +# Example: tossed you out of your seat! +# Output; if Rifle hit you: Rifle tossed you out of your seat! +# +# tossed-out-with-speed: Sends a message to the tossed player but the tosser was running +# Example: really knocked you of your seat! +# Output; if Rifle hit you: Rifle really knocked you of your seat! +# +# tossing-someone: Sends a message to the player that tossed someone off their chair +# Example: You tossed out of their chair! +# Output; if Rifle was sitting: You tossed Rifle out of their chair! +# +# tossing-someone-with-speed: Sends a message to the player that tossed someone off their chair with speed! +# Example: You really knocked out of their chair! +# Output; if Rifle was sitting: You really knocked Rifle out of their chair! +# +# Other Plugins +# +# denied-by-worldguard: called when worldguard blocks seating in a region. +# WorldGuard and WorldEdit must be enabled for these features to work! +command.help.footer=------------------------------------------------ +command.help.header=--------------[Available Commands]-------------- +command.help.info=Displays a list of all commands. +command.help.main=/rfc or /rfchairs is the main command +command.invalid_subcommand="" is not a valid subcommand. Type /rfchairs help for a list of them! +command.mute-message.disabled=Event Messaging is now Disabled! +command.mute-message.enabled=Event Messaging is now Enabled! +command.mute.info=Mutes event messages from the plugin for the executor [Player Only] +command.no-permission=You are not allowed to do that! +command.not_enough_args=Missing Arguments. Type /rfchairs help for info +command.not_player=You need to be a player to use this command! +command.reload.info=Reloads the config and messages [Console Can Cast] +command.reload.success=Config Reloaded +command.reset.info=Resets all chairs [Console Can Cast] +command.reset.success=Chairs Reset +command.toggle-disabled=Seating is now Disabled! +command.toggle-enabled=Seating is now Enabled! +command.toggle.info=Disables seating on chairs for the executor [Player Only] +denied-by-worldguard=You may not sit in this region! +no-permission=Can't sit there . I won't allow you! +no-sign-at-ends=This seat [which is a stair] doesn't have signs on both its ends! +occupied-seat=Can't sit there , my homie sits there. +pluginPrefix=[Rifle's Chairs] +too-far-from-seat=Can't sit there . You are too far! +too-many-items=! You have quite a hefty stack of items on your hand. Remove them! +tossed-out-of-chair=Tossed!... by . +tossed-out-with-speed=You got chucked off your seat by . +tossing-someone=You tossed off their seat! +tossing-someone-with-speed=You forcibly tossed off their seat! diff --git a/plugin.yml b/src/main/resources/paper-plugin.yml similarity index 75% rename from plugin.yml rename to src/main/resources/paper-plugin.yml index 047cea7..469de16 100644 --- a/plugin.yml +++ b/src/main/resources/paper-plugin.yml @@ -1,15 +1,13 @@ main: com.rifledluffy.chairs.RFChairs +loader: com.rifledluffy.chairs.RFChairsLoader name: RFChairs -version: 6.0 -authors: [Rifle D. Luffy, VicenteRD, carlpoole, i0xHeX] -api-version: 1.13 -description: Chairs but Rifle's way. -softdepend: [WorldGuard, WorldEdit] -commands: - rfchairs: - usage: / - description: The main prefix for other commands. Type /rfchairs help for more info - aliases: [rfc] +api-version: '${apiVersion}' +version: ${version} +description: ${description} +authors: [ Rifle D. Luffy, VicenteRD, carlpoole, i0xHeX, GreensurvivorsTeam ] +softdepend: + - WorldGuard + - WorldEdit permissions: rfchairs.use: description: Use of chairs diff --git a/src/messages.yml b/src/messages.yml deleted file mode 100644 index 362c156..0000000 --- a/src/messages.yml +++ /dev/null @@ -1,53 +0,0 @@ -# Certain events occur when users use this plugin. Here you can define what messages might be said. -# -# Use %user% to refer to the user's name -# Use %seated% to refer to the seated's name -# -# General Events -# -# occupied-seat: Triggers when someone is already seated on the chair -# too-far-from-seat: Triggers when someone is too far to seat from their chair -# no-permission: Triggers when someone has no permission -# too-many-items: Triggers when someone sits with too large of an item stack -# -# Combat -# -# tossed-out-of-chair: Sends a message to the tossed player when they get tossed off -# Example: %user% tossed you out of your seat! -# Output; if Rifle hit you: Rifle tossed you out of your seat! -# -# tossed-out-with-speed: Sends a message to the tossed player but the tosser was running -# Example: %user% really knocked you of your seat! -# Output; if Rifle hit you: Rifle really knocked you of your seat! -# -# tossing-someone: Sends a message to the player that tossed someone off their chair -# Example: You tossed %seated% out of their chair! -# Output; if Rifle was sitting: You tossed Rifle out of their chair! -# -# tossing-someone-with-speed: Sends a message to the player that tossed someone off their chair with speed! -# Example: You really knocked %seated% out of their chair! -# Output; if Rifle was sitting: You really knocked Rifle out of their chair! -# -# Other Plugins -# -# denied-by-worldguard: called when worldguard blocks seating in a region. -# WorldGuard and WorldEdit must be enabled for these features to work! -temp-mute-duration: 60 -mute-message-enabled: "&8[&6Rifle's Chairs&8] &7Event Messaging is now &aEnabled!" -mute-message-disabled: "&8[&6Rifle's Chairs&8] &7Event Messaging is now &cDisabled!" -toggle-message-enabled: "&8[&6Rifle's Chairs&8] &7Seating is now &aEnabled!" -toggle-message-disabled: "&8[&6Rifle's Chairs&8] &7Seating is now &cDisabled!" -occupied-seat: "&8[&6Rifle's Chairs&8] &cCan't sit there &7%user%, &amy homie &7%seated%&c sits there." -too-far-from-seat: "&8[&6Rifle's Chairs&8] &cCan't sit there &7%user%&c. You are too far!" -no-permission: "&8[&6Rifle's Chairs&8] &cCan't sit there &7%user%&c. I won't allow you!" -too-many-items: "&8[&6Rifle's Chairs&8] &c&7%user%&c! You have quite a hefty stack of items on your hand. Remove them!" -tossed-out-of-chair: "&8[&6Rifle's Chairs&8] &cTossed!... by &7%user%." -tossed-out-with-speed: "&8[&6Rifle's Chairs&8] &cYou got chucked off your seat by &7%user%." -tossing-someone: "&8[&6Rifle's Chairs&8] &cYou tossed &7%seated%&c off their seat!" -tossing-someone-with-speed: "&8[&6Rifle's Chairs&8] &cYou forcibly tossed &7%seated%&c off their seat!" -priority-replaced: "&8[&6Rifle's Chairs&8] &cYou forcibly tossed to make space for &7%user%&c, &7%seated%" -no-sign-at-ends: "&8[&6Rifle's Chairs&8] &cThis seat &8[&7which is a stair&8]&c doesn't have signs on both its ends!" -denied-by-worldguard: "&8[&6Rifle's Chairs&8] &cYou may not sit in this region!" -denied-by-plotsquared: "&8[&6Rifle's Chairs&8] &cYou may not sit in this plot!" -denied-by-griefprevention: "&8[&6Rifle's Chairs&8] &cYou may not sit in this claim!" -