diff --git a/.gitignore b/.gitignore index 7162ee7..3f7ecf4 100644 --- a/.gitignore +++ b/.gitignore @@ -147,3 +147,4 @@ dist/ nbdist/ .nb-gradle/ nbactions.xml +/.gradle/ \ No newline at end of file diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..1b58689 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,22 @@ +plugins { + id("java") +} + +group = "at.helpch" +version = "2.0.0" + +repositories { + mavenCentral() + maven("https://hub.spigotmc.org/nexus/content/groups/public/") + maven("https://repo.helpch.at/releases/") + maven("https://repo.essentialsx.net/releases/") +} + +dependencies { + compileOnly(libs.spigot) + compileOnly(libs.papi) + compileOnly(libs.ess) { + exclude("io.papermc", "paperlib") + exclude("io.papermc.paper", "paper-api") + } +} \ No newline at end of file diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..099b16c --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,9 @@ +[versions] +spigot = "26.1.2-R0.1-SNAPSHOT" +papi = "2.12.2" +ess = "2.21.2" + +[libraries] +spigot = { group = "org.spigotmc", name = "spigot-api", version.ref = "spigot" } +papi = { group = "me.clip", name = "placeholderapi", version.ref = "papi" } +ess = { group = "net.essentialsx", name = "EssentialsX", version.ref = "ess" } \ 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..61285a6 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..c61a118 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..adff685 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# 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" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# 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..c4bdd3a --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,93 @@ +@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 + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +: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/pom.xml b/pom.xml deleted file mode 100644 index dd4141f..0000000 --- a/pom.xml +++ /dev/null @@ -1,80 +0,0 @@ - - 4.0.0 - com.extendedclip.papi.expansion.essentials - essentials-expansion - 1.5.2 - PAPI-Expansion-Essentials - PlaceholderAPI expansion for Essentials placeholders - - - - spigot-repo - https://hub.spigotmc.org/nexus/content/groups/public/ - - - placeholderapi - https://repo.extendedclip.com/content/repositories/placeholderapi/ - - - ess-repo - https://repo.essentialsx.net/releases/ - - - - - - org.spigotmc - spigot-api - 1.19.3-R0.1-SNAPSHOT - provided - - - me.clip - placeholderapi - 2.11.2 - provided - - - net.essentialsx - EssentialsX - 2.19.7 - - - org.bstats - bstats-bukkit - - - provided - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 3.2.0 - - ${project.name} - - - true - true - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.1 - - 1.8 - 1.8 - UTF-8 - false - - - - - diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..0003d05 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "Essentials-Expansion" \ No newline at end of file diff --git a/src/main/java/at/helpch/essentialsexpansion/EssentialsExpansion.java b/src/main/java/at/helpch/essentialsexpansion/EssentialsExpansion.java new file mode 100644 index 0000000..7a48980 --- /dev/null +++ b/src/main/java/at/helpch/essentialsexpansion/EssentialsExpansion.java @@ -0,0 +1,443 @@ +/* + * + * Essentials-Expansion + * Copyright (C) 2019 Ryan McCarthy + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * + */ +package at.helpch.essentialsexpansion; + +import com.earth2me.essentials.Essentials; +import com.earth2me.essentials.Kit; +import com.earth2me.essentials.User; +import com.earth2me.essentials.utils.DateUtil; +import com.earth2me.essentials.utils.DescParseTickFormat; + +import net.md_5.bungee.api.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.OfflinePlayer; +import org.bukkit.scheduler.BukkitTask; +import org.jetbrains.annotations.NotNull; +import com.google.common.primitives.Ints; +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.expansion.Configurable; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.expansion.Taskable; +import net.essentialsx.api.v2.services.BalanceTop; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.math.BigDecimal; +import java.text.DateFormat; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.time.Instant; +import java.time.temporal.ChronoUnit; + +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; + +public class EssentialsExpansion extends PlaceholderExpansion implements Taskable, Configurable { + + private static final NumberFormat numberFormat = NumberFormat.getInstance(Locale.ENGLISH); + private static final DecimalFormat commasFormat = new DecimalFormat("#,###"); + private static final DecimalFormat coordsFormat = commasFormat; + private static final List placeholders; + + static { + placeholders = Stream.of( + Stream.of( + "balance", + "balance_commas", + "balance_fixed", + "balance_formatted", + "player_stripped", + "player" + ).map(placeholder -> "baltop_" + placeholder + "_"), + + Stream.of( + "baltop_rank", + "is_clearinventory_confirm", + "is_pay_confirm", + "is_pay_enabled", + "is_teleport_enabled", + "muted", + "vanished", + + "afk", + "afk_reason", + "afk_player_count", + + "msg_ignore", + "fly", + + "nickname", + "nickname_stripped", + + "muted_time_remaining", + "geolocation", + "godmode", + "unique", + + "jailed", + "jailed_time_remaining", + + "pm_recipient", + "safe_online", + "tp_cooldown", + + "world_date", + "world_time", + "world_time_24", + + "worth", + "worth_" + ), + + Stream.of( + "last_use", + "is_available", + "time_until_available", + "has" + ).map(placeholder -> "kit_" + placeholder + "_"), + + Stream.of( + Stream.of( + "total", + "max", + "name_", + "has_" + ), + Stream.of( + "world", + "x", + "y", + "z" + ).map(placeholder -> placeholder + "_") + ).flatMap(s->s).map(placeholder -> "home_" + placeholder) + + ).flatMap(s->s).map(placeholder -> "%essentials_" + placeholder + "%").toList(); + } + + private Map formats; + + private Essentials essentials; + private BalanceTop baltop; + private BukkitTask refreshTask = null; + + @Override + public @NotNull String getAuthor() { + return "clip"; + } + + @Override + public @NotNull String getIdentifier() { + return "essentials"; + } + + @Override + public @NotNull String getVersion() { + return "2.0.0"; + } + + @Override + public @NotNull String getRequiredPlugin() { + return "Essentials"; + } + + @Override + public @NotNull List getPlaceholders() { + return placeholders; + } + + @Override + public Map getDefaults() { + return Map.of( + "formatting.thousands", "k", + "formatting.millions", "m", + "formatting.billions", "b", + "formatting.trillions", "t", + "formatting.quadrillions", "q", + "baltop.refresh", 5L + ); + } + + @Override + public void start() { + formats = new LinkedHashMap<>() {{ + put(1000000000000000L, getString("formatting.quadrillions", "q")); + put(1000000000000L, getString("formatting.trillions", "t")); + put(1000000000L, getString("formatting.billions", "b")); + put(1000000L, getString("formatting.millions", "m")); + put(1000L, getString("formatting.thousands", "k")); + }}; + essentials = (Essentials) getPlaceholderAPI().getServer().getPluginManager().getPlugin("Essentials"); + assert essentials != null; + baltop = essentials.getBalanceTop(); + long refresh = getLong("baltop.refresh", 5); + if (refresh > 0) { + refreshTask = getPlaceholderAPI().getServer().getScheduler().runTaskTimerAsynchronously(getPlaceholderAPI(), () -> baltop.calculateBalanceTopMapAsync(), 0, refresh * 20L); + } + } + + @Override + public void stop() { + if (refreshTask != null) refreshTask.cancel(); + refreshTask = null; + } + + @Override + public String onRequest(OfflinePlayer player, String params) { + + // Put this before the null check as most of it doesn't require a player + if (params.startsWith("baltop_")) { + Map baltopCache = baltop.getBalanceTopCache(); + params = params.substring("baltop_".length()); + + String[] args = params.split("_"); + return switch (args[0]) { + case "balance", "player" -> { + if (args.length == 1) yield null; + + Integer rank = Ints.tryParse(args[args.length > 2 ? 2 : 1]); + if (rank == null) yield "Invalid rank"; + + BalanceTop.Entry[] entries = baltopCache.values().toArray(new BalanceTop.Entry[0]); + if (rank >= entries.length) yield "0"; + + if (args[0].equals("balance")) { + yield switch (args[1]) { + case "fixed" -> String.valueOf(entries[rank].getBalance().longValue()); + case "formatted" -> fixMoney(entries[rank].getBalance().doubleValue()); + case "commas" -> commasFormat.format(entries[rank].getBalance().doubleValue()); + default -> String.valueOf(entries[rank].getBalance().doubleValue()); + }; + } + + if (args[1].equals("stripped")) { + User user = essentials.getUser(entries[rank].getUuid()); + yield user != null ? user.getName() : null; + } + yield entries[rank].getDisplayName(); + } + case "rank" -> { + // Another null check because it's above the normal one + if (player == null) yield ""; + + if (!baltopCache.containsKey(player.getUniqueId())) yield ""; + + yield String.valueOf(new ArrayList<>(baltopCache.keySet()).indexOf(player.getUniqueId()) + 1); + } + default -> null; + }; + } + + if (player == null) return ""; + + Object output = request(player, params); + return switch (output) { + case null -> null; + case Boolean bool -> bool ? PlaceholderAPIPlugin.booleanTrue() : PlaceholderAPIPlugin.booleanFalse(); + default -> output.toString(); + }; + } + + private Object request(OfflinePlayer player, String params) { + User user = essentials.getUser(player.getUniqueId()); + return switch (params) { + case "is_clearinventory_confirm" -> user.isPromptingClearConfirm(); + case "is_pay_confirm" -> user.isPromptingPayConfirm(); + case "is_pay_enabled" -> user.isAcceptingPay(); + case "is_teleport_enabled" -> user.isTeleportEnabled(); + case "muted", "is_muted" -> user.isMuted(); + case "vanished" -> user.isVanished(); + + case "afk" -> user.isAfk(); + case "afk_reason" -> user.getAfkMessage() == null ? "" : ChatColor.translateAlternateColorCodes('&', user.getAfkMessage()); + case "afk_player_count" -> String.valueOf(essentials + .getUsers() + .getAllUserUUIDs() + .stream() + .map(essentials::getUser) + .filter(User::isAfk) + .count()); + + case "msg_ignore" -> user.isIgnoreMsg(); + case "fly" -> user.getBase().getAllowFlight(); + + case "nickname" -> user.getNickname() != null ? user.getNickname() : player.getName(); + case "nickname_stripped" -> ChatColor.stripColor(user.getNickname() != null ? user.getNickname() : player.getName()); + + case "muted_time_remaining" -> user.isMuted() ? DateUtil.formatDateDiff(user.getMuteTimeout()) : ""; + case "geolocation" -> user.getGeoLocation() != null ? user.getGeoLocation() : ""; + case "godmode" -> user.isGodModeEnabled(); + case "unique" -> NumberFormat.getInstance().format(essentials.getUsers().getUserCount()); + + case "jailed" -> user.isJailed(); + case "jailed_time_remaining" -> user.isJailed() ? user.getFormattedJailTime() : ""; + + case "pm_recipient" -> user.getReplyRecipient() != null ? user.getReplyRecipient().getName() : ""; + case "safe_online" -> String.valueOf(StreamSupport + .stream(essentials.getOnlineUsers().spliterator(), false) + .filter(user1 -> !user1.isHidden()) + .count()); + case "tp_cooldown" -> { + final double cooldown = essentials.getSettings().getTeleportCooldown(); + + final long now = System.currentTimeMillis(); + final long lastTeleport = user.getLastTeleportTimestamp(); + + long diff = TimeUnit.MILLISECONDS.toSeconds(now - lastTeleport); + + yield diff < cooldown ? String.valueOf((int) (cooldown - diff)) :"0"; + } + + case "world_date" -> DateFormat.getDateInstance(DateFormat.MEDIUM, essentials.getI18n().getCurrentLocale()) + .format(DescParseTickFormat.ticksToDate(user.getWorld() == null ? 0 : user.getWorld().getFullTime())); + case "world_time" -> DescParseTickFormat.format12(user.getWorld() == null ? 0 : user.getWorld().getTime()); + case "world_time_24" -> DescParseTickFormat.format24(user.getWorld() == null ? 0 : user.getWorld().getTime()); + default -> { + String[] args = params.split("_"); + params = params.substring(args[0].length() + (params.contains("_") ? 1 : 0)); + + yield switch (args[0]) { + case "kit" -> { + if (params.startsWith("last_use_")) { + String kitName = params.substring("last_use_".length()).toLowerCase(); + + try { + Kit kit = new Kit(kitName, essentials); + long time = user.getKitTimestamp(kit.getName()); + yield time <= 0 ? "0" : PlaceholderAPIPlugin.getDateFormat().format(new Date(time)); + } catch (Exception e) { + yield "Invalid kit name"; + } + } + + if (params.startsWith("is_available_")) { + String kitName = params.substring("is_available_".length()).toLowerCase(); + + try { + Kit kit = new Kit(kitName, essentials); + try { + long time = kit.getNextUse(user); + yield time == 0; + } catch (Exception e) { + yield false; + } + } catch (Exception e) { + yield "Invalid kit name"; + } + } + if (params.startsWith("time_until_available_")) { + String kitName = params.substring("time_until_available_".length()).toLowerCase(); + boolean raw = false; + + if (kitName.startsWith("raw_")) { + raw = true; + kitName = kitName.substring(4); + + } + if (kitName.isEmpty()) yield "Invalid kit name"; + + try { + Kit kit = new Kit(kitName, essentials); + try { + long time = kit.getNextUse(user); + if (time <= System.currentTimeMillis()) yield raw ? "0" : DateUtil.formatDateDiff(System.currentTimeMillis()); + yield raw ? String.valueOf(Instant.now().until(Instant.ofEpochMilli(time), ChronoUnit.MILLIS)) : DateUtil.formatDateDiff(time); + } catch (Exception e) { + yield "-1"; + } + } catch (Exception e) { + yield "Invalid kit name"; + } + } + + if (params.startsWith("has_")) { + Player p = player.getPlayer(); + yield p != null && p.hasPermission("essentials.kits." + params.substring("has_".length())); + } + yield null; + } + case "home" -> { + String type = args[1]; + + List homes = user.getHomes(); + + String homeName = params.substring(type.length() + (params.contains("_") ? 1 : 0)); + Integer homeNumber = Ints.tryParse(homeName); + + yield switch (type) { + case "total" -> homes.size() + ""; + case "max" -> essentials.getSettings().getHomeLimit(user); + case "has" -> user.hasHome(homeName); + case "name" -> homeNumber == null || homeNumber < 0 || homeNumber >= homes.size() ? "" : user.getHomes().get(homeNumber); + default -> { + if (homeNumber != null && (homeNumber < 0 || homeNumber >= user.getHomes().size())) yield "Invalid home"; + + Location home = user.getHome(homeNumber == null ? homeName : user.getHomes().get(homeNumber)); + if (home == null) yield "Invalid home"; + + Object output = switch (type) { + case "w", "world" -> home.getWorld() == null ? "null" : home.getWorld().getName(); + case "x" -> home.getX(); + case "y" -> home.getY(); + case "z" -> home.getZ(); + default -> null; + }; + yield output instanceof Double coords ? coordsFormat.format(coords) : output; + } + }; + } + case "worth" -> { + ItemStack item; + if (args.length == 1) { + Player p = player.getPlayer(); + if (p == null) yield "Player offline and no material provided"; + + item = p.getInventory().getItemInMainHand(); + } else { + Material material = Material.getMaterial(params.toUpperCase()); + if (material == null) yield "Invalid material"; + + item = new ItemStack(material); + } + if (item.getType() == Material.AIR) yield "No worth"; + + BigDecimal worth = essentials.getWorth().getPrice(essentials, item); + yield worth == null ? "No worth" : worth.doubleValue(); + } + default -> null; + }; + } + }; + } + + private String fixMoney(double d) { + for (Map.Entry format : formats.entrySet()) { + if (d < format.getKey()) continue; + numberFormat.setMaximumFractionDigits(2); + numberFormat.setMinimumFractionDigits(0); + return numberFormat.format(d / format.getKey()) + format.getValue(); + } + return numberFormat.format(d); + } +} diff --git a/src/main/java/com/extendedclip/papi/expansion/essentials/EssentialsExpansion.java b/src/main/java/com/extendedclip/papi/expansion/essentials/EssentialsExpansion.java deleted file mode 100644 index 75efb7d..0000000 --- a/src/main/java/com/extendedclip/papi/expansion/essentials/EssentialsExpansion.java +++ /dev/null @@ -1,481 +0,0 @@ -/* - * - * Essentials-Expansion - * Copyright (C) 2019 Ryan McCarthy - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - * - */ -package com.extendedclip.papi.expansion.essentials; - -import com.earth2me.essentials.Essentials; -import com.earth2me.essentials.Kit; -import com.earth2me.essentials.User; -import com.earth2me.essentials.utils.DateUtil; -import com.earth2me.essentials.utils.DescParseTickFormat; - -import com.google.common.primitives.Ints; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import net.essentialsx.api.v2.services.BalanceTop; -import org.bukkit.*; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.jetbrains.annotations.NotNull; - -import java.math.BigDecimal; -import java.text.DateFormat; -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.time.Instant; -import java.time.temporal.ChronoUnit; -import java.util.*; - -import java.util.concurrent.TimeUnit; -import java.util.stream.StreamSupport; - -public class EssentialsExpansion extends PlaceholderExpansion { - - private String k; - private String m; - private String b; - private String t; - private String q; - private final DecimalFormat format = new DecimalFormat("#,###"); - - private final DecimalFormat coordsFormat = new DecimalFormat("#.###"); - - private Essentials essentials; - private BalanceTop baltop; - - private final String VERSION = getClass().getPackage().getImplementationVersion(); - - @Override - public boolean canRegister() { - return Bukkit.getPluginManager().getPlugin("Essentials") != null && Bukkit.getPluginManager().getPlugin("Essentials").isEnabled(); - } - - @Override - public boolean register() { - k = getString("formatting.thousands", "k"); - m = getString("formatting.millions", "m"); - b = getString("formatting.billions", "b"); - t = getString("formatting.trillions", "t"); - q = getString("formatting.quadrillions", "q"); - - essentials = (Essentials) Bukkit.getPluginManager().getPlugin("Essentials"); - if (essentials != null && essentials.isEnabled()) { - baltop = essentials.getBalanceTop(); - baltop.calculateBalanceTopMapAsync(); - return super.register(); - } - return false; - } - - @Override - public @NotNull String getAuthor() { - return "clip"; - } - - @Override - public @NotNull String getIdentifier() { - return "essentials"; - } - - @Override - public @NotNull String getVersion() { - return VERSION; - } - - @Override - public String onRequest(OfflinePlayer player, @NotNull String identifier) { - final String papiTrue = PlaceholderAPIPlugin.booleanTrue(); - final String papiFalse = PlaceholderAPIPlugin.booleanFalse(); - - // Put this before the null check as most of it is not required - if (identifier.startsWith("baltop_")) { - Map baltopCache = baltop.getBalanceTopCache(); - identifier = identifier.substring(7); - - if (identifier.startsWith("balance_")) { - identifier = identifier.substring(8); - - if (identifier.startsWith("fixed_")) { - identifier = identifier.substring(6); - - Integer id = Ints.tryParse(identifier); - if (id == null) { - return "Invalid ID"; - } - - BalanceTop.Entry[] entries = baltopCache.values().toArray(new BalanceTop.Entry[0]); - if (id >= entries.length) { - return "0"; - } - return String.valueOf(entries[id].getBalance().longValue()); - } - - if (identifier.startsWith("formatted_")) { - identifier = identifier.substring(10); - - Integer id = Ints.tryParse(identifier); - if (id == null) { - return "Invalid ID"; - } - - BalanceTop.Entry[] entries = baltopCache.values().toArray(new BalanceTop.Entry[0]); - if (id >= entries.length) { - return "0"; - } - return fixMoney(entries[id].getBalance().doubleValue()); - } - - if (identifier.startsWith("commas_")) { - identifier = identifier.substring(7); - - Integer id = Ints.tryParse(identifier); - if (id == null) { - return "Invalid ID"; - } - - BalanceTop.Entry[] entries = baltopCache.values().toArray(new BalanceTop.Entry[0]); - if (id >= entries.length) { - return "0"; - } - return format.format(entries[id].getBalance().doubleValue()); - } - - Integer id = Ints.tryParse(identifier); - if (id == null) { - return "Invalid ID"; - } - - BalanceTop.Entry[] entries = baltopCache.values().toArray(new BalanceTop.Entry[0]); - if (id >= entries.length) { - return "0"; - } - return String.valueOf(entries[id].getBalance().doubleValue()); - } - - if (identifier.startsWith("player_")) { - identifier = identifier.substring(7); - - boolean stripped = false; - - if (identifier.startsWith("stripped_")) { - identifier = identifier.substring(9); - stripped = true; - } - - Integer id = Ints.tryParse(identifier); - if (id == null) { - return "Invalid ID"; - } - - BalanceTop.Entry[] entries = baltopCache.values().toArray(new BalanceTop.Entry[0]); - if (id >= entries.length) { - return "0"; - } - - if (stripped) { - User user = essentials.getUser(entries[id].getUuid()); - if (user != null) { - return user.getName(); - } else { - return null; - } - } else { - return entries[id].getDisplayName(); - } - } - - if (identifier.equals("rank")) { - // Another null check because it is above the normal one - if (player == null) return ""; - - if (!baltopCache.containsKey(player.getUniqueId())) { - return ""; - } - - return String.valueOf(new ArrayList<>(baltopCache.keySet()).indexOf(player.getUniqueId()) + 1); - } - - return null; - } - - if (player == null) return ""; - - if (identifier.equals("tp_cooldown")) { - final double cooldown = essentials.getSettings().getTeleportCooldown(); - - final long d1 = System.currentTimeMillis(); - final long d2 = essentials.getUser(player.getUniqueId()).getLastTeleportTimestamp(); - - long diff = TimeUnit.MILLISECONDS.toSeconds(d1 - d2); - - if(diff < cooldown) return String.valueOf((int) (cooldown - diff)); - - return "0"; - } - - if (identifier.startsWith("kit_last_use_")) { - String kitName = identifier.split("kit_last_use_")[1].toLowerCase(); - Kit kit; - - try { - kit = new Kit(kitName, essentials); - } catch (Exception e) { - return "Invalid kit name"; - } - - long time = essentials.getUser(player.getUniqueId()).getKitTimestamp(kit.getName()); - - if (time == 1 || time <= 0) { - return "1"; - } - return PlaceholderAPIPlugin.getDateFormat().format(new Date(time)); - } - - if (identifier.startsWith("kit_is_available_")) { - String kitName = identifier.split("kit_is_available_")[1].toLowerCase(); - Kit kit; - User user = essentials.getUser(player.getUniqueId()); - long time; - - try { - kit = new Kit(kitName, essentials); - } catch (Exception e) { - return "Invalid kit name"; - } - - try { - time = kit.getNextUse(user); - } catch (Exception e) { - return papiFalse; - } - - return time == 0 ? papiTrue : papiFalse; - } - - if (identifier.startsWith("kit_time_until_available_")) { - String kitName = identifier.split("kit_time_until_available_")[1].toLowerCase(); - boolean raw = false; - User user = essentials.getUser(player.getUniqueId()); - Kit kit; - long time; - - if (kitName.startsWith("raw_")) { - raw = true; - kitName = kitName.substring(4); - - if (kitName.isEmpty()) { - return "Invalid kit name"; - } - } - - try { - kit = new Kit(kitName, essentials); - } catch (Exception e) { - return "Invalid kit name"; - } - - try { - time = kit.getNextUse(user); - } catch (Exception e) { - return "-1"; - } - - if (time <= System.currentTimeMillis()) { - return raw ? "0" : DateUtil.formatDateDiff(System.currentTimeMillis()); - } - - if (raw) { - return String.valueOf(Instant.now().until(Instant.ofEpochMilli(time), ChronoUnit.MILLIS)); - } else { - return DateUtil.formatDateDiff(time); - } - } - - if (identifier.startsWith("has_kit_")) { - Player oPlayer = player.getPlayer(); - if (oPlayer == null) return papiFalse; - - String kit = identifier.split("has_kit_")[1]; - return oPlayer.hasPermission("essentials.kits." + kit) ? papiTrue : papiFalse; - } - - if (identifier.startsWith("home_")) { - Integer homeNumber; - final User user = essentials.getUser(player.getUniqueId()); - - // Removes all the letters from the identifier to get the home slot. - // Checks if the number slot is an integer or not. - if ((homeNumber = Ints.tryParse(identifier.replaceAll("\\D+", ""))) == null) return null; - - // Since it is easier for users to type from 1-x I subtract one from the original number to work from 0-x. - homeNumber -= 1; - - // checks if the home is out of bounds and returns and empty string if it is. - if (homeNumber >= user.getHomes().size() || homeNumber < 0) return ""; - - // checks if the identifier matches the pattern home_%d - if (identifier.matches("(\\w+_)(\\d+)")) return user.getHomes().get(homeNumber); - - //checks if the identifier matches the pattern home_%d_(w/x/y/z) - if (identifier.matches("(\\w+_)(\\d+)(_\\w)")) { - - try { - final Location home = user.getHome(user.getHomes().get(homeNumber)); - final StringBuilder stringBuilder = new StringBuilder(); - - switch (identifier.charAt(identifier.length() - 1)) { - case 'w': - stringBuilder.append(home.getWorld().getName()); - break; - case 'x': - stringBuilder.append(coordsFormat.format(home.getX())); - break; - case 'y': - stringBuilder.append((int) home.getY()); - break; - case 'z': - stringBuilder.append(coordsFormat.format(home.getZ())); - break; - } - - return stringBuilder.toString(); - } catch (Exception e) { - return null; - } - } - } - - if (identifier.startsWith("worth")) { - ItemStack item; - - if (identifier.contains(":")){ - Material material = Material.getMaterial(identifier.replace("worth:", "").toUpperCase()); - - if (material == null) return ""; - item = new ItemStack(material,1); - } else { - Player oPlayer = player.getPlayer(); - if (oPlayer == null) return ""; - - if (oPlayer.getItemInHand().getType() == Material.AIR) return ""; - item = oPlayer.getItemInHand(); - } - - BigDecimal worth = essentials.getWorth().getPrice(essentials, item); - if (worth == null) return ""; - return String.valueOf(worth.doubleValue()); - } - - final User user = essentials.getUser(player.getUniqueId()); - - switch (identifier) { - case "is_clearinventory_confirm": - return user.isPromptingClearConfirm() ? papiTrue : papiFalse; - case "is_pay_confirm": - return user.isPromptingPayConfirm() ? papiTrue : papiFalse; - case "is_pay_enabled": - return user.isAcceptingPay() ? papiTrue : papiFalse; - case "is_teleport_enabled": - return user.isTeleportEnabled() ? papiTrue : papiFalse; - case "is_muted": - return user.isMuted() ? papiTrue : papiFalse; - case "vanished": - return user.isVanished() ? papiTrue : papiFalse; - case "afk": - return user.isAfk() ? papiTrue : papiFalse; - case "afk_reason": - if (user.getAfkMessage() == null) return ""; - return ChatColor.translateAlternateColorCodes('&', user.getAfkMessage()); - case "afk_player_count": - return String.valueOf(essentials.getUserMap().getAllUniqueUsers().stream() - .map(UUID -> essentials.getUser(UUID)).filter(User::isAfk) - .count()); - case "msg_ignore": - return user.isIgnoreMsg() ? papiTrue : papiFalse; - case "fly": - return user.getBase().getAllowFlight() ? papiTrue : papiFalse; - case "nickname": - return user.getNickname() != null ? essentials.getUser(player.getUniqueId()).getNickname() : player.getName(); - case "nickname_stripped": - return ChatColor.stripColor(user.getNickname() != null ? essentials.getUser(player.getUniqueId()).getNickname() : player.getName()); - case "muted_time_remaining": - return user.isMuted() ? DateUtil.formatDateDiff(user.getMuteTimeout()) : ""; - case "geolocation": - return user.getGeoLocation() != null ? user.getGeoLocation() : ""; - case "godmode": - return user.isGodModeEnabled() ? papiTrue : papiFalse; - case "unique": - return NumberFormat.getInstance().format(essentials.getUserMap().getUniqueUsers()); - case "homes_set": - return user.getHomes().isEmpty() ? "0" : String.valueOf(user.getHomes().size()); - case "homes_max": - return String.valueOf(essentials.getSettings().getHomeLimit(user)); - case "jailed": - return user.isJailed() ? papiTrue : papiFalse; - case "jailed_time_remaining": - return user.isJailed() ? user.getFormattedJailTime() : ""; - case "pm_recipient": - return user.getReplyRecipient() != null ? user.getReplyRecipient().getName() : ""; - case "safe_online": - return String.valueOf(StreamSupport.stream(essentials.getOnlineUsers().spliterator(), false) - .filter(user1 -> !user1.isHidden()) - .count()); - case "world_date": - return DateFormat.getDateInstance(DateFormat.MEDIUM, essentials.getI18n().getCurrentLocale()) - .format(DescParseTickFormat.ticksToDate(user.getWorld() == null ? 0 : user.getWorld().getFullTime())); - case "world_time": - return DescParseTickFormat.format12(user.getWorld() == null ? 0 : user.getWorld().getTime()); - case "world_time_24": - return DescParseTickFormat.format24(user.getWorld() == null ? 0 : user.getWorld().getTime()); - } - return null; - } - - private String format(double d) { - NumberFormat format = NumberFormat.getInstance(Locale.ENGLISH); - format.setMaximumFractionDigits(2); - format.setMinimumFractionDigits(0); - return format.format(d); - } - - private String fixMoney(double d) { - - if (d < 1000L) { - return format(d); - } - if (d < 1000000L) { - return format(d / 1000L) + k; - } - if (d < 1000000000L) { - return format(d / 1000000L) + m; - } - if (d < 1000000000000L) { - return format(d / 1000000000L) + b; - } - if (d < 1000000000000000L) { - return format(d / 1000000000000L) + t; - } - if (d < 1000000000000000000L) { - return format(d / 1000000000000000L) + q; - } - - return String.valueOf(d); - } -}