diff --git a/.github/workflows/pr_build_jars.yml b/.github/workflows/pr_build_jars.yml index 61dccd0..c7ad7d4 100644 --- a/.github/workflows/pr_build_jars.yml +++ b/.github/workflows/pr_build_jars.yml @@ -5,8 +5,10 @@ on: branches: - development paths: - - "src/**" - - "build.gradle" + - "../../spigot/**" + - "../../paper/**" + - "build.gradle.kts" + - "settings.gradle.kts" jobs: testBuilds: diff --git a/build.gradle.kts b/build.gradle.kts index 2ef405d..87e1ac8 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -7,129 +7,99 @@ plugins { id("io.github.goooler.shadow") version "8.1.7" } -group = "me.clip" -version = "2.11.8-DEV-${System.getProperty("BUILD_NUMBER")}" +subprojects { + apply(plugin = "java-library") + apply(plugin = "maven-publish") + apply(plugin = "com.github.hierynomus.license") + apply(plugin = "io.github.goooler.shadow") -description = "An awesome placeholder provider!" + group = "me.clip" + version = "2.11.8-DEV-${System.getProperty("BUILD_NUMBER")}" -repositories { - maven("https://oss.sonatype.org/content/repositories/snapshots/") + description = "An awesome placeholder provider!" - mavenCentral() - mavenLocal() + repositories { + maven("https://oss.sonatype.org/content/repositories/snapshots/") - maven("https://repo.codemc.org/repository/maven-public/") - maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/") - maven("https://repo.papermc.io/repository/maven-public/") -} + mavenCentral() + mavenLocal() -dependencies { - implementation("org.bstats:bstats-bukkit:3.0.1") - implementation("net.kyori:adventure-platform-bukkit:4.4.1") - - //compileOnly("org.spigotmc:spigot-api:1.21-R0.1-SNAPSHOT") - compileOnly("dev.folia:folia-api:1.20.1-R0.1-SNAPSHOT") - compileOnlyApi("org.jetbrains:annotations:23.0.0") - - testImplementation("org.openjdk.jmh:jmh-core:1.32") - testImplementation("org.openjdk.jmh:jmh-generator-annprocess:1.32") - - testImplementation("org.junit.jupiter:junit-jupiter-engine:5.8.2") - testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.8.1") -} - - -java { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 - - withJavadocJar() - withSourcesJar() - - disableAutoTargetJvm() -} - -license { - header = rootProject.file("config/headers/main.txt") - - include("**/*.java") - mapping("java", "JAVADOC_STYLE") - - encoding = "UTF-8" - - ext { - set("year", 2024) - } -} - -val javaComponent: SoftwareComponent = components["java"] - -tasks { - processResources { - eachFile { expand("version" to project.version) } + maven("https://repo.codemc.org/repository/maven-public/") + maven("https://hub.spigotmc.org/nexus/content/repositories/snapshots/") + maven("https://repo.papermc.io/repository/maven-public/") } - build { - dependsOn(named("shadowJar")) + dependencies { + implementation("org.bstats:bstats-bukkit:3.0.1") + implementation("net.kyori:adventure-platform-bukkit:4.4.1") + + compileOnly("dev.folia:folia-api:1.21.11-R0.1-SNAPSHOT") + compileOnlyApi("org.jetbrains:annotations:23.0.0") + + testImplementation("org.openjdk.jmh:jmh-core:1.32") + testImplementation("org.openjdk.jmh:jmh-generator-annprocess:1.32") + + testImplementation("org.junit.jupiter:junit-jupiter-engine:5.8.2") + testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.8.1") } - withType { - options.encoding = "UTF-8" - options.release = 8 + + java { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + withJavadocJar() + withSourcesJar() + + disableAutoTargetJvm() } - withType { - isFailOnError = false + license { + header = rootProject.file("config/headers/main.txt") - with(options as StandardJavadocDocletOptions) { - addStringOption("Xdoclint:none", "-quiet") - addStringOption("encoding", "UTF-8") - addStringOption("charSet", "UTF-8") + include("**/*.java") + mapping("java", "JAVADOC_STYLE") + + encoding = "UTF-8" + + ext { + set("year", 2024) } } - withType { - archiveClassifier.set("") + tasks { + processResources { + eachFile { expand("version" to project.version) } + } - relocate("org.bstats", "me.clip.placeholderapi.metrics") - relocate("net.kyori", "me.clip.placeholderapi.libs.kyori") + build { + dependsOn(named("shadowJar")) + } - exclude("META-INF/versions/**") - } + withType { + options.encoding = "UTF-8" + options.release = 8 + } - test { - useJUnitPlatform() - } + withType { + isFailOnError = false - publishing { - publications { - create("maven") { - artifactId = "placeholderapi" - from(javaComponent) + with(options as StandardJavadocDocletOptions) { + addStringOption("Xdoclint:none", "-quiet") + addStringOption("encoding", "UTF-8") + addStringOption("charSet", "UTF-8") } } - repositories { - maven { - if ("-DEV" in version.toString()) { - url = uri("https://repo.extendedclip.com/snapshots") - } else { - url = uri("https://repo.extendedclip.com/releases") - } - - credentials { - username = System.getenv("JENKINS_USER") - password = System.getenv("JENKINS_PASS") - } - } + test { + useJUnitPlatform() } } - publish.get().setDependsOn(listOf(build.get())) -} - -configurations { - testImplementation { - extendsFrom(compileOnly.get()) + configurations { + testImplementation { + extendsFrom(compileOnly.get()) + } } -} + +} \ No newline at end of file diff --git a/paper/build.gradle.kts b/paper/build.gradle.kts new file mode 100644 index 0000000..be958b5 --- /dev/null +++ b/paper/build.gradle.kts @@ -0,0 +1,44 @@ +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar + +dependencies { + api(project(":spigot")) +} + +val javaComponent: SoftwareComponent = components["java"] + +tasks { + withType { + archiveClassifier.set("") + archiveBaseName.set("PlaceholderAPI-Paper") + + relocate("org.bstats", "me.clip.placeholderapi.metrics") + + exclude("META-INF/versions/**") + } + + publishing { + publications { + create("maven") { + artifactId = "placeholderapi-paper" + from(javaComponent) + } + } + + repositories { + maven { + if ("-DEV" in version.toString()) { + url = uri("https://repo.extendedclip.com/snapshots") + } else { + url = uri("https://repo.extendedclip.com/releases") + } + + credentials { + username = System.getenv("JENKINS_USER") + password = System.getenv("JENKINS_PASS") + } + } + } + } + + publish.get().setDependsOn(listOf(build.get())) +} \ No newline at end of file diff --git a/paper/src/main/java/me/clip/placeholderapi/PAPIComponents.java b/paper/src/main/java/me/clip/placeholderapi/PAPIComponents.java new file mode 100644 index 0000000..30aba58 --- /dev/null +++ b/paper/src/main/java/me/clip/placeholderapi/PAPIComponents.java @@ -0,0 +1,162 @@ +package me.clip.placeholderapi; + +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.expansion.Relational; +import me.clip.placeholderapi.replacer.ExactReplacer; +import me.clip.placeholderapi.replacer.RelationalExactReplacer; +import me.clip.placeholderapi.replacer.Replacer; +import net.kyori.adventure.text.Component; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; + +import java.util.List; +import java.util.stream.Collectors; + +import static me.clip.placeholderapi.PlaceholderAPI.RELATIONAL_PLACEHOLDER_PATTERN; + +public final class PAPIComponents { + private static final Replacer PERCENT_EXACT_REPLACER = new ExactReplacer('%', '%'); + private static final Replacer BRACKET_EXACT_REPLACER = new ExactReplacer('{', '}'); + private static final RelationalExactReplacer RELATIONAL_EXACT_REPLACER = new RelationalExactReplacer(); + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal %_%}. + * + * @param player Player to parse the placeholders against + * @param component Component to set the placeholder values in + * @return Component containing all translated placeholders + */ + @NotNull + public static Component setPlaceholders(final OfflinePlayer player, @NotNull final Component component) { + // TODO: explore a custom TextReplacementRenderer which doesn't use regex for performance benefits i.e. merge CharsReplacer with kyori TextReplacementRenderer + return component.replaceText(config -> config.match(PlaceholderAPI.PLACEHOLDER_PATTERN).replacement((result, builder) -> + builder.content(PERCENT_EXACT_REPLACER.apply(result.group(), player, PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion)))); + } + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal %_%}. + * + * @param player Player to parse the placeholders against + * @param components List of Components to set the placeholder values in + * @return List of Components containing all translated placeholders + */ + @NotNull + public static List setPlaceholders(final OfflinePlayer player, @NotNull final List components) { + return components.stream().map(component -> setPlaceholders(player, component)).collect(Collectors.toList()); + } + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal %_%}. + * + * @param player Player to parse the placeholders against + * @param component Component to set the placeholder values in + * @return Component containing all translated placeholders + */ + @NotNull + public static Component setPlaceholders(final Player player, @NotNull final Component component) { + return setPlaceholders((OfflinePlayer) player, component); + } + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal %_%}. + * + * @param player Player to parse the placeholders against + * @param components List of Components to set the placeholder values in + * @return List of components containing all translated placeholders + */ + @NotNull + public static List setPlaceholders(final Player player, @NotNull final List components) { + return setPlaceholders((OfflinePlayer) player, components); + } + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal {_}}. + * + * @param player Player to parse the placeholders against + * @param component Component to set the placeholder values in + * @return Component containing all translated placeholders + */ + @NotNull + public static Component setBracketPlaceholders(final OfflinePlayer player, @NotNull final Component component) { + return component.replaceText(config -> config.match(PlaceholderAPI.BRACKET_PLACEHOLDER_PATTERN).replacement((result, builder) -> + builder.content(BRACKET_EXACT_REPLACER.apply(result.group(), player, PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion)))); + } + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal {_}}. + * + * @param player Player to parse the placeholders against + * @param components List of Components to set the placeholder values in + * @return List of Components containing all translated placeholders + */ + @NotNull + public static List setBracketPlaceholders(final OfflinePlayer player, @NotNull final List components) { + return components.stream().map(component -> setBracketPlaceholders(player, component)).collect(Collectors.toList()); + } + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal {_}}. + * + * @param player Player to parse the placeholders against + * @param component Component to set the placeholder values in + * @return Component containing all translated placeholders + */ + @NotNull + public static Component setBracketPlaceholders(final Player player, @NotNull final Component component) { + return setBracketPlaceholders((OfflinePlayer) player, component); + } + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal {_}}. + * + * @param player Player to parse the placeholders against + * @param components List of Components to set the placeholder values in + * @return List of Components containing all translated placeholders + */ + @NotNull + public static List setBracketPlaceholders(final Player player, @NotNull final List components) { + return setBracketPlaceholders((OfflinePlayer) player, components); + } + + /** + * set relational placeholders in the text specified placeholders are matched with the pattern + * {@literal %%} when set with this method + * + * @param one First player to compare + * @param two Second player to compare + * @param component Component to parse the placeholders in + * @return The Component containing the parsed relational placeholders + */ + public static Component setRelationalPlaceholders(Player one, Player two, Component component) { + return component.replaceText(config -> config.match(RELATIONAL_PLACEHOLDER_PATTERN).replacement((result, builder) -> + builder.content(RELATIONAL_EXACT_REPLACER.apply(result.group(2), one, two, PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion)))); + } + + /** + * Translate placeholders in the provided List based on the relation of the two provided players. + *
The pattern of a valid placeholder is {@literal %rel__%}. + * + * @param one Player to compare + * @param two Player to compare + * @param components List of Components to parse the placeholder values to + * @return The List of Components containing the parsed relational placeholders + */ + public static List setRelationalPlaceholders(Player one, Player two, List components) { + return components.stream().map(line -> setRelationalPlaceholders(one, two, line)) + .collect(Collectors.toList()); + } + + // kyori doesn't seem to have a method that can do a contains with regex, we don't want to do a more expensive replace +// public static boolean containsPlaceholders(@Nullable final Component text) { +// return text != null && text.replaceText() +// } +} diff --git a/paper/src/main/java/me/clip/placeholderapi/replacer/ExactReplacer.java b/paper/src/main/java/me/clip/placeholderapi/replacer/ExactReplacer.java new file mode 100644 index 0000000..88f3b5e --- /dev/null +++ b/paper/src/main/java/me/clip/placeholderapi/replacer/ExactReplacer.java @@ -0,0 +1,56 @@ +package me.clip.placeholderapi.replacer; + +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import org.bukkit.OfflinePlayer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Function; +import java.util.regex.Pattern; + +public final class ExactReplacer implements Replacer { + private static final Pattern DELIMITER = Pattern.compile("_"); + + private final char start; + private final char end; + + public ExactReplacer(final char start, final char end) { + this.start = start; + this.end = end; + } + + @NotNull + @Override + public String apply(@NotNull String text, @Nullable final OfflinePlayer player, + @NotNull final Function lookup) { + text = text.substring(1, text.length() - 1); + final String[] parts = DELIMITER.split(text); + final PlaceholderExpansion expansion; + + if (parts.length == 0) { + expansion = lookup.apply(text); + } else { + expansion = lookup.apply(parts[0]); + } + + if (expansion == null) { + return start + text + end; + } + + final String params; + + if (text.endsWith("_")) { + params = ""; + } else { + params = text.substring(text.indexOf('_') + 1); + } + + final String result = expansion.onRequest(player, params); + + if (result == null) { + return start + text + end; + } + + return result; + } +} diff --git a/paper/src/main/java/me/clip/placeholderapi/replacer/RelationalExactReplacer.java b/paper/src/main/java/me/clip/placeholderapi/replacer/RelationalExactReplacer.java new file mode 100644 index 0000000..af5c7d8 --- /dev/null +++ b/paper/src/main/java/me/clip/placeholderapi/replacer/RelationalExactReplacer.java @@ -0,0 +1,53 @@ +package me.clip.placeholderapi.replacer; + +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.expansion.Relational; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.util.function.Function; +import java.util.regex.Pattern; + +public final class RelationalExactReplacer { + private static final Pattern DELIMITER = Pattern.compile("_"); + + @NotNull + public String apply(@NotNull String text, @Nullable final Player player1, + @Nullable final Player player2, @NotNull final Function lookup) { + final String[] parts = DELIMITER.split(text); + final PlaceholderExpansion expansion; + + if (parts.length == 0) { + expansion = lookup.apply(text); + } else { + expansion = lookup.apply(parts[0]); + } + + if (expansion == null) { + return "%rel_" + text + '%'; + } + + if (!(expansion instanceof Relational)) { + return "%rel_" + text + '%'; + } + + final String params; + + if (text.endsWith("_")) { + params = ""; + } else { + params = text.substring(text.indexOf('_') + 1); + } + + final String result = ((Relational) expansion).onPlaceholderRequest(player1, player2, params); + + if (result == null) { + return "%rel_" + text + '%'; + } + + return result; + } +} diff --git a/settings.gradle.kts b/settings.gradle.kts index 70e18e7..cbf315b 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1 +1,3 @@ rootProject.name = "PlaceholderAPI" + +include("spigot", "paper") \ No newline at end of file diff --git a/spigot/build.gradle.kts b/spigot/build.gradle.kts new file mode 100644 index 0000000..3b92ccf --- /dev/null +++ b/spigot/build.gradle.kts @@ -0,0 +1,41 @@ +import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar + +val javaComponent: SoftwareComponent = components["java"] + +tasks { + withType { + archiveClassifier.set("") + archiveBaseName.set("PlaceholderAPI-Spigot") + + relocate("org.bstats", "me.clip.placeholderapi.metrics") + relocate("net.kyori", "me.clip.placeholderapi.libs.kyori") + + exclude("META-INF/versions/**") + } + + publishing { + publications { + create("maven") { + artifactId = "placeholderapi" + from(javaComponent) + } + } + + repositories { + maven { + if ("-DEV" in version.toString()) { + url = uri("https://repo.extendedclip.com/snapshots") + } else { + url = uri("https://repo.extendedclip.com/releases") + } + + credentials { + username = System.getenv("JENKINS_USER") + password = System.getenv("JENKINS_PASS") + } + } + } + } + + publish.get().setDependsOn(listOf(build.get())) +} \ No newline at end of file diff --git a/spigot/src/main/java/me/clip/placeholderapi/PlaceholderAPI.java b/spigot/src/main/java/me/clip/placeholderapi/PlaceholderAPI.java new file mode 100644 index 0000000..10d30f5 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/PlaceholderAPI.java @@ -0,0 +1,606 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi; + +import com.google.common.collect.ImmutableSet; + +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.expansion.Relational; +import me.clip.placeholderapi.expansion.manager.LocalExpansionManager; +import me.clip.placeholderapi.replacer.CharsReplacer; +import me.clip.placeholderapi.replacer.Replacer; +import me.clip.placeholderapi.replacer.Replacer.Closure; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.OfflinePlayer; +import org.bukkit.entity.Player; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; + +public final class PlaceholderAPI { + + private static final Replacer REPLACER_PERCENT = new CharsReplacer(Closure.PERCENT); + private static final Replacer REPLACER_BRACKET = new CharsReplacer(Closure.BRACKET); + + static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("[%]([^%]+)[%]"); + static final Pattern BRACKET_PLACEHOLDER_PATTERN = Pattern.compile("[{]([^{}]+)[}]"); + static final Pattern RELATIONAL_PLACEHOLDER_PATTERN = Pattern + .compile("[%](rel_)([^%]+)[%]"); + + + private PlaceholderAPI() { + } + + // === Current API === + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal %_%}. + * + * @param player Player to parse the placeholders against + * @param text Text to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static String setPlaceholders(final OfflinePlayer player, + @NotNull final String text) { + return REPLACER_PERCENT.apply(text, player, + PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion); + } + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal %_%}. + * + * @param player Player to parse the placeholders against + * @param text List of Strings to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static List setPlaceholders(final OfflinePlayer player, + @NotNull final List text) { + return text.stream().map(line -> setPlaceholders(player, line)).collect(Collectors.toList()); + } + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal %_%}. + * + * @param player Player to parse the placeholders against + * @param text Text to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static String setPlaceholders(final Player player, @NotNull String text) { + return setPlaceholders(((OfflinePlayer) player), text); + } + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal %_%}. + * + * @param player Player to parse the placeholders against + * @param text List of Strings to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static List setPlaceholders(final Player player, @NotNull List<@NotNull String> text) { + return setPlaceholders(((OfflinePlayer) player), text); + } + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal {_}}. + * + * @param player Player to parse the placeholders against + * @param text Text to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static String setBracketPlaceholders(final OfflinePlayer player, + @NotNull final String text) { + return REPLACER_BRACKET.apply(text, player, + PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion); + } + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal {_}}. + * + * @param player Player to parse the placeholders against + * @param text List of Strings to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static List<@NotNull String> setBracketPlaceholders(final OfflinePlayer player, + @NotNull final List<@NotNull String> text) { + return text.stream().map(line -> setBracketPlaceholders(player, line)) + .collect(Collectors.toList()); + } + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal {_}}. + * + * @param player Player to parse the placeholders against + * @param text Text to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static String setBracketPlaceholders(Player player, @NotNull String text) { + return setBracketPlaceholders((OfflinePlayer) player, text); + } + + /** + * Translates all placeholders into their corresponding values. + *
The pattern of a valid placeholder is {@literal {_}}. + * + * @param player Player to parse the placeholders against + * @param text List of Strings to set the placeholder values in + * @return String containing all translated placeholders + */ + @NotNull + public static List setBracketPlaceholders(Player player, @NotNull List text) { + return setBracketPlaceholders((OfflinePlayer) player, text); + } + + /** + * set relational placeholders in the text specified placeholders are matched with the pattern + * {@literal %%} when set with this method + * + * @param one First player to compare + * @param two Second player to compare + * @param text Text to parse the placeholders in + * @return The text containing the parsed relational placeholders + */ + public static String setRelationalPlaceholders(Player one, Player two, String text) { + final Matcher matcher = RELATIONAL_PLACEHOLDER_PATTERN.matcher(text); + + while (matcher.find()) { + final String format = matcher.group(2); + final int index = format.indexOf("_"); + + if (index <= 0 || index >= format.length()) { + continue; + } + + String identifier = format.substring(0, index).toLowerCase(Locale.ROOT); + String params = format.substring(index + 1); + final PlaceholderExpansion expansion = PlaceholderAPIPlugin.getInstance() + .getLocalExpansionManager().getExpansion(identifier); + + if (!(expansion instanceof Relational)) { + continue; + } + + final String value = ((Relational) expansion).onPlaceholderRequest(one, two, params); + + if (value != null) { + text = text.replaceAll(Pattern.quote(matcher.group()), Matcher.quoteReplacement(value)); + } + } + + return text; + } + + /** + * Translate placeholders in the provided List based on the relation of the two provided players. + *
The pattern of a valid placeholder is {@literal %rel__%}. + * + * @param one Player to compare + * @param two Player to compare + * @param text text to parse the placeholder values to + * @return The text containing the parsed relational placeholders + */ + public static List setRelationalPlaceholders(Player one, Player two, List text) { + return text.stream().map(line -> setRelationalPlaceholders(one, two, line)) + .collect(Collectors.toList()); + } + + /** + * Check if a specific placeholder identifier is currently registered + * + * @param identifier The identifier to check + * @return true if identifier is already registered + */ + public static boolean isRegistered(@NotNull final String identifier) { + return PlaceholderAPIPlugin.getInstance().getLocalExpansionManager() + .findExpansionByIdentifier(identifier).isPresent(); + } + + /** + * Get all registered placeholder identifiers + * + * @return A Set of type String containing the identifiers of all registered expansions. + */ + @NotNull + public static Set getRegisteredIdentifiers() { + return ImmutableSet + .copyOf(PlaceholderAPIPlugin.getInstance().getLocalExpansionManager().getIdentifiers()); + } + + /** + * Get the normal placeholder pattern. + * + * @return Regex Pattern of {@literal [%]([^%]+)[%]} + */ + public static Pattern getPlaceholderPattern() { + return PLACEHOLDER_PATTERN; + } + + /** + * Get the bracket placeholder pattern. + * + * @return Regex Pattern of {@literal [{]([^{}]+)[}]} + */ + public static Pattern getBracketPlaceholderPattern() { + return BRACKET_PLACEHOLDER_PATTERN; + } + + /** + * Get the relational placeholder pattern. + * + * @return Regex Pattern of {@literal [%](rel_)([^%]+)[%]} + */ + public static Pattern getRelationalPlaceholderPattern() { + return RELATIONAL_PLACEHOLDER_PATTERN; + } + + /** + * Check if a String contains any PlaceholderAPI placeholders ({@literal + * %_%}). + * + * @param text String to check + * @return true if String contains any matches to the normal placeholder pattern, false otherwise + */ + public static boolean containsPlaceholders(String text) { + return text != null && PLACEHOLDER_PATTERN.matcher(text).find(); + } + + /** + * Check if a String contains any PlaceholderAPI bracket placeholders ({@literal + * {_}}). + * + * @param text String to check + * @return true if String contains any matches to the bracket placeholder pattern, false otherwise + */ + public static boolean containsBracketPlaceholders(String text) { + return text != null && BRACKET_PLACEHOLDER_PATTERN.matcher(text).find(); + } + + // === Deprecated API === + + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static boolean registerExpansion(PlaceholderExpansion expansion) { + return expansion.register(); + } + + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static boolean unregisterExpansion(PlaceholderExpansion expansion) { + return expansion.unregister(); + } + + /** + * Get map of registered placeholders + * + * @return Map of registered placeholders + * @deprecated Use {@link LocalExpansionManager#getExpansions()} instead. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static Map getPlaceholders() { + return PlaceholderAPIPlugin.getInstance().getLocalExpansionManager() + .getExpansions().stream() + .collect(Collectors.toMap(PlaceholderExpansion::getIdentifier, ex -> ex)); + } + + /** + * @param plugin The Plugin to register with this {@link PlaceholderHook} + * @param placeholderHook The {@link PlaceholderHook} to register + * @return always false + * @deprecated Please use {@link PlaceholderExpansion} to + * register placeholders instead + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static boolean registerPlaceholderHook(Plugin plugin, PlaceholderHook placeholderHook) { + Msg.warn("Nag author(s) %s of plugin %s about their usage of the deprecated PlaceholderHook" + + " class! This class will be removed in v2.13.0!", plugin.getDescription().getAuthors(), + plugin.getName()); + return false; + } + + /** + * @param identifier The identifier to use for the {@link PlaceholderHook} + * @param placeholderHook The {@link PlaceholderHook} to register + * @return always false + * @deprecated Please use {@link PlaceholderExpansion} to + * register placeholders instead + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static boolean registerPlaceholderHook(String identifier, + PlaceholderHook placeholderHook) { + Msg.warn("%s is attempting to register placeholders via deprecated PlaceholderHook class." + + " This class is no longer supported and will be removed in v2.13.0!", identifier); + return false; + } + + /** + * @param plugin The plugin to unregister + * @return always false + * @deprecated Please use {@link PlaceholderExpansion} to + * unregister placeholders instead + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static boolean unregisterPlaceholderHook(Plugin plugin) { + Msg.warn("Nag author(s) %s of plugin %s about their usage of the PlaceholderAPI class." + + " This way of unregistering placeholders is no longer supported and will be removed" + + " in v2.13.0!", plugin.getDescription().getAuthors(), plugin.getName()); + return false; + } + + /** + * @param identifier The identifier to unregister + * @return always false + * @deprecated Please use {@link PlaceholderExpansion} to + * unregister placeholders instead + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static boolean unregisterPlaceholderHook(String identifier) { + Msg.warn("%s is attempting to unregister placeholders via PlaceholderAPI class." + + " This way of unregistering placeholders is no longer supported and will be removed" + + " in v2.13.0!", identifier); + return false; + } + + /** + * @return Set of registered identifiers + * @deprecated Will be removed in a future release. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static Set getRegisteredPlaceholderPlugins() { + return getRegisteredIdentifiers(); + } + + /** + * @return always null + * @deprecated Will be removed in a future release. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static Set getExternalPlaceholderPlugins() { + return null; + } + + /** + * @param player The offline player to parse the placeholders against + * @param text The text to parse + * @param pattern The Pattern to use + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + * @deprecated Please use {@link #setPlaceholders(OfflinePlayer, String)} instead + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static String setPlaceholders(OfflinePlayer player, + String text, Pattern pattern, boolean colorize) { + return setPlaceholders(player, text); + } + + /** + * @param player The offline player to parse the placeholders against + * @param text The List of text to parse + * @param pattern The Pattern to use + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + * @deprecated Please use {@link #setPlaceholders(OfflinePlayer, List)} instead + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static List setPlaceholders(OfflinePlayer player, + List text, Pattern pattern, boolean colorize) { + return setPlaceholders(player, text); + } + + /** + * @param player The offline player to parse the placeholders against + * @param text The List of text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + * @deprecated Use {@link #setPlaceholders(OfflinePlayer, List)} instead. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static List setPlaceholders(OfflinePlayer player, List text, + boolean colorize) { + return setPlaceholders(player, text); + } + + /** + * @param player The offline player to parse the placeholders against + * @param text The List of text to parse + * @param pattern The Pattern to use + * @return String with the parsed placeholders + * @deprecated Use {@link #setPlaceholders(OfflinePlayer, List)} instead. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static List setPlaceholders(OfflinePlayer player, List text, + Pattern pattern) { + return setPlaceholders(player, text); + } + + /** + * @param player The offline player to parse the placeholders against + * @param text The text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + * @deprecated Will be removed in a future release. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static String setPlaceholders(Player player, String text, boolean colorize) { + return setPlaceholders(player, text); + } + + /** + * @param player The offline player to parse the placeholders against + * @param text The List of text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + * @deprecated Will be removed in a future release. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static List setPlaceholders(Player player, List text, boolean colorize) { + return setPlaceholders(player, text); + } + + /** + * @param player The offline player to parse the placeholders against + * @param text The text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static String setPlaceholders(OfflinePlayer player, String text, boolean colorize) { + return setPlaceholders(player, text); + } + + /** + * @param player The offline player to parse the placeholders against + * @param text The text to parse + * @param pattern The Pattern to use + * @return String with the parsed placeholders + * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static String setPlaceholders(OfflinePlayer player, String text, Pattern pattern) { + return setPlaceholders(player, text); + } + + /** + * @param player The offline player to parse the placeholders against + * @param text The List of text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + * @deprecated Use {@link #setPlaceholders(OfflinePlayer, List)} instead. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static List setBracketPlaceholders(OfflinePlayer player, List text, + boolean colorize) { + return setBracketPlaceholders(player, text); + } + + /** + * @param player The offline player to parse the placeholders against + * @param text The text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static String setBracketPlaceholders(OfflinePlayer player, String text, boolean colorize) { + return setBracketPlaceholders(player, text); + } + + /** + * @param player The offline player to parse the placeholders against + * @param text The text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + * @deprecated Will be removed in a future release. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static String setBracketPlaceholders(Player player, String text, boolean colorize) { + return setBracketPlaceholders(player, text); + } + + /** + * @param player The offline player to parse the placeholders against + * @param text The List of text to parse + * @param colorize If PlaceholderAPI should also parse color codes + * @return String with the parsed placeholders + * @deprecated Will be removed in a future release. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static List setBracketPlaceholders(Player player, List text, + boolean colorize) { + return setBracketPlaceholders(player, text); + } + + /** + * set relational placeholders in the text specified placeholders are matched with the pattern + * {@literal %%} when set with this method + * + * @param one Player to compare + * @param two Player to compare + * @param text Text to parse the placeholders in + * @param colorize If color codes ({@literal &[0-1a-fk-o]}) should be translated + * @return The text containing the parsed relational placeholders + * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static String setRelationalPlaceholders(Player one, Player two, String text, + boolean colorize) { + return setRelationalPlaceholders(one, two, text); + } + + /** + * Translate placeholders in the provided list based on the relation of the two provided players. + *
The pattern of a valid placeholder is {@literal %rel__%}. + * + * @param one First player to compare + * @param two Second player to compare + * @param text Text to parse the placeholders in + * @param colorize If color codes ({@literal &[0-1a-fk-o]}) should be translated + * @return The text containing the parsed relational placeholders + * @deprecated Use {@link #setRelationalPlaceholders(Player, Player, List)} instead. + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public static List setRelationalPlaceholders(Player one, Player two, List text, + boolean colorize) { + return setRelationalPlaceholders(one, two, text); + } +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/PlaceholderAPIPlugin.java b/spigot/src/main/java/me/clip/placeholderapi/PlaceholderAPIPlugin.java new file mode 100644 index 0000000..719a26d --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/PlaceholderAPIPlugin.java @@ -0,0 +1,303 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi; + +import java.text.SimpleDateFormat; +import java.util.HashMap; +import java.util.Map; + +import me.clip.placeholderapi.commands.PlaceholderCommandRouter; +import me.clip.placeholderapi.configuration.PlaceholderAPIConfig; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.expansion.Version; +import me.clip.placeholderapi.expansion.manager.CloudExpansionManager; +import me.clip.placeholderapi.expansion.manager.LocalExpansionManager; +import me.clip.placeholderapi.listeners.ServerLoadEventListener; +import me.clip.placeholderapi.scheduler.UniversalScheduler; +import me.clip.placeholderapi.scheduler.scheduling.schedulers.TaskScheduler; +import me.clip.placeholderapi.updatechecker.UpdateChecker; +import me.clip.placeholderapi.util.ExpansionSafetyCheck; +import me.clip.placeholderapi.util.Msg; +import net.kyori.adventure.platform.bukkit.BukkitAudiences; +import org.bstats.bukkit.Metrics; +import org.bstats.charts.AdvancedPie; +import org.bstats.charts.SimplePie; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.command.PluginCommand; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.plugin.java.JavaPlugin; +import org.jetbrains.annotations.NotNull; + +/** + * Yes I have a shit load of work to do... + * + * @author Ryan McCarthy + */ +public final class PlaceholderAPIPlugin extends JavaPlugin { + + @NotNull + private static final Version VERSION; + private static PlaceholderAPIPlugin instance; + + static { + String version = Bukkit.getServer().getBukkitVersion().split("-")[0]; + String suffix; + if (version.chars() + .filter(c -> c == '.') + .count() == 1) { + suffix = "R1"; + version = 'v' + version.replace('.', '_') + '_' + suffix; + } else { + int minor = Integer.parseInt(version.split("\\.")[2].charAt(0) + ""); + version = 'v' + version.replace('.', '_').replace("_" + minor, "") + '_' + "R" + (minor - 1); + } + + boolean isSpigot; + try { + Class.forName("org.spigotmc.SpigotConfig"); + isSpigot = true; + } catch (final ExceptionInInitializerError | ClassNotFoundException ignored) { + isSpigot = false; + } + + VERSION = new Version(version, isSpigot); + } + + @NotNull + private final PlaceholderAPIConfig config = new PlaceholderAPIConfig(this); + + @NotNull + private final LocalExpansionManager localExpansionManager = new LocalExpansionManager(this); + @NotNull + private final CloudExpansionManager cloudExpansionManager = new CloudExpansionManager(this); + @NotNull + private final TaskScheduler scheduler = UniversalScheduler.getScheduler(this); + + private BukkitAudiences adventure; + private boolean safetyCheck = false; + + + /** + * Gets the static instance of the main class for PlaceholderAPI. This class is not the actual API + * class, this is the main class that extends JavaPlugin. For most API methods, use static methods + * available from the class: {@link PlaceholderAPI} + * + * @return PlaceholderAPIPlugin instance + */ + @NotNull + public static PlaceholderAPIPlugin getInstance() { + return instance; + } + + /** + * Get the configurable {@linkplain String} value that should be returned when a boolean is true + * + * @return string value of true + */ + @NotNull + public static String booleanTrue() { + return getInstance().getPlaceholderAPIConfig().booleanTrue(); + } + + /** + * Get the configurable {@linkplain String} value that should be returned when a boolean is false + * + * @return string value of false + */ + @NotNull + public static String booleanFalse() { + return getInstance().getPlaceholderAPIConfig().booleanFalse(); + } + + /** + * Get the configurable {@linkplain SimpleDateFormat} object that is used to parse time for + * generic time based placeholders + * + * @return date format + */ + @NotNull + public static SimpleDateFormat getDateFormat() { + try { + return new SimpleDateFormat(getInstance().getPlaceholderAPIConfig().dateFormat()); + } catch (final IllegalArgumentException ex) { + Msg.warn("Configured date format ('%s') is invalid! Defaulting to 'MM/dd/yy HH:mm:ss'", + ex, getInstance().getPlaceholderAPIConfig().dateFormat()); + return new SimpleDateFormat("MM/dd/yy HH:mm:ss"); + } + } + + @Deprecated + public static Version getServerVersion() { + return VERSION; + } + + @Override + public void onLoad() { + saveDefaultConfig(); + + safetyCheck = new ExpansionSafetyCheck(this).runChecks(); + + if (safetyCheck) { + return; + } + + instance = this; + } + + @Override + public void onEnable() { + if (safetyCheck) { + return; + } + + setupCommand(); + setupMetrics(); + setupExpansions(); + + adventure = BukkitAudiences.create(this); + + if (config.isCloudEnabled()) { + getCloudExpansionManager().load(); + } + + if (config.checkUpdates()) { + new UpdateChecker(this).fetch(); + } + } + + @Override + public void onDisable() { + if (safetyCheck) { + return; + } + + getCloudExpansionManager().kill(); + getLocalExpansionManager().kill(); + + HandlerList.unregisterAll(this); + + scheduler.cancelTasks(this); + + adventure.close(); + adventure = null; + + instance = null; + } + + public void reloadConf(@NotNull final CommandSender sender) { + getLocalExpansionManager().kill(); + + reloadConfig(); + + getLocalExpansionManager().load(sender); + + if (config.isCloudEnabled()) { + getCloudExpansionManager().load(); + } else { + getCloudExpansionManager().kill(); + } + } + + @NotNull + public LocalExpansionManager getLocalExpansionManager() { + return localExpansionManager; + } + + @NotNull + public CloudExpansionManager getCloudExpansionManager() { + return cloudExpansionManager; + } + + @NotNull + public BukkitAudiences getAdventure() { + if (adventure == null) { + throw new IllegalStateException("Tried to access Adventure when the plugin was disabled!"); + } + + return adventure; + } + + @NotNull + public TaskScheduler getScheduler() { + return scheduler; + } + + /** + * Obtain the configuration class for PlaceholderAPI. + * + * @return PlaceholderAPIConfig instance + */ + @NotNull + public PlaceholderAPIConfig getPlaceholderAPIConfig() { + return config; + } + + private void setupCommand() { + final PluginCommand pluginCommand = getCommand("placeholderapi"); + if (pluginCommand == null) { + return; + } + + final PlaceholderCommandRouter router = new PlaceholderCommandRouter(this); + pluginCommand.setExecutor(router); + pluginCommand.setTabCompleter(router); + + try { + getServer().getPluginManager().registerEvents((Listener) Class.forName("me.clip.placeholderapi.TestListener").newInstance(), this); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void setupMetrics() { + final Metrics metrics = new Metrics(this, 438); + metrics.addCustomChart(new SimplePie("using_expansion_cloud", + () -> getPlaceholderAPIConfig().isCloudEnabled() ? "yes" : "no")); + + metrics.addCustomChart(new SimplePie("using_spigot", () -> getServerVersion().isSpigot() ? "yes" : "no")); + + metrics.addCustomChart(new AdvancedPie("expansions_used", () -> { + final Map values = new HashMap<>(); + + for (final PlaceholderExpansion expansion : getLocalExpansionManager().getExpansions()) { + values.put(expansion.getRequiredPlugin() == null ? expansion.getIdentifier() + : expansion.getRequiredPlugin(), 1); + } + + return values; + })); + } + + private void setupExpansions() { + Bukkit.getPluginManager().registerEvents(getLocalExpansionManager(), this); + + try { + Class.forName("org.bukkit.event.server.ServerLoadEvent"); + new ServerLoadEventListener(this); + } catch (final ClassNotFoundException ignored) { + scheduler + .runTaskLater(() -> getLocalExpansionManager().load(Bukkit.getConsoleSender()), 1); + } + } + +} diff --git a/src/main/java/me/clip/placeholderapi/PlaceholderHook.java b/spigot/src/main/java/me/clip/placeholderapi/PlaceholderHook.java similarity index 70% rename from src/main/java/me/clip/placeholderapi/PlaceholderHook.java rename to spigot/src/main/java/me/clip/placeholderapi/PlaceholderHook.java index 9906b8a..d187a5a 100644 --- a/src/main/java/me/clip/placeholderapi/PlaceholderHook.java +++ b/spigot/src/main/java/me/clip/placeholderapi/PlaceholderHook.java @@ -26,17 +26,17 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class PlaceholderHook { - @Nullable - public String onRequest(final OfflinePlayer player, @NotNull final String params) { - if (player != null && player.isOnline()) { - return onPlaceholderRequest(player.getPlayer(), params); + @Nullable + public String onRequest(final OfflinePlayer player, @NotNull final String params) { + if (player != null && player.isOnline()) { + return onPlaceholderRequest(player.getPlayer(), params); + } + + return onPlaceholderRequest(null, params); } - return onPlaceholderRequest(null, params); - } - - @Nullable - public String onPlaceholderRequest(final Player player, @NotNull final String params) { - return null; - } + @Nullable + public String onPlaceholderRequest(final Player player, @NotNull final String params) { + return null; + } } diff --git a/spigot/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommand.java b/spigot/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommand.java new file mode 100644 index 0000000..ae94bc2 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommand.java @@ -0,0 +1,110 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.commands; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; + +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.stream.Stream; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; + +public abstract class PlaceholderCommand { + + @NotNull + private final String label; + @NotNull + private final Set alias; + + @Nullable + private String permission; + + + protected PlaceholderCommand(@NotNull final String label, @NotNull final String... alias) { + this.label = label; + this.alias = Sets.newHashSet(alias); + + setPermission("placeholderapi." + label); + } + + @NotNull + public static Stream filterByPermission(@NotNull final CommandSender sender, + @NotNull final Stream commands) { + return commands.filter( + target -> target.getPermission() == null || sender.hasPermission(target.getPermission())); + } + + public static void suggestByParameter(@NotNull final Stream possible, + @NotNull final List suggestions, @Nullable final String parameter) { + if (parameter == null) { + possible.forEach(suggestions::add); + } else { + possible.filter(suggestion -> suggestion.toLowerCase(Locale.ROOT).startsWith(parameter.toLowerCase(Locale.ROOT))) + .forEach(suggestions::add); + } + } + + @NotNull + public final String getLabel() { + return label; + } + + @NotNull + @Unmodifiable + public final Set getAlias() { + return ImmutableSet.copyOf(alias); + } + + @NotNull + @Unmodifiable + public final Set getLabels() { + return ImmutableSet.builder().add(label).addAll(alias).build(); + } + + @Nullable + public final String getPermission() { + return permission; + } + + public void setPermission(@NotNull final String permission) { + this.permission = permission; + } + + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + + } + + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + + } + +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommandRouter.java b/spigot/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommandRouter.java new file mode 100644 index 0000000..d53f4ce --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommandRouter.java @@ -0,0 +1,145 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.commands; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Stream; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.commands.impl.cloud.CommandECloud; +import me.clip.placeholderapi.commands.impl.local.CommandDump; +import me.clip.placeholderapi.commands.impl.local.CommandExpansionRegister; +import me.clip.placeholderapi.commands.impl.local.CommandExpansionUnregister; +import me.clip.placeholderapi.commands.impl.local.CommandHelp; +import me.clip.placeholderapi.commands.impl.local.CommandInfo; +import me.clip.placeholderapi.commands.impl.local.CommandList; +import me.clip.placeholderapi.commands.impl.local.CommandParse; +import me.clip.placeholderapi.commands.impl.local.CommandReload; +import me.clip.placeholderapi.commands.impl.local.CommandVersion; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.command.TabCompleter; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +public final class PlaceholderCommandRouter implements CommandExecutor, TabCompleter { + + @Unmodifiable + private static final List COMMANDS = ImmutableList.of(new CommandHelp(), + new CommandInfo(), + new CommandList(), + new CommandDump(), + new CommandECloud(), + new CommandParse(), + new CommandReload(), + new CommandVersion(), + new CommandExpansionRegister(), + new CommandExpansionUnregister()); + + + @NotNull + private final PlaceholderAPIPlugin plugin; + @NotNull + @Unmodifiable + private final Map commands; + + + public PlaceholderCommandRouter(@NotNull final PlaceholderAPIPlugin plugin) { + this.plugin = plugin; + + final ImmutableMap.Builder commands = ImmutableMap.builder(); + + for (final PlaceholderCommand command : COMMANDS) { + command.getLabels().forEach(label -> commands.put(label, command)); + } + + this.commands = commands.build(); + } + + + @Override + public boolean onCommand(@NotNull final CommandSender sender, @NotNull final Command command, + @NotNull final String alias, @NotNull final String[] args) { + if (args.length == 0) { + final PlaceholderCommand fallback = commands.get("version"); + if (fallback != null) { + fallback.evaluate(plugin, sender, "", Collections.emptyList()); + } + + return true; + } + + final String search = args[0].toLowerCase(Locale.ROOT); + final PlaceholderCommand target = commands.get(search); + + if (target == null) { + Msg.msg(sender, "&cUnknown command &7" + search); + return true; + } + + final String permission = target.getPermission(); + if (permission != null && !permission.isEmpty() && !sender.hasPermission(permission)) { + Msg.msg(sender, "&cYou do not have permission to do this!"); + return true; + } + + target + .evaluate(plugin, sender, search, Arrays.asList(Arrays.copyOfRange(args, 1, args.length))); + + return true; + } + + @Override + public List onTabComplete(@NotNull final CommandSender sender, + @NotNull final Command command, @NotNull final String alias, @NotNull final String[] args) { + final List suggestions = new ArrayList<>(); + + if (args.length > 1) { + final PlaceholderCommand target = this.commands.get(args[0].toLowerCase(Locale.ROOT)); + + if (target != null) { + target.complete(plugin, sender, args[0].toLowerCase(Locale.ROOT), + Arrays.asList(Arrays.copyOfRange(args, 1, args.length)), suggestions); + } + + return suggestions; + } + + final Stream targets = PlaceholderCommand + .filterByPermission(sender, commands.values().stream()).map(PlaceholderCommand::getLabels) + .flatMap(Collection::stream); + PlaceholderCommand.suggestByParameter(targets, suggestions, args.length == 0 ? null : args[0]); + + return suggestions; + } + +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloud.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloud.java new file mode 100644 index 0000000..f9c2e3e --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloud.java @@ -0,0 +1,146 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.cloud; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.commands.PlaceholderCommand; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Stream; + +public final class CommandECloud extends PlaceholderCommand { + + @Unmodifiable + private static final List COMMANDS = ImmutableList + .of(new CommandECloudClear(), + new CommandECloudStatus(), + new CommandECloudUpdate(), + new CommandECloudRefresh(), + new CommandECloudDownload(), + new CommandECloudExpansionInfo(), + new CommandECloudExpansionList(), + new CommandECloudExpansionPlaceholders()); + + static { + COMMANDS + .forEach(command -> command.setPermission("placeholderapi.ecloud." + command.getLabel())); + } + + @NotNull + @Unmodifiable + private final Map commands; + + + public CommandECloud() { + super("ecloud"); + + final ImmutableMap.Builder commands = ImmutableMap.builder(); + + for (final PlaceholderCommand command : COMMANDS) { + command.getLabels().forEach(label -> commands.put(label, command)); + } + + this.commands = commands.build(); + } + + + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { + Msg.msg(sender, + "&b&lPlaceholderAPI &8- &7eCloud Help Menu &8- ", + " ", + "&b/papi &fecloud status", + " &7&oView status of the eCloud", + "&b/papi &fecloud list {page}", + " &7&oList all/author specific available expansions", + "&b/papi &fecloud info {version}", + " &7&oView information about a specific expansion available on the eCloud", + "&b/papi &fecloud placeholders ", + " &7&oView placeholders for an expansion", + "&b/papi &fecloud download {version}", + " &7&oDownload an expansion from the eCloud", + "&b/papi &fecloud update ", + " &7&oUpdate a specific/all installed expansions", + "&b/papi &fecloud refresh", + " &7&oFetch the most up to date list of expansions available.", + "&b/papi &fecloud clear", + " &7&oClear the expansion cloud cache."); + + return; + } + + final String search = params.get(0).toLowerCase(Locale.ROOT); + final PlaceholderCommand target = commands.get(search); + + if (target == null) { + Msg.msg(sender, "&cUnknown command &7ecloud " + search); + return; + } + + final String permission = target.getPermission(); + if (permission != null && !permission.isEmpty() && !sender.hasPermission(permission)) { + Msg.msg(sender, "&cYou do not have permission to do this!"); + return; + } + + if (!plugin.getPlaceholderAPIConfig().isCloudEnabled()) { + Msg.msg(sender, "&cThe eCloud Manager is not enabled! To enable it, set 'cloud_enabled' to true and reload the plugin."); + return; + } + + target.evaluate(plugin, sender, search, params.subList(1, params.size())); + } + + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() <= 1) { + final Stream targets = filterByPermission(sender, commands.values().stream()) + .map(PlaceholderCommand::getLabels).flatMap(Collection::stream); + suggestByParameter(targets, suggestions, params.isEmpty() ? null : params.get(0)); + + return; // send sub commands + } + + final String search = params.get(0).toLowerCase(Locale.ROOT); + final PlaceholderCommand target = commands.get(search); + + if (target == null) { + return; + } + + target.complete(plugin, sender, search, params.subList(1, params.size()), suggestions); + } + +} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudClear.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudClear.java similarity index 72% rename from src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudClear.java rename to spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudClear.java index 6083d5d..db0b145 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudClear.java +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudClear.java @@ -21,6 +21,7 @@ package me.clip.placeholderapi.commands.impl.cloud; import java.util.List; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.util.Msg; @@ -30,17 +31,17 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandECloudClear extends PlaceholderCommand { - public CommandECloudClear() { - super("clear"); - } + public CommandECloudClear() { + super("clear"); + } - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - plugin.getCloudExpansionManager().clean(); - Msg.msg(sender, - "&aThe eCloud cache has been cleared!"); - } + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + plugin.getCloudExpansionManager().clean(); + Msg.msg(sender, + "&aThe eCloud cache has been cleared!"); + } } diff --git a/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudDownload.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudDownload.java new file mode 100644 index 0000000..d8434f6 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudDownload.java @@ -0,0 +1,140 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.cloud; + +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.commands.PlaceholderCommand; +import me.clip.placeholderapi.expansion.cloud.CloudExpansion; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +public final class CommandECloudDownload extends PlaceholderCommand { + + public CommandECloudDownload() { + super("download"); + } + + private boolean isBlockedExpansion(String name) { + String env = System.getenv("PAPI_BLOCKED_EXPANSIONS"); + if (env == null) { + return false; + } + + return Arrays.stream(env.split(",")) + .anyMatch(s -> s.equalsIgnoreCase(name)); + } + + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { + Msg.msg(sender, + "&cYou must supply the name of an expansion."); + return; + } + + if (isBlockedExpansion(params.get(0))) { + Msg.msg(sender, + "&cThis expansion can't be downloaded."); + return; + } + + final CloudExpansion expansion = plugin.getCloudExpansionManager() + .findCloudExpansionByName(params.get(0)).orElse(null); + if (expansion == null) { + Msg.msg(sender, + "&cFailed to find an expansion named: &f" + params.get(0)); + return; + } + + final CloudExpansion.Version version; + if (params.size() < 2) { + version = expansion.getVersion(expansion.getLatestVersion()); + if (version == null) { + Msg.msg(sender, + "&cCould not find latest version for expansion."); + return; + } + } else { + version = expansion.getVersion(params.get(1)); + if (version == null) { + Msg.msg(sender, + "&cCould not find specified version: &f" + params.get(1), + "&7Available versions: &f" + expansion.getAvailableVersions()); + return; + } + } + + if (!version.isVerified()) { + Msg.msg(sender, "&cThe expansion '&f" + params.get(0) + "&c' is not verified and can only be downloaded manually from &fhttps://ecloud.placeholderapi.com"); + return; + } + + plugin.getCloudExpansionManager().downloadExpansion(expansion, version) + .whenComplete((file, exception) -> { + if (exception != null) { + Msg.msg(sender, + "&cFailed to download expansion: &f" + exception.getMessage()); + return; + } + + Msg.msg(sender, + "&aSuccessfully downloaded expansion &f" + expansion.getName() + " [" + version + .getVersion() + "] &ato file: &f" + file.getName(), + "&aMake sure to type &f/papi reload &ato enable your new expansion!"); + + plugin.getCloudExpansionManager().load(); + }); + } + + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 2) { + return; + } + + if (params.size() <= 1) { + final Stream names = plugin.getCloudExpansionManager().getCloudExpansions().values() + .stream().map(CloudExpansion::getName).map(name -> name.replace(' ', '_')); + suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); + return; + } + + final Optional expansion = plugin.getCloudExpansionManager() + .findCloudExpansionByName(params.get(0)); + if (!expansion.isPresent()) { + return; + } + + suggestByParameter(expansion.get().getAvailableVersions().stream(), suggestions, params.get(1)); + } + +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionInfo.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionInfo.java new file mode 100644 index 0000000..0c7e851 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionInfo.java @@ -0,0 +1,133 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.cloud; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Stream; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.commands.PlaceholderCommand; +import me.clip.placeholderapi.expansion.cloud.CloudExpansion; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +public final class CommandECloudExpansionInfo extends PlaceholderCommand { + + public CommandECloudExpansionInfo() { + super("info"); + } + + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { + Msg.msg(sender, + "&cYou must specify the name of the expansion."); + return; + } + + final CloudExpansion expansion = plugin.getCloudExpansionManager() + .findCloudExpansionByName(params.get(0)).orElse(null); + if (expansion == null) { + Msg.msg(sender, + "&cThere is no expansion with the name: &f" + params.get(0)); + return; + } + + final StringBuilder builder = new StringBuilder(); + + builder.append("&bExpansion: &f") + .append(expansion.shouldUpdate() ? "&e" : "&a") + .append(expansion.getName()) + .append('\n') + .append("&bAuthor: &f") + .append(expansion.getAuthor()) + .append('\n'); + + if (params.size() < 2) { + builder.append("&bLatest Version: &f") + .append(expansion.getLatestVersion()) + .append('\n') + .append("&bReleased: &f") + .append(expansion.getTimeSinceLastUpdate()) + .append(" ago") + .append('\n') + .append("&bVerified: ") + .append(expansion.getVersion().isVerified() ? "&a&l✔" : "&c&l❌") + .append('\n') + .append("&bRelease Notes: &f") + .append(expansion.getVersion().getReleaseNotes()) + .append('\n'); + } else { + final CloudExpansion.Version version = expansion.getVersion(params.get(1)); + if (version == null) { + Msg.msg(sender, + "&cCould not find specified version: &f" + params.get(1), + "&aVersions: &f" + expansion.getAvailableVersions()); + return; + } + + builder.append("&bVersion: &f") + .append(version.getVersion()) + .append('\n') + .append("&bVerified: ") + .append(version.isVerified() ? "&a&l✔" : "&c&l❌") + .append('\n') + .append("&bRelease Notes: &f") + .append(version.getReleaseNotes()) + .append('\n') + .append("&bDownload URL: &f") + .append(version.getUrl()) + .append('\n'); + } + + Msg.msg(sender, builder.toString()); + } + + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 2) { + return; + } + + if (params.size() <= 1) { + final Stream names = plugin.getCloudExpansionManager().getCloudExpansions().values() + .stream().map(CloudExpansion::getName).map(name -> name.replace(' ', '_')); + suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); + return; + } + + final Optional expansion = plugin.getCloudExpansionManager() + .findCloudExpansionByName(params.get(0)); + if (!expansion.isPresent()) { + return; + } + + suggestByParameter(expansion.get().getAvailableVersions().stream(), suggestions, params.get(1)); + } + +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionList.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionList.java new file mode 100644 index 0000000..d38fcd2 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionList.java @@ -0,0 +1,354 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.cloud; + +import com.google.common.base.Strings; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.google.common.primitives.Ints; + +import java.text.SimpleDateFormat; +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.commands.PlaceholderCommand; +import me.clip.placeholderapi.configuration.ExpansionSort; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.expansion.cloud.CloudExpansion; +import me.clip.placeholderapi.util.Format; +import me.clip.placeholderapi.util.Msg; +import net.kyori.adventure.text.Component; +import net.kyori.adventure.text.TextComponent; +import net.kyori.adventure.text.event.ClickEvent; +import net.kyori.adventure.text.event.HoverEvent; +import net.kyori.adventure.text.format.NamedTextColor; +import net.kyori.adventure.text.format.TextDecoration; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +import static net.kyori.adventure.text.Component.*; +import static net.kyori.adventure.text.format.NamedTextColor.*; + +public final class CommandECloudExpansionList extends PlaceholderCommand { + + private static final int PAGE_SIZE = 10; + + @NotNull + private static final Function EXPANSION_NAME = + expansion -> (expansion.shouldUpdate() ? "&6" : expansion.hasExpansion() ? "&a" : "&7") + + expansion.getName(); + @NotNull + private static final Function EXPANSION_AUTHOR = + expansion -> "&f" + expansion.getAuthor(); + @NotNull + private static final Function EXPANSION_VERIFIED = + expansion -> expansion.getVersion().isVerified() ? "&aY" : "&cN"; + @NotNull + private static final Function EXPANSION_LATEST_VERSION = + expansion -> "&f" + expansion.getLatestVersion(); + @NotNull + private static final Function EXPANSION_CURRENT_VERSION = + expansion -> "&f" + PlaceholderAPIPlugin.getInstance().getLocalExpansionManager() + .findExpansionByName(expansion.getName()).map(PlaceholderExpansion::getVersion) + .orElse("Unknown"); + + + @Unmodifiable + private static final Set OPTIONS = ImmutableSet.of("all", "installed"); + + + public CommandECloudExpansionList() { + super("list"); + } + + @NotNull + private static Collection getExpansions(@NotNull final String target, + @NotNull final PlaceholderAPIPlugin plugin) { + switch (target.toLowerCase(Locale.ROOT)) { + case "all": + return plugin.getCloudExpansionManager().getCloudExpansions().values(); + case "installed": + return plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values(); + default: + return plugin.getCloudExpansionManager().getCloudExpansionsByAuthor(target).values(); + } + } + + @NotNull + private static List getPage(@NotNull final List expansions, + final int page) { + final int head = (page * PAGE_SIZE); + final int tail = Math.min(expansions.size(), head + PAGE_SIZE); + + if (expansions.size() < head) { + return Collections.emptyList(); + } + + return expansions.subList(head, tail); + } + + public static void addExpansionTitle(@NotNull final StringBuilder builder, + @NotNull final String target, final int page) { + switch (target.toLowerCase(Locale.ROOT)) { + case "all": + builder.append("&bAll Expansions"); + break; + case "installed": + builder.append("&bInstalled Expansions"); + break; + default: + builder.append("&bExpansions by &f") + .append(target); + break; + } + + if (page == -1) { + builder.append('\n'); + return; + } + + builder.append(" &bPage&7: &a") + .append(page) + .append("&r"); + } + + private static Component getMessage(@NotNull final List expansions, + final int page, final int limit, @NotNull final String target) { + final SimpleDateFormat format = PlaceholderAPIPlugin.getDateFormat(); + + final TextComponent.Builder message = text(); + + for (int index = 0; index < expansions.size(); index++) { + final CloudExpansion expansion = expansions.get(index); + final TextComponent.Builder line = text(); + + final int expansionNumber = index + ((page - 1) * PAGE_SIZE) + 1; + line.append(text(expansionNumber + ". ", DARK_GRAY)); + + final NamedTextColor expansionColour; + + if (expansion.shouldUpdate()) { + expansionColour = GOLD; + } else { + if (expansion.hasExpansion()) { + expansionColour = GREEN; + } else { + expansionColour = GRAY; + } + } + + line.append(text(expansion.getName(), expansionColour)); + + line.clickEvent(ClickEvent.suggestCommand("/papi ecloud download " + expansion.getName())); + + final TextComponent.Builder hoverText = text("Click to download this expansion!", AQUA) + .append(newline()).append(newline()) + .append(text("Author: ", AQUA)).append(text(expansion.getAuthor(), WHITE)) + .append(newline()) + .append(text("Verified: ", AQUA)).append(text(expansion.getVersion().isVerified() ? "✔" : "❌", expansion.getVersion().isVerified() ? GREEN : RED, TextDecoration.BOLD)) + .append(newline()) + .append(text("Released: ", AQUA)).append(text(format.format(expansion.getLastUpdate()), WHITE)) + .toBuilder(); + + Optional.ofNullable(expansion.getDescription()) + .filter(description -> !description.isEmpty()) + .ifPresent(description -> hoverText.append(newline()).append(newline()) + .append(text(description.replace("\r", "").trim(), WHITE)) + ); + + line.hoverEvent(HoverEvent.showText(hoverText.build())); + + if (index != expansions.size() - 1) { + line.append(newline()); + } + + message.append(line.build()); + } + + if (limit > 1) { + message.append(newline()); + + final TextComponent.Builder left = text("◀", page > 1 ? GRAY : DARK_GRAY).toBuilder(); + + if (page > 1) { + left.clickEvent(ClickEvent.runCommand("/papi ecloud list " + target + " " + (page - 1))); + } + + final TextComponent.Builder right = text("▶", page < limit ? GRAY : DARK_GRAY).toBuilder(); + + if (page < limit) { + right.clickEvent(ClickEvent.runCommand("/papi ecloud list " + target + " " + (page + 1))); + } + + message.append(left, text(" " + page + " ", GREEN), right); + } + + return message.build(); + } + + private static void addExpansionTable(@NotNull final List expansions, + @NotNull final StringBuilder message, final int startIndex, + @NotNull final String versionTitle, + @NotNull final Function versionFunction) { + final Map> functions = new LinkedHashMap<>(); + + final AtomicInteger counter = new AtomicInteger(startIndex); + functions.put("&f", expansion -> "&8" + counter.getAndIncrement() + "."); + + functions.put("&9Name", EXPANSION_NAME); + functions.put("&9Author", EXPANSION_AUTHOR); + functions.put("&9Verified", EXPANSION_VERIFIED); + functions.put(versionTitle, versionFunction); + + final List> rows = new ArrayList<>(); + + rows.add(0, new ArrayList<>(functions.keySet())); + + for (final CloudExpansion expansion : expansions) { + rows.add(functions.values().stream().map(function -> function.apply(expansion)) + .map(Objects::toString).collect(Collectors.toList())); + } + + final List table = Format.tablify(Format.Align.LEFT, rows) + .orElse(Collections.emptyList()); + if (table.isEmpty()) { + return; + } + + table.add(1, "&8" + Strings.repeat("-", table.get(0).length() - (rows.get(0).size() * 2))); + + message.append(String.join("\n", table)); + } + + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { + Msg.msg(sender, + "&cYou must specify an option. [all, {author}, installed]"); + return; + } + + final boolean installed = params.get(0).equalsIgnoreCase("installed"); + final List expansions = Lists + .newArrayList(getExpansions(params.get(0), plugin)); + + if (expansions.isEmpty()) { + Msg.msg(sender, + "&cNo expansions available to list."); + return; + } + + expansions + .sort(plugin.getPlaceholderAPIConfig().getExpansionSort().orElse(ExpansionSort.LATEST)); + + if (!(sender instanceof Player) && params.size() < 2) { + final StringBuilder builder = new StringBuilder(); + + addExpansionTitle(builder, params.get(0), -1); + addExpansionTable(expansions, + builder, + 1, + installed ? "&9Version" : "&9Latest Version", + installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION); + + Msg.msg(sender, builder.toString()); + return; + } + + final int page; + + if (params.size() < 2) { + page = 1; + } else { + //noinspection UnstableApiUsage + final Integer parsed = Ints.tryParse(params.get(1)); + if (parsed == null) { + Msg.msg(sender, + "&cPage number must be an integer."); + return; + } + + final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE); + + if (parsed < 1 || parsed > limit) { + Msg.msg(sender, + "&cPage number must be in the range &8[&a1&7..&a" + limit + "&8]"); + return; + } + + page = parsed; + } + + final StringBuilder builder = new StringBuilder(); + final List values = getPage(expansions, page - 1); + + addExpansionTitle(builder, params.get(0), page); + + if (!(sender instanceof Player)) { + addExpansionTable(values, + builder, + ((page - 1) * PAGE_SIZE) + 1, + installed ? "&9Version" : "&9Latest Version", + installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION); + + Msg.msg(sender, builder.toString()); + + return; + } + + Msg.msg(sender, builder.toString()); + + final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE); + + final Component message = getMessage(values, page, limit, params.get(0)); + plugin.getAdventure().player((Player) sender).sendMessage(message); + } + + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 2) { + return; + } + + if (params.size() <= 1) { + suggestByParameter( + Sets.union(OPTIONS, plugin.getCloudExpansionManager().getCloudExpansionAuthors()) + .stream(), suggestions, params.isEmpty() ? null : params.get(0)); + return; + } + + suggestByParameter(IntStream.rangeClosed(1, + (int) Math.ceil((double) getExpansions(params.get(0), plugin).size() / PAGE_SIZE)) + .mapToObj(Objects::toString), suggestions, params.get(1)); + } + +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionPlaceholders.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionPlaceholders.java new file mode 100644 index 0000000..3fcab71 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionPlaceholders.java @@ -0,0 +1,96 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.cloud; + +import com.google.common.collect.Lists; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.commands.PlaceholderCommand; +import me.clip.placeholderapi.expansion.cloud.CloudExpansion; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +public final class CommandECloudExpansionPlaceholders extends PlaceholderCommand { + + public CommandECloudExpansionPlaceholders() { + super("placeholders"); + } + + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { + Msg.msg(sender, + "&cYou must specify the name of the expansion."); + return; + } + + final CloudExpansion expansion = plugin.getCloudExpansionManager() + .findCloudExpansionByName(params.get(0)).orElse(null); + if (expansion == null) { + Msg.msg(sender, + "&cThere is no expansion with the name: &f" + params.get(0)); + return; + } + + final List placeholders = expansion.getPlaceholders(); + if (placeholders == null || placeholders.isEmpty()) { + Msg.msg(sender, + "&cThe expansion specified does not have placeholders listed."); + return; + } + + final List> partitions = Lists + .partition(placeholders.stream().sorted().collect(Collectors.toList()), 10); + + Msg.msg(sender, + "&6" + placeholders.size() + "&7 placeholders: &a", + partitions.stream().map(partition -> String.join(", ", partition)) + .collect(Collectors.joining("\n"))); + + } + + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 1) { + return; + } + + final Stream names = plugin.getCloudExpansionManager() + .getCloudExpansions() + .values() + .stream() + .map(CloudExpansion::getName) + .map(name -> name.replace(' ', '_')); + + suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); + } + +} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudRefresh.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudRefresh.java similarity index 72% rename from src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudRefresh.java rename to spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudRefresh.java index c814d9e..b64dd92 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudRefresh.java +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudRefresh.java @@ -21,6 +21,7 @@ package me.clip.placeholderapi.commands.impl.cloud; import java.util.List; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.util.Msg; @@ -30,18 +31,18 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandECloudRefresh extends PlaceholderCommand { - public CommandECloudRefresh() { - super("refresh"); - } + public CommandECloudRefresh() { + super("refresh"); + } - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - plugin.getCloudExpansionManager().load(); + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + plugin.getCloudExpansionManager().load(); - Msg.msg(sender, - "&aThe eCloud manager has been refreshed!"); - } + Msg.msg(sender, + "&aThe eCloud manager has been refreshed!"); + } } diff --git a/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudStatus.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudStatus.java new file mode 100644 index 0000000..e921187 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudStatus.java @@ -0,0 +1,65 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.cloud; + +import java.util.List; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.commands.PlaceholderCommand; +import me.clip.placeholderapi.expansion.manager.CloudExpansionManager; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +public final class CommandECloudStatus extends PlaceholderCommand { + + public CommandECloudStatus() { + super("status"); + } + + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + final CloudExpansionManager manager = plugin.getCloudExpansionManager(); + + final int updateCount = manager.getCloudUpdateCount(); + final int authorCount = manager.getCloudExpansionAuthorCount(); + final int expansionCount = manager.getCloudExpansions().size(); + + final StringBuilder builder = new StringBuilder(); + + builder.append("&bThere are &a").append(expansionCount) + .append("&b expansions available on the eCloud.").append('\n'); + builder.append("&7A total of &f").append(authorCount) + .append("&7 authors have contributed to the eCloud.").append('\n'); + + if (updateCount > 0) { + builder.append("&eYou have &f").append(updateCount) + .append(updateCount > 1 ? "&e expansions" : "&e expansion").append(" installed that ") + .append(updateCount > 1 ? "have an" : "has an").append(" update available."); + } + + Msg.msg(sender, builder.toString()); + } + +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudUpdate.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudUpdate.java new file mode 100644 index 0000000..1a33d92 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudUpdate.java @@ -0,0 +1,143 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.cloud; + +import com.google.common.collect.Lists; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.stream.Collectors; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.commands.PlaceholderCommand; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.expansion.cloud.CloudExpansion; +import me.clip.placeholderapi.util.Futures; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; + +/** + * please don't flame me for this code, I will fix this shit later. + */ +public final class CommandECloudUpdate extends PlaceholderCommand { + + public CommandECloudUpdate() { + super("update"); + } + + private static CompletableFuture>> downloadAndDiscover( + @NotNull final List expansions, @NotNull final PlaceholderAPIPlugin plugin) { + return expansions.stream() + .map(expansion -> plugin.getCloudExpansionManager() + .downloadExpansion(expansion, expansion.getVersion())) + .map(future -> future.thenCompose(plugin.getLocalExpansionManager()::findExpansionInFile)) + .collect(Futures.collector()); + } + + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { + Msg.msg(sender, + "&cYou must define 'all' or the name of an expansion to update."); + return; + } + + final boolean multiple = params.get(0).equalsIgnoreCase("all"); + final List expansions = new ArrayList<>(); + + // gather target expansions + if (multiple) { + expansions.addAll(plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values()); + } else { + plugin.getCloudExpansionManager().findCloudExpansionByName(params.get(0)) + .ifPresent(expansions::add); + } + + // remove the ones that are the latest version + expansions.removeIf(expansion -> !expansion.shouldUpdate()); + + if (expansions.isEmpty()) { + Msg.msg(sender, + "&cNo updates available for " + (!multiple ? "this expansion." + : "your active expansions.")); + return; + } + + Msg.msg(sender, + "&aUpdating expansions: " + expansions.stream().map(CloudExpansion::getName) + .collect(Collectors.joining("&7, &6", "&8[&6", "&8]&r"))); + + Futures.onMainThread(plugin, downloadAndDiscover(expansions, plugin), (classes, exception) -> { + if (exception != null) { + Msg.msg(sender, + "&cFailed to update expansions: &e" + exception.getMessage()); + return; + } + + Msg.msg(sender, + "&aSuccessfully downloaded updates, registering new versions."); + + final String message = classes.stream() + .filter(Objects::nonNull) + .map(plugin.getLocalExpansionManager()::register) + .filter(Optional::isPresent) + .map(Optional::get) + .map(expansion -> " &a" + expansion.getName() + " &f" + expansion.getVersion()) + .collect(Collectors.joining("\n")); + + Msg.msg(sender, + "&7Registered expansions:", message); + + }); + } + + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 1) { + return; + } + + final List installed = Lists + .newArrayList(plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values()); + installed.removeIf(expansion -> !expansion.shouldUpdate()); + + if (!installed.isEmpty() && (params.isEmpty() || "all" + .startsWith(params.get(0).toLowerCase(Locale.ROOT)))) { + suggestions.add("all"); + } + + suggestByParameter( + installed.stream().map(CloudExpansion::getName).map(name -> name.replace(" ", "_")), + suggestions, params.isEmpty() ? null : params.get(0)); + } + +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandDump.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandDump.java new file mode 100644 index 0000000..23555e1 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandDump.java @@ -0,0 +1,213 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.local; + +import com.google.common.io.CharStreams; +import com.google.gson.Gson; +import com.google.gson.JsonObject; +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.commands.PlaceholderCommand; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.time.Instant; +import java.time.ZoneId; +import java.time.format.DateTimeFormatter; +import java.time.format.FormatStyle; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.logging.Level; +import java.util.stream.Collectors; + +public final class CommandDump extends PlaceholderCommand { + + @NotNull + private static final String URL = "https://paste.helpch.at/"; + + @NotNull + private static final Gson gson = new Gson(); + + @NotNull + private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter + .ofLocalizedDateTime(FormatStyle.LONG) + .withLocale(Locale.US) + .withZone(ZoneId.of("UTC")); + + + public CommandDump() { + super("dump"); + } + + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + postDump(makeDump(plugin)).whenComplete((key, exception) -> { + if (exception != null) { + plugin.getLogger().log(Level.WARNING, "failed to post dump details", exception); + + Msg.msg(sender, + "&cFailed to post dump details, check console."); + return; + } + + Msg.msg(sender, + "&aSuccessfully posted dump: " + URL + key); + }); + } + + @NotNull + private CompletableFuture postDump(@NotNull final String dump) { + return CompletableFuture.supplyAsync(() -> { + try { + final HttpURLConnection connection = ((HttpURLConnection) new URL(URL + "documents") + .openConnection()); + connection.setRequestMethod("POST"); + connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); + connection.setDoOutput(true); + + connection.connect(); + + try (final OutputStream stream = connection.getOutputStream()) { + stream.write(dump.getBytes(StandardCharsets.UTF_8)); + } + + try (final InputStream stream = connection.getInputStream()) { + final String json = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8)); + return gson.fromJson(json, JsonObject.class).get("key").getAsString(); + } + } catch (final IOException ex) { + throw new CompletionException(ex); + } + }); + } + + @NotNull + private String makeDump(@NotNull final PlaceholderAPIPlugin plugin) { + final StringBuilder builder = new StringBuilder(); + + builder.append("Generated: ") + .append(DATE_FORMAT.format(Instant.now())) + .append("\n\n"); + + builder.append("PlaceholderAPI: ") + .append(plugin.getDescription().getVersion()) + .append("\n\n"); + + builder.append("Expansions Registered:") + .append('\n'); + + final List expansions = plugin.getLocalExpansionManager() + .getExpansions() + .stream() + .sorted( + Comparator.comparing(PlaceholderExpansion::getIdentifier) + .thenComparing(PlaceholderExpansion::getAuthor) + ) + .collect(Collectors.toList()); + + int size = expansions.stream().map(e -> e.getIdentifier().length()) + .max(Integer::compareTo) + .orElse(0); + + for (final PlaceholderExpansion expansion : expansions) { + builder.append(" ") + .append(String.format("%-" + size + "s", expansion.getIdentifier())) + .append(" [Author: ") + .append(expansion.getAuthor()) + .append(", Version: ") + .append(expansion.getVersion()) + .append("]\n"); + + } + + builder.append('\n'); + + builder.append("Expansions Directory:") + .append('\n'); + + final String[] jars = plugin.getLocalExpansionManager() + .getExpansionsFolder() + .list((dir, name) -> name.toLowerCase(Locale.ROOT).endsWith(".jar")); + + + if (jars == null) { + builder.append(" ¨[Warning]: Could not load jar files from expansions folder."); + } else { + for (final String jar : jars) { + builder.append(" ") + .append(jar) + .append('\n'); + } + } + + builder.append('\n'); + + builder.append("Server Info: ") + .append(plugin.getServer().getBukkitVersion()) + .append('/') + .append(plugin.getServer().getVersion()) + .append("\n"); + + builder.append("Java Version: ") + .append(System.getProperty("java.version")) + .append("\n\n"); + + builder.append("Plugin Info:") + .append('\n'); + + List plugins = Arrays.stream(plugin.getServer().getPluginManager().getPlugins()) + .sorted(Comparator.comparing(Plugin::getName)) + .collect(Collectors.toList()); + + size = plugins.stream().map(pl -> pl.getName().length()) + .max(Integer::compareTo) + .orElse(0); + + for (final Plugin other : plugins) { + builder.append(" ") + .append(String.format("%-" + size + "s", other.getName())) + .append(" [Authors: [") + .append(String.join(", ", other.getDescription().getAuthors())) + .append("], Version: ") + .append(other.getDescription().getVersion()) + .append("]") + .append("\n"); + } + + return builder.toString(); + } +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionRegister.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionRegister.java new file mode 100644 index 0000000..0544204 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionRegister.java @@ -0,0 +1,111 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.local; + +import java.io.File; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.logging.Level; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.commands.PlaceholderCommand; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.expansion.manager.LocalExpansionManager; +import me.clip.placeholderapi.util.Futures; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +public final class CommandExpansionRegister extends PlaceholderCommand { + + public CommandExpansionRegister() { + super("register"); + } + + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.size() < 1) { + Msg.msg(sender, + "&cYou must specify the name of an expansion file."); + return; + } + + final LocalExpansionManager manager = plugin.getLocalExpansionManager(); + + final File file = new File(manager.getExpansionsFolder(), params.get(0)); + if (!file.exists() || !file.getParentFile().equals(manager.getExpansionsFolder())) { + Msg.msg(sender, + "&cThe file &f" + file.getName() + "&c doesn't exist!"); + return; + } + + Futures.onMainThread(plugin, manager.findExpansionInFile(file), (clazz, exception) -> { + if (exception != null) { + Msg.msg(sender, + "&cFailed to find expansion in file: &f" + file); + + plugin.getLogger() + .log(Level.WARNING, "failed to find expansion in file: " + file, exception); + return; + } + + if (clazz == null) { + Msg.msg(sender, + "&cNo expansion class found in file: &f" + file); + return; + } + + final Optional expansion = manager.register(clazz); + if (!expansion.isPresent()) { + Msg.msg(sender, + "&cFailed to register expansion from &f" + params.get(0)); + return; + } + + Msg.msg(sender, + "&aSuccessfully registered expansion: &f" + expansion.get().getName()); + + }); + } + + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 1) { + return; + } + + final String[] fileNames = plugin.getLocalExpansionManager().getExpansionsFolder() + .list((dir, name) -> name.endsWith(".jar")); + if (fileNames == null || fileNames.length == 0) { + return; + } + + suggestByParameter(Arrays.stream(fileNames), suggestions, + params.isEmpty() ? null : params.get(0)); + } + +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionUnregister.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionUnregister.java new file mode 100644 index 0000000..231a7c2 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionUnregister.java @@ -0,0 +1,78 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.local; + +import java.util.List; +import java.util.Optional; + +import me.clip.placeholderapi.PlaceholderAPI; +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.commands.PlaceholderCommand; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +public final class CommandExpansionUnregister extends PlaceholderCommand { + + public CommandExpansionUnregister() { + super("unregister"); + } + + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { + Msg.msg(sender, + "&cYou must specify the name of the expansion."); + return; + } + + final Optional expansion = plugin.getLocalExpansionManager() + .findExpansionByName(params.get(0)); + if (!expansion.isPresent()) { + Msg.msg(sender, + "&cThere is no expansion loaded with the identifier: &f" + params.get(0)); + return; + } + + final String message = !expansion.get().unregister() ? + "&cFailed to unregister expansion: &f" : + "&aSuccessfully unregistered expansion: &f"; + + Msg.msg(sender, message + expansion.get().getName()); + } + + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 1) { + return; + } + + suggestByParameter(PlaceholderAPI.getRegisteredIdentifiers().stream(), suggestions, + params.isEmpty() ? null : params.get(0)); + } + +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandHelp.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandHelp.java new file mode 100644 index 0000000..f2b3bd1 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandHelp.java @@ -0,0 +1,73 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.local; + +import java.util.List; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.commands.PlaceholderCommand; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.command.CommandSender; +import org.bukkit.plugin.PluginDescriptionFile; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +public final class CommandHelp extends PlaceholderCommand { + + public CommandHelp() { + super("help"); + } + + + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + final PluginDescriptionFile description = plugin.getDescription(); + + Msg.msg(sender, + "&b&lPlaceholderAPI &8- &7Help Menu &8- &7(&f" + description.getVersion() + "&7)", + " ", + "&b/papi &fbcparse &9 ", + " &7&oParse a message with placeholders and broadcast it", + "&b/papi &fcmdparse &9 ", + " &7&oParse a message with relational placeholders", + "&b/papi &fdump", + " &7&oDump all relevant information needed to help debug issues into a paste link.", + "&b/papi &finfo &9", + " &7&oView information for a specific expansion", + "&b/papi &flist", + " &7&oList active expansions", + "&b/papi &fparse &9 ", + " &7&oParse a message with placeholders", + "&b/papi &fparserel &9 ", + " &7&oParse a message with relational placeholders", + "&b/papi &fregister &9", + " &7&oRegister an expansion by the name of the file", + "&b/papi &freload", + " &7&oReload the config of PAPI", + "&b/papi &funregister &9", + " &7&oUnregister an expansion by name", + "&b/papi &fversion", + " &7&oView plugin info/version"); + } + +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandInfo.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandInfo.java new file mode 100644 index 0000000..4badaf6 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandInfo.java @@ -0,0 +1,114 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.local; + +import java.util.List; + +import me.clip.placeholderapi.PlaceholderAPI; +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.commands.PlaceholderCommand; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +public final class CommandInfo extends PlaceholderCommand { + + public CommandInfo() { + super("info"); + } + + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (params.isEmpty()) { + Msg.msg(sender, + "&cYou must specify the name of the expansion."); + return; + } + + final PlaceholderExpansion expansion = plugin.getLocalExpansionManager() + .findExpansionByIdentifier(params.get(0)).orElse(null); + if (expansion == null) { + Msg.msg(sender, + "&cThere is no expansion loaded with the identifier: &f" + params.get(0)); + return; + } + + final StringBuilder builder = new StringBuilder(); + + builder.append("&7Placeholder expansion info for: &r") + .append(expansion.getName()) + .append('\n') + .append("&7Status: &r") + .append(expansion.isRegistered() ? "&aRegistered" : "7cNotRegistered") + .append('\n'); + + final String author = expansion.getAuthor(); + if (author != null) { + builder.append("&7Author: &r") + .append(author) + .append('\n'); + } + + final String version = expansion.getVersion(); + if (version != null) { + builder.append("&7Version: &r") + .append(version) + .append('\n'); + } + + final String requiredPlugin = expansion.getRequiredPlugin(); + if (requiredPlugin != null) { + builder.append("&7Requires plugin: &r") + .append(requiredPlugin) + .append('\n'); + } + + final List placeholders = expansion.getPlaceholders(); + if (placeholders != null && !placeholders.isEmpty()) { + builder.append("&8&m-- &7Placeholders &8&m--&r") + .append('\n'); + + for (final String placeholder : placeholders) { + builder.append(placeholder) + .append('\n'); + } + } + + Msg.msg(sender, builder.toString()); + } + + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() > 1) { + return; + } + + suggestByParameter(PlaceholderAPI.getRegisteredIdentifiers().stream(), suggestions, + params.isEmpty() ? null : params.get(0)); + } + +} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandList.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandList.java similarity index 58% rename from src/main/java/me/clip/placeholderapi/commands/impl/local/CommandList.java rename to spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandList.java index 0284b89..d3bf0d9 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandList.java +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandList.java @@ -21,9 +21,11 @@ package me.clip.placeholderapi.commands.impl.local; import com.google.common.collect.Lists; + import java.util.List; import java.util.Set; import java.util.stream.Collectors; + import me.clip.placeholderapi.PlaceholderAPI; import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; @@ -34,28 +36,28 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandList extends PlaceholderCommand { - public CommandList() { - super("list"); - } - - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - final Set identifiers = PlaceholderAPI.getRegisteredIdentifiers(); - if (identifiers.isEmpty()) { - Msg.msg(sender, "&cThere are no placeholder hooks active!"); - return; + public CommandList() { + super("list"); } - final List> partitions = Lists - .partition(identifiers.stream().sorted().collect(Collectors.toList()), 10); - Msg.msg(sender, - "&7A total of &f" + identifiers.size() + "&7 placeholder hook(s) are active: &a", - partitions.stream().map(partition -> String.join("&7, &a", partition)) - .collect(Collectors.joining("\n"))); - } + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + final Set identifiers = PlaceholderAPI.getRegisteredIdentifiers(); + if (identifiers.isEmpty()) { + Msg.msg(sender, "&cThere are no placeholder hooks active!"); + return; + } + + final List> partitions = Lists + .partition(identifiers.stream().sorted().collect(Collectors.toList()), 10); + + Msg.msg(sender, + "&7A total of &f" + identifiers.size() + "&7 placeholder hook(s) are active: &a", + partitions.stream().map(partition -> String.join("&7, &a", partition)) + .collect(Collectors.joining("\n"))); + } } diff --git a/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandParse.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandParse.java new file mode 100644 index 0000000..ad752ab --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandParse.java @@ -0,0 +1,257 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.local; + +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.stream.Stream; + +import me.clip.placeholderapi.PlaceholderAPI; +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.commands.PlaceholderCommand; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.Bukkit; +import org.bukkit.OfflinePlayer; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; + +public final class CommandParse extends PlaceholderCommand { + + public CommandParse() { + super("parse", "bcparse", "parserel", "cmdparse"); + } + + + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + switch (alias.toLowerCase(Locale.ROOT)) { + case "parserel": + evaluateParseRelation(sender, params); + break; + case "parse": + evaluateParseSingular(sender, params, false, false); + break; + case "bcparse": + evaluateParseSingular(sender, params, true, false); + break; + case "cmdparse": + evaluateParseSingular(sender, params, false, true); + break; + } + } + + @Override + public void complete(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + switch (alias.toLowerCase(Locale.ROOT)) { + case "parserel": + completeParseRelation(params, suggestions); + break; + case "parse": + case "bcparse": + case "cmdparse": + completeParseSingular(sender, params, suggestions); + break; + } + } + + + private void evaluateParseSingular(@NotNull final CommandSender sender, + @NotNull @Unmodifiable final List params, final boolean broadcast, + final boolean command) { + if (params.size() < 2) { + Msg.msg(sender, + "&cYou must provide a target and message: &b/papi " + + (command ? "cmdparse" : (broadcast ? "bcparse" : "parse")) + + " &7{target} &a{message}"); + return; + } + + OfflinePlayer player; + + if ("me".equalsIgnoreCase(params.get(0))) { + if (!(sender instanceof Player)) { + Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!"); + return; + } + + player = ((Player) sender); + } else if ("--null".equalsIgnoreCase(params.get(0))) { + player = null; + } else { + final OfflinePlayer target = resolvePlayer(params.get(0)); + if (target == null) { + Msg.msg(sender, "&cFailed to find player: &7" + params.get(0)); + return; + } + + player = target; + } + + final String message = PlaceholderAPI + .setPlaceholders(player, String.join(" ", params.subList(1, params.size()))); + + if (command) { + Bukkit.dispatchCommand(sender, message); + return; + } + + if (broadcast) { + Bukkit.broadcastMessage(message); + } else { + sender.sendMessage(message); + } + } + + private void evaluateParseRelation(@NotNull final CommandSender sender, + @NotNull @Unmodifiable final List params) { + if (params.size() < 3) { + Msg.msg(sender, + "&cYou must supply two targets, and a message: &b/papi parserel &7{target one} " + + "{target two} &a{message}"); + return; + } + + OfflinePlayer playerOne; + + if ("me".equalsIgnoreCase(params.get(0))) { + if (!(sender instanceof Player)) { + Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!"); + return; + } + + playerOne = ((Player) sender); + } else { + playerOne = resolvePlayer(params.get(0)); + } + + if (playerOne == null || !playerOne.isOnline()) { + Msg.msg(sender, "&cFailed to find player: &f" + params.get(0)); + return; + } + + OfflinePlayer playerTwo; + + if ("me".equalsIgnoreCase(params.get(1))) { + if (!(sender instanceof Player)) { + Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!"); + return; + } + + playerTwo = ((Player) sender); + } else { + playerTwo = resolvePlayer(params.get(1)); + } + + if (playerTwo == null || !playerTwo.isOnline()) { + Msg.msg(sender, "&cFailed to find player: &f" + params.get(1)); + return; + } + + final String message = PlaceholderAPI + .setRelationalPlaceholders((Player) playerOne, (Player) playerTwo, + String.join(" ", params.subList(2, params.size()))); + + sender.sendMessage(message); + } + + + private void completeParseSingular(@NotNull final CommandSender sender, + @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { + if (params.size() <= 1) { + if (sender instanceof Player && (params.isEmpty() || "me" + .startsWith(params.get(0).toLowerCase(Locale.ROOT)))) { + suggestions.add("me"); + } + + if ("--null".startsWith(params.get(0).toLowerCase(Locale.ROOT))) { + suggestions.add("--null"); + } + + final Stream names = Bukkit.getOnlinePlayers().stream().map(Player::getName); + suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); + + return; + } + + final String name = params.get(params.size() - 1); + if (!name.startsWith("%") || name.endsWith("%")) { + return; + } + + final int index = name.indexOf('_'); + if (index == -1) { + return; // no arguments supplied yet + } + + final PlaceholderExpansion expansion = PlaceholderAPIPlugin.getInstance() + .getLocalExpansionManager().findExpansionByIdentifier(name.substring(1, index)) + .orElse(null); + if (expansion == null) { + return; + } + + final Set possible = new HashSet<>(expansion.getPlaceholders()); + + PlaceholderAPIPlugin.getInstance() + .getCloudExpansionManager() + .findCloudExpansionByName(expansion.getName()) + .ifPresent(cloud -> possible.addAll(cloud.getPlaceholders())); + + suggestByParameter(possible.stream(), suggestions, params.get(params.size() - 1)); + } + + private void completeParseRelation(@NotNull @Unmodifiable final List params, + @NotNull final List suggestions) { + if (params.size() > 2) { + return; + } + + final Stream names = Bukkit.getOnlinePlayers().stream().map(Player::getName); + suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(params.size() - 1)); + } + + + @Nullable + private OfflinePlayer resolvePlayer(@NotNull final String name) { + OfflinePlayer target = Bukkit.getPlayerExact(name); + + if (target == null) { + // Not the best option, but Spigot doesn't offer a good replacement (as usual) + target = Bukkit.getOfflinePlayer(name); + + return target.hasPlayedBefore() ? target : null; + } + + return target; + + } + +} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandReload.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandReload.java similarity index 74% rename from src/main/java/me/clip/placeholderapi/commands/impl/local/CommandReload.java rename to spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandReload.java index e60d4b6..3797856 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandReload.java +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandReload.java @@ -21,6 +21,7 @@ package me.clip.placeholderapi.commands.impl.local; import java.util.List; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.util.ExpansionSafetyCheck; @@ -30,17 +31,17 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandReload extends PlaceholderCommand { - public CommandReload() { - super("reload"); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (!new ExpansionSafetyCheck(plugin).runChecks()) { - plugin.reloadConf(sender); + public CommandReload() { + super("reload"); + } + + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + if (!new ExpansionSafetyCheck(plugin).runChecks()) { + plugin.reloadConf(sender); + } } - } } diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandVersion.java b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandVersion.java similarity index 65% rename from src/main/java/me/clip/placeholderapi/commands/impl/local/CommandVersion.java rename to spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandVersion.java index f637d9c..939c63d 100644 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandVersion.java +++ b/spigot/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandVersion.java @@ -21,6 +21,7 @@ package me.clip.placeholderapi.commands.impl.local; import java.util.List; + import me.clip.placeholderapi.PlaceholderAPIPlugin; import me.clip.placeholderapi.commands.PlaceholderCommand; import me.clip.placeholderapi.util.Msg; @@ -31,22 +32,22 @@ import org.jetbrains.annotations.Unmodifiable; public final class CommandVersion extends PlaceholderCommand { - public CommandVersion() { - super("version"); - } + public CommandVersion() { + super("version"); + } - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - final PluginDescriptionFile description = plugin.getDescription(); + @Override + public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CommandSender sender, @NotNull final String alias, + @NotNull @Unmodifiable final List params) { + final PluginDescriptionFile description = plugin.getDescription(); - Msg.msg(sender, - "&b&lPlaceholderAPI &7(&f" + description.getVersion() + "&7)", - "&7Author: &f" + description.getAuthors(), - "&7PAPI Commands: &b/papi &fhelp", - "&7eCloud Commands&8: &b/papi &fecloud"); - } + Msg.msg(sender, + "&b&lPlaceholderAPI &7(&f" + description.getVersion() + "&7)", + "&7Author: &f" + description.getAuthors(), + "&7PAPI Commands: &b/papi &fhelp", + "&7eCloud Commands&8: &b/papi &fecloud"); + } } diff --git a/src/main/java/me/clip/placeholderapi/configuration/ExpansionSort.java b/spigot/src/main/java/me/clip/placeholderapi/configuration/ExpansionSort.java similarity index 64% rename from src/main/java/me/clip/placeholderapi/configuration/ExpansionSort.java rename to spigot/src/main/java/me/clip/placeholderapi/configuration/ExpansionSort.java index 87a795c..5f5d01d 100644 --- a/src/main/java/me/clip/placeholderapi/configuration/ExpansionSort.java +++ b/spigot/src/main/java/me/clip/placeholderapi/configuration/ExpansionSort.java @@ -21,27 +21,28 @@ package me.clip.placeholderapi.configuration; import java.util.Comparator; + import me.clip.placeholderapi.expansion.cloud.CloudExpansion; import org.jetbrains.annotations.NotNull; public enum ExpansionSort implements Comparator { - NAME(Comparator.comparing(CloudExpansion::getName)), - AUTHOR(Comparator.comparing(CloudExpansion::getAuthor)), - LATEST(Comparator.comparing(CloudExpansion::getLastUpdate).reversed()); + NAME(Comparator.comparing(CloudExpansion::getName)), + AUTHOR(Comparator.comparing(CloudExpansion::getAuthor)), + LATEST(Comparator.comparing(CloudExpansion::getLastUpdate).reversed()); - @NotNull - private final Comparator comparator; + @NotNull + private final Comparator comparator; - ExpansionSort(@NotNull final Comparator comparator) { - this.comparator = comparator; - } + ExpansionSort(@NotNull final Comparator comparator) { + this.comparator = comparator; + } - @Override - public final int compare(final CloudExpansion expansion1, final CloudExpansion expansion2) { - return comparator.compare(expansion1, expansion2); - } + @Override + public final int compare(final CloudExpansion expansion1, final CloudExpansion expansion2) { + return comparator.compare(expansion1, expansion2); + } } diff --git a/spigot/src/main/java/me/clip/placeholderapi/configuration/PlaceholderAPIConfig.java b/spigot/src/main/java/me/clip/placeholderapi/configuration/PlaceholderAPIConfig.java new file mode 100644 index 0000000..891498d --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/configuration/PlaceholderAPIConfig.java @@ -0,0 +1,94 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.configuration; + +import java.util.Optional; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import org.jetbrains.annotations.NotNull; + +public final class PlaceholderAPIConfig { + + @NotNull + private final PlaceholderAPIPlugin plugin; + + public PlaceholderAPIConfig(@NotNull final PlaceholderAPIPlugin plugin) { + this.plugin = plugin; + } + + + public boolean checkUpdates() { + return plugin.getConfig().getBoolean("check_updates"); + } + + + public boolean isCloudEnabled() { + return plugin.getConfig().getBoolean("cloud_enabled"); + } + + public void setCloudEnabled(boolean state) { + plugin.getConfig().set("cloud_enabled", state); + plugin.saveConfig(); + } + + + public boolean isDebugMode() { + return plugin.getConfig().getBoolean("debug", false); + } + + + public Optional getExpansionSort() { + final String option = plugin.getConfig() + .getString("cloud_sorting", ExpansionSort.LATEST.name()); + + try { + //noinspection ConstantConditions (bad spigot annotation) + return Optional.of(ExpansionSort.valueOf(option.toUpperCase())); + } catch (final IllegalArgumentException ignored) { + return Optional.empty(); + } + } + + + @NotNull + public String dateFormat() { + //noinspection ConstantConditions (bad spigot annotation) + return plugin.getConfig().getString("date_format", "MM/dd/yy HH:mm:ss"); + } + + + @NotNull + public String booleanTrue() { + //noinspection ConstantConditions (bad spigot annotation) + return plugin.getConfig().getString("boolean.true", "true"); + } + + @NotNull + public String booleanFalse() { + //noinspection ConstantConditions (bad spigot annotation) + return plugin.getConfig().getString("boolean.false", "false"); + } + + public boolean detectMaliciousExpansions() { + return plugin.getConfig().getBoolean("detect_malicious_expansions", true); + } + +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/events/ExpansionRegisterEvent.java b/spigot/src/main/java/me/clip/placeholderapi/events/ExpansionRegisterEvent.java new file mode 100644 index 0000000..ebef47a --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/events/ExpansionRegisterEvent.java @@ -0,0 +1,89 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.events; + +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.jetbrains.annotations.NotNull; + +/** + * This event indicates that a single {@link PlaceholderExpansion PlaceholderExpansion} has + * been registered in PlaceholderAPI. + * + *

To know when all Expansions have been registered, use the + * {@link me.clip.placeholderapi.events.ExpansionsLoadedEvent ExpansionsLoadedEvent} instead. + */ +public final class ExpansionRegisterEvent extends Event implements Cancellable { + + @NotNull + private static final HandlerList HANDLERS = new HandlerList(); + @NotNull + private final PlaceholderExpansion expansion; + private boolean cancelled; + + public ExpansionRegisterEvent(@NotNull final PlaceholderExpansion expansion) { + this.expansion = expansion; + } + + @NotNull + public static HandlerList getHandlerList() { + return HANDLERS; + } + + /** + * The {@link PlaceholderExpansion PlaceholderExpansion} that was registered in PlaceholderAPI. + *
The PlaceholderExpansion will be available for use when the event + * {@link #isCancelled() was not cancelled}! + * + * @return Current instance of the registered {@link PlaceholderExpansion PlaceholderExpansion} + */ + @NotNull + public PlaceholderExpansion getExpansion() { + return expansion; + } + + /** + * Indicates if this event was cancelled or not. + *
A cancelled Event will result in the {@link #getExpansion() PlaceholderExpansion} NOT + * being added to PlaceholderAPI's internal list and will therefore be considered not registered + * anymore. + * + * @return Whether the event has been cancelled or not. + */ + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + + @NotNull + @Override + public HandlerList getHandlers() { + return HANDLERS; + } + +} diff --git a/src/main/java/me/clip/placeholderapi/events/ExpansionUnregisterEvent.java b/spigot/src/main/java/me/clip/placeholderapi/events/ExpansionUnregisterEvent.java similarity index 65% rename from src/main/java/me/clip/placeholderapi/events/ExpansionUnregisterEvent.java rename to spigot/src/main/java/me/clip/placeholderapi/events/ExpansionUnregisterEvent.java index e899b60..3e04410 100644 --- a/src/main/java/me/clip/placeholderapi/events/ExpansionUnregisterEvent.java +++ b/spigot/src/main/java/me/clip/placeholderapi/events/ExpansionUnregisterEvent.java @@ -28,7 +28,7 @@ import org.jetbrains.annotations.NotNull; /** * This event indicates that a {@link PlaceholderExpansion PlaceholderExpansion} has been * unregistered by PlaceholderAPI. - * + * *

Note that this event is triggered before the PlaceholderExpansion is completely * removed. *
This includes removing any Listeners, stopping active tasks and clearing the cache of @@ -36,35 +36,35 @@ import org.jetbrains.annotations.NotNull; */ public final class ExpansionUnregisterEvent extends Event { - @NotNull - private static final HandlerList HANDLERS = new HandlerList(); - - @NotNull - private final PlaceholderExpansion expansion; + @NotNull + private static final HandlerList HANDLERS = new HandlerList(); - public ExpansionUnregisterEvent(@NotNull final PlaceholderExpansion expansion) { - this.expansion = expansion; - } + @NotNull + private final PlaceholderExpansion expansion; - @NotNull - public static HandlerList getHandlerList() { - return HANDLERS; - } - - /** - * The {@link PlaceholderExpansion PlaceholderExpansion} that was unregistered. - * - * @return The {@link PlaceholderExpansion PlaceholderExpansion} instance. - */ - @NotNull - public PlaceholderExpansion getExpansion() { - return expansion; - } + public ExpansionUnregisterEvent(@NotNull final PlaceholderExpansion expansion) { + this.expansion = expansion; + } - @NotNull - @Override - public HandlerList getHandlers() { - return HANDLERS; - } + @NotNull + public static HandlerList getHandlerList() { + return HANDLERS; + } + + /** + * The {@link PlaceholderExpansion PlaceholderExpansion} that was unregistered. + * + * @return The {@link PlaceholderExpansion PlaceholderExpansion} instance. + */ + @NotNull + public PlaceholderExpansion getExpansion() { + return expansion; + } + + @NotNull + @Override + public HandlerList getHandlers() { + return HANDLERS; + } } diff --git a/src/main/java/me/clip/placeholderapi/events/ExpansionsLoadedEvent.java b/spigot/src/main/java/me/clip/placeholderapi/events/ExpansionsLoadedEvent.java similarity index 96% rename from src/main/java/me/clip/placeholderapi/events/ExpansionsLoadedEvent.java rename to spigot/src/main/java/me/clip/placeholderapi/events/ExpansionsLoadedEvent.java index 872d275..6b60e25 100644 --- a/src/main/java/me/clip/placeholderapi/events/ExpansionsLoadedEvent.java +++ b/spigot/src/main/java/me/clip/placeholderapi/events/ExpansionsLoadedEvent.java @@ -23,6 +23,7 @@ package me.clip.placeholderapi.events; import java.util.Collections; import java.util.List; + import me.clip.placeholderapi.expansion.PlaceholderExpansion; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; @@ -32,14 +33,14 @@ import org.jetbrains.annotations.NotNull; * This event indicated that all {@link PlaceholderExpansion PlaceholderExpansions} have * been registered in PlaceholderAPI and can now be used. *
This even will also be triggered whenever PlaceholderAPI gets reloaded. - * + * *

All PlaceholderExpansions, except for those loaded by plugins, are loaded * after Spigot triggered its ServerLoadEvent (1.13+), or after PlaceholderAPI has been enabled. */ public class ExpansionsLoadedEvent extends Event { - + private final List expansions; - + public ExpansionsLoadedEvent(List expansions) { this.expansions = Collections.unmodifiableList(expansions); } @@ -47,16 +48,16 @@ public class ExpansionsLoadedEvent extends Event { /** * Returns a unmodifiable list of {@link PlaceholderExpansion PlaceholderExpansions} that * have been registered by PlaceholderAPI. - * + * *

This list does not include manually registered PlaceholderExpansions. - * + * * @return List of {@link PlaceholderExpansion registered PlaceholderExpansions}. */ @NotNull - public final List getExpansions(){ + public final List getExpansions() { return expansions; } - + @NotNull private static final HandlerList HANDLERS = new HandlerList(); diff --git a/src/main/java/me/clip/placeholderapi/events/PlaceholderHookUnloadEvent.java b/spigot/src/main/java/me/clip/placeholderapi/events/PlaceholderHookUnloadEvent.java similarity index 58% rename from src/main/java/me/clip/placeholderapi/events/PlaceholderHookUnloadEvent.java rename to spigot/src/main/java/me/clip/placeholderapi/events/PlaceholderHookUnloadEvent.java index e0a8ce5..9d9a888 100644 --- a/src/main/java/me/clip/placeholderapi/events/PlaceholderHookUnloadEvent.java +++ b/spigot/src/main/java/me/clip/placeholderapi/events/PlaceholderHookUnloadEvent.java @@ -31,40 +31,40 @@ import org.jetbrains.annotations.NotNull; @Deprecated public final class PlaceholderHookUnloadEvent extends Event { - @NotNull - private static final HandlerList HANDLERS = new HandlerList(); + @NotNull + private static final HandlerList HANDLERS = new HandlerList(); - @NotNull - private final String plugin; - @NotNull - private final PlaceholderHook placeholderHook; + @NotNull + private final String plugin; + @NotNull + private final PlaceholderHook placeholderHook; - public PlaceholderHookUnloadEvent(@NotNull final String plugin, - @NotNull final PlaceholderHook placeholderHook) { - this.plugin = plugin; - this.placeholderHook = placeholderHook; - } + public PlaceholderHookUnloadEvent(@NotNull final String plugin, + @NotNull final PlaceholderHook placeholderHook) { + this.plugin = plugin; + this.placeholderHook = placeholderHook; + } - @NotNull - public static HandlerList getHandlerList() { - return HANDLERS; - } + @NotNull + public static HandlerList getHandlerList() { + return HANDLERS; + } - @NotNull - public String getHookName() { - return plugin; - } + @NotNull + public String getHookName() { + return plugin; + } - @NotNull - public PlaceholderHook getHook() { - return placeholderHook; - } + @NotNull + public PlaceholderHook getHook() { + return placeholderHook; + } - @NotNull - @Override - public HandlerList getHandlers() { - return HANDLERS; - } + @NotNull + @Override + public HandlerList getHandlers() { + return HANDLERS; + } } diff --git a/src/main/java/me/clip/placeholderapi/exceptions/NoDefaultCommandException.java b/spigot/src/main/java/me/clip/placeholderapi/exceptions/NoDefaultCommandException.java similarity index 90% rename from src/main/java/me/clip/placeholderapi/exceptions/NoDefaultCommandException.java rename to spigot/src/main/java/me/clip/placeholderapi/exceptions/NoDefaultCommandException.java index 99c9602..b981f06 100644 --- a/src/main/java/me/clip/placeholderapi/exceptions/NoDefaultCommandException.java +++ b/spigot/src/main/java/me/clip/placeholderapi/exceptions/NoDefaultCommandException.java @@ -22,8 +22,8 @@ package me.clip.placeholderapi.exceptions; public final class NoDefaultCommandException extends RuntimeException { - public NoDefaultCommandException(final String message) { - super(message); - } + public NoDefaultCommandException(final String message) { + super(message); + } } diff --git a/src/main/java/me/clip/placeholderapi/expansion/Cacheable.java b/spigot/src/main/java/me/clip/placeholderapi/expansion/Cacheable.java similarity index 91% rename from src/main/java/me/clip/placeholderapi/expansion/Cacheable.java rename to spigot/src/main/java/me/clip/placeholderapi/expansion/Cacheable.java index a12a595..4ba19ed 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/Cacheable.java +++ b/spigot/src/main/java/me/clip/placeholderapi/expansion/Cacheable.java @@ -24,15 +24,15 @@ package me.clip.placeholderapi.expansion; * Classes implementing this interface will have a {@link #clear() clear void} that is called * by PlaceholderAPI whenever the {@link me.clip.placeholderapi.expansion.PlaceholderExpansion PlaceholderExpansion} * is unregistered. - * + * *

This allows you to execute things such as clearing internal caches, saving data to files, etc. * * @author Ryan McCarthy */ public interface Cacheable { - /** - * Called when the implementing class is unregistered from PlaceholderAPI - */ - void clear(); + /** + * Called when the implementing class is unregistered from PlaceholderAPI + */ + void clear(); } diff --git a/src/main/java/me/clip/placeholderapi/expansion/Cleanable.java b/spigot/src/main/java/me/clip/placeholderapi/expansion/Cleanable.java similarity index 88% rename from src/main/java/me/clip/placeholderapi/expansion/Cleanable.java rename to spigot/src/main/java/me/clip/placeholderapi/expansion/Cleanable.java index ae14598..71a8898 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/Cleanable.java +++ b/spigot/src/main/java/me/clip/placeholderapi/expansion/Cleanable.java @@ -25,7 +25,7 @@ import org.bukkit.entity.Player; /** * Classes implementing this interface will have a {@link #cleanup(Player) cleanup void} that is * called by PlaceholderAPI whenever a Player leaves the server. - * + * *

This can be useful for cases where you keep data of the player in a cache or similar * and want to free up space whenever they leave. * @@ -33,10 +33,10 @@ import org.bukkit.entity.Player; */ public interface Cleanable { - /** - * Called when a player leaves the server - * - * @param p (@link Player} who left the server - */ - void cleanup(Player p); + /** + * Called when a player leaves the server + * + * @param p (@link Player} who left the server + */ + void cleanup(Player p); } diff --git a/src/main/java/me/clip/placeholderapi/expansion/Configurable.java b/spigot/src/main/java/me/clip/placeholderapi/expansion/Configurable.java similarity index 74% rename from src/main/java/me/clip/placeholderapi/expansion/Configurable.java rename to spigot/src/main/java/me/clip/placeholderapi/expansion/Configurable.java index 8b2558e..761f07f 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/Configurable.java +++ b/spigot/src/main/java/me/clip/placeholderapi/expansion/Configurable.java @@ -26,32 +26,32 @@ import java.util.Map; * Implementing this interface allows {@link me.clip.placeholderapi.expansion.PlaceholderExpansion PlaceholderExpansions} * to set a list of default configuration values through the {@link #getDefaults() getDefaults method} * that should be added to the config.yml of PlaceholderAPI. - * + * *

The entries will be added under {@code expansions} as their own section. *

Example:

* returning a Map with key {@code foo} and value {@code bar} will result in the following config entry: - * + * *

  * expansions:
  *   myexpansion:
  *     foo: "bar"
  * 
- * + * *

The configuration is set before the PlaceholderExpansion is registered! * * @author Ryan McCarthy */ public interface Configurable { - /** - * The map returned by this method will be used to set config options in PlaceholderAPI's config.yml. - * - *

The key and value pairs are set under a section named after your - * {@link me.clip.placeholderapi.expansion.PlaceholderExpansion PlaceholderExpansion} in the - * {@code expansions} section of the config. - * - * @return Map of config path / values which need to be added / removed from the PlaceholderAPI - * config.yml file - */ - Map getDefaults(); + /** + * The map returned by this method will be used to set config options in PlaceholderAPI's config.yml. + * + *

The key and value pairs are set under a section named after your + * {@link me.clip.placeholderapi.expansion.PlaceholderExpansion PlaceholderExpansion} in the + * {@code expansions} section of the config. + * + * @return Map of config path / values which need to be added / removed from the PlaceholderAPI + * config.yml file + */ + Map getDefaults(); } diff --git a/spigot/src/main/java/me/clip/placeholderapi/expansion/NMSVersion.java b/spigot/src/main/java/me/clip/placeholderapi/expansion/NMSVersion.java new file mode 100644 index 0000000..78ce23a --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/expansion/NMSVersion.java @@ -0,0 +1,81 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.expansion; + +public enum NMSVersion { + + UNKNOWN("unknown"), + SPIGOT_1_7_R1("v1_7_R1"), + SPIGOT_1_7_R2("v1_7_R2"), + SPIGOT_1_7_R3("v1_7_R3"), + SPIGOT_1_7_R4("v1_7_R4"), + SPIGOT_1_8_R1("v1_8_R1"), + SPIGOT_1_8_R2("v1_8_R2"), + SPIGOT_1_8_R3("v1_8_R3"), + SPIGOT_1_9_R1("v1_9_R1"), + SPIGOT_1_9_R2("v1_9_R2"), + SPIGOT_1_10_R1("v1_10_R1"), + SPIGOT_1_11_R1("v1_11_R1"), + SPIGOT_1_12_R1("v1_12_R1"), + SPIGOT_1_13_R1("v1_13_R1"), + SPIGOT_1_13_R2("v1_13_R2"), + SPIGOT_1_14_R1("v1_14_R1"), + SPIGOT_1_15_R1("v1_15_R1"), + SPIGOT_1_16_R1("v1_16_R1"), + SPIGOT_1_16_R2("v1_16_R2"), + SPIGOT_1_16_R3("v1_16_R3"), + SPIGOT_1_17_R1("v1_17_R1"), + SPIGOT_1_18_R1("v1_18_R1"), + SPIGOT_1_19_R1("v1_19_R1"), + SPIGOT_1_19_R2("v1_19_R2"), + SPIGOT_1_19_R3("v1_19_R3"), + SPIGOT_1_20_R1("v1_20_R1"), + SPIGOT_1_20_R2("v1_20_R2"), + SPIGOT_1_20_R3("v1_20_R3"), + SPIGOT_1_20_R4("v1_20_R4"), + SPIGOT_1_21_R1("v1_21_R1"), + SPIGOT_1_21_R2("V1_21_R2"), + SPIGOT_1_21_R3("V1_21_R3"), + SPIGOT_1_21_R4("V1_21_R4"), + SPIGOT_1_21_R5("V1_21_R5"), + SPIGOT_1_21_R6("V1_21_R6"); + + private final String version; + + NMSVersion(String version) { + this.version = version; + } + + public static NMSVersion getVersion(String version) { + for (NMSVersion v : values()) { + if (v.getVersion().equalsIgnoreCase(version)) { + return v; + } + } + + return NMSVersion.UNKNOWN; + } + + public String getVersion() { + return version; + } + +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/expansion/PlaceholderExpansion.java b/spigot/src/main/java/me/clip/placeholderapi/expansion/PlaceholderExpansion.java new file mode 100644 index 0000000..d3b042a --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/expansion/PlaceholderExpansion.java @@ -0,0 +1,479 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.expansion; + +import java.util.Collections; +import java.util.List; +import java.util.logging.Level; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.PlaceholderHook; +import org.bukkit.Bukkit; +import org.bukkit.configuration.ConfigurationSection; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.Contract; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +/** + * Any class extending this will be able to get registered as a PlaceholderExpansion. + *
The registration either happens automatically when the jar file containing a + * class extending this one is located under the {@code PlaceholderAPI/expansions} + * directory or when the {@link #register()} method is called by said class. + */ +public abstract class PlaceholderExpansion extends PlaceholderHook { + + /** + * The type is {@link Type#INTERNAL} by default. + * For external expansions, the type is updated on {@link me.clip.placeholderapi.expansion.manager.LocalExpansionManager#register(Class) register}. + * + * @since 2.11.4 + */ + @ApiStatus.Internal + protected Type expansionType = Type.INTERNAL; + + /** + * The placeholder identifier of this expansion. May not contain {@literal %}, + * {@literal {}} or _ + * + * @return placeholder identifier that is associated with this expansion + */ + @NotNull + public abstract String getIdentifier(); + + /** + * The author of this expansion + * + * @return name of the author for this expansion + */ + @NotNull + public abstract String getAuthor(); + + /** + * The version of this expansion + * + * @return current version of this expansion + */ + @NotNull + public abstract String getVersion(); + + /** + * The name of this expansion + * + * @return {@link #getIdentifier()} by default, name of this expansion if specified + */ + @NotNull + public String getName() { + return getIdentifier(); + } + + /** + * The name of the plugin that this expansion hooks into. by default will null + * + * @return plugin name that this expansion requires to function + */ + @Nullable + public String getRequiredPlugin() { + return getPlugin(); + } + + /** + * The placeholders associated with this expansion + * + * @return placeholder list that this expansion provides + */ + @NotNull + public List getPlaceholders() { + return Collections.emptyList(); + } + + + /** + * Expansions that do not use the ecloud and instead register from the dependency should set this + * to true to ensure that your placeholder expansion is not unregistered when the papi reload + * command is used + * + * @return if this expansion should persist through placeholder reloads + */ + public boolean persist() { + return false; + } + + + /** + * Check if this placeholder identifier has already been registered + * + * @return true if the identifier for this expansion is already registered + */ + public final boolean isRegistered() { + return getPlaceholderAPI().getLocalExpansionManager().findExpansionByIdentifier(getIdentifier()) + .map(it -> it.equals(this)).orElse(false); + } + + + /** + * If any requirements need to be checked before this expansion should register, you can check + * them here + * + * @return true if this hook meets all the requirements to register + */ + public boolean canRegister() { + return getRequiredPlugin() == null + || Bukkit.getPluginManager().getPlugin(getRequiredPlugin()) != null; + } + + /** + * Attempt to register this PlaceholderExpansion + * + * @return true if this expansion is now registered with PlaceholderAPI + */ + public boolean register() { + return getPlaceholderAPI().getLocalExpansionManager().register(this); + } + + /** + * Attempt to unregister this PlaceholderExpansion + * + * @return true if this expansion is now unregistered with PlaceholderAPI + */ + public final boolean unregister() { + return getPlaceholderAPI().getLocalExpansionManager().unregister(this); + } + + + /** + * Quick getter for the {@link PlaceholderAPIPlugin} instance + * + * @return {@link PlaceholderAPIPlugin} instance + */ + @NotNull + public final PlaceholderAPIPlugin getPlaceholderAPI() { + return PlaceholderAPIPlugin.getInstance(); + } + + /** + * Get the type of the expansion + * + * @return the type of the expansion + * @since 2.11.4 + */ + @ApiStatus.Internal + public Type getExpansionType() { + return expansionType; + } + + /** + * Set the type of the expansion + * + * @param expansionType the new type + * @since 2.11.4 + */ + @ApiStatus.Internal + public void setExpansionType(Type expansionType) { + this.expansionType = expansionType; + } + + // === Configuration === + + /** + * Gets the ConfigurationSection of the expansion located in the config.yml of PlaceholderAPI or + * null when not specified. + *
You may use the {@link Configurable} interface to define default values set + * + * @return ConfigurationSection that this expansion has. + */ + @Nullable + public final ConfigurationSection getConfigSection() { + return getPlaceholderAPI().getConfig().getConfigurationSection("expansions." + getIdentifier()); + } + + /** + * Gets the ConfigurationSection relative to the {@link #getConfigSection() default one} set + * by the expansion or null when the default ConfigurationSection is null + * + * @param path The path to get the ConfigurationSection from. This is relative to the default section + * @return ConfigurationSection relative to the default section + */ + @Nullable + public final ConfigurationSection getConfigSection(@NotNull final String path) { + final ConfigurationSection section = getConfigSection(); + return section == null ? null : section.getConfigurationSection(path); + } + + /** + * Gets the Object relative to the {@link #getConfigSection() default ConfigurationSection} set + * by the expansion or the provided Default Object, when the default ConfigurationSection is null + * + * @param path The path to get the Object from. This is relative to the default section + * @param def The default Object to return when the ConfigurationSection returns null + * @return Object from the provided path or the default one provided + */ + @Nullable + @Contract("_, !null -> !null") + public final Object get(@NotNull final String path, final Object def) { + final ConfigurationSection section = getConfigSection(); + return section == null ? def : section.get(path, def); + } + + /** + * Gets the int relative to the {@link #getConfigSection() default ConfigurationSection} set + * by the expansion or the provided Default int, when the default ConfigurationSection is null + * + * @param path The path to get the int from. This is relative to the default section + * @param def The default int to return when the ConfigurationSection returns null + * @return int from the provided path or the default one provided + */ + public final int getInt(@NotNull final String path, final int def) { + final ConfigurationSection section = getConfigSection(); + return section == null ? def : section.getInt(path, def); + } + + /** + * Gets the long relative to the {@link #getConfigSection() default ConfigurationSection} set + * by the expansion or the provided Default long, when the default ConfigurationSection is null + * + * @param path The path to get the long from. This is relative to the default section + * @param def The default long to return when the ConfigurationSection returns null + * @return long from the provided path or the default one provided + */ + public final long getLong(@NotNull final String path, final long def) { + final ConfigurationSection section = getConfigSection(); + return section == null ? def : section.getLong(path, def); + } + + /** + * Gets the double relative to the {@link #getConfigSection() default ConfigurationSection} set + * by the expansion or the provided Default double, when the default ConfigurationSection is null + * + * @param path The path to get the double from. This is relative to the default section + * @param def The default double to return when the ConfigurationSection returns null + * @return double from the provided path or the default one provided + */ + public final double getDouble(@NotNull final String path, final double def) { + final ConfigurationSection section = getConfigSection(); + return section == null ? def : section.getDouble(path, def); + } + + /** + * Gets the String relative to the {@link #getConfigSection() default ConfigurationSection} set + * by the expansion or the provided Default String, when the default ConfigurationSection is null + * + * @param path The path to get the String from. This is relative to the default section + * @param def The default String to return when the ConfigurationSection returns null. Can be null + * @return String from the provided path or the default one provided + */ + @Nullable + @Contract("_, !null -> !null") + public final String getString(@NotNull final String path, @Nullable final String def) { + final ConfigurationSection section = getConfigSection(); + return section == null ? def : section.getString(path, def); + } + + /** + * Gets a String List relative to the {@link #getConfigSection() default ConfigurationSection} set + * by the expansion or an empty List, when the default ConfigurationSection is null + * + * @param path The path to get the String list from. This is relative to the default section + * @return String list from the provided path or an empty list + */ + @NotNull + public final List getStringList(@NotNull final String path) { + final ConfigurationSection section = getConfigSection(); + return section == null ? Collections.emptyList() : section.getStringList(path); + } + + /** + * Gets the boolean relative to the {@link #getConfigSection() default ConfigurationSection} set + * by the expansion or the default boolean, when the default ConfigurationSection is null + * + * @param path The path to get the boolean from. This is relative to the default section + * @param def The default boolean to return when the ConfigurationSection is null + * @return boolean from the provided path or the default one provided + */ + public final boolean getBoolean(@NotNull final String path, final boolean def) { + final ConfigurationSection section = getConfigSection(); + return section == null ? def : section.getBoolean(path, def); + } + + /** + * Whether the {@link #getConfigSection() default ConfigurationSection} contains the provided path + * or not. This will return {@code false} when either the default section is null, or doesn't + * contain the provided path + * + * @param path The path to check + * @return true when the default ConfigurationSection is not null and contains the path, false otherwise + */ + public final boolean configurationContains(@NotNull final String path) { + final ConfigurationSection section = getConfigSection(); + return section != null && section.contains(path); + } + + /** + * Logs the provided message with the provided Level in the console. + *
The message will be prefixed with {@link #getName() [<expansion name>]} + * + * @param level The Level at which the message should be logged with + * @param msg The message to log + */ + public void log(Level level, String msg) { + getPlaceholderAPI().getLogger().log(level, "[" + getName() + "] " + msg); + } + + /** + * Logs the provided message and Throwable with the provided Level in the console. + *
The message will be prefixed with {@link #getName() [<expansion name>]} + * + * @param level The Level at which the message should be logged with + * @param msg The message to log + * @param throwable The Throwable to log + */ + public void log(Level level, String msg, Throwable throwable) { + getPlaceholderAPI().getLogger().log(level, "[" + getName() + "] " + msg, throwable); + } + + /** + * Logs the provided message with Level "info". + *
The message will be prefixed with {@link #getName() [<expansion name>]} + * + * @param msg The message to log + */ + public void info(String msg) { + log(Level.INFO, msg); + } + + /** + * Logs the provided message with Level "warning". + *
The message will be prefixed with {@link #getName() [<expansion name>]} + * + * @param msg The message to log + */ + public void warning(String msg) { + log(Level.WARNING, msg); + } + + /** + * Logs the provided message with Level "severe" (error). + *
The message will be prefixed with {@link #getName() [<expansion name>]} + * + * @param msg The message to log + */ + public void severe(String msg) { + log(Level.SEVERE, msg); + } + + /** + * Logs the provided message and Throwable with Level "severe" (error). + *
The message will be prefixed with {@link #getName() [<expansion name>]} + * + * @param msg The message to log + * @param throwable The Throwable to log + */ + public void severe(String msg, Throwable throwable) { + log(Level.SEVERE, msg, throwable); + } + + + /** + * Whether the provided Object is an instance of this PlaceholderExpansion. + *
This method will perform the following checks in order: + *

    + *
  • Checks if Object equals the class. Returns true when equal and continues otherwise
  • + *
  • Checks if the Object is an instance of a PlaceholderExpansion. Returns false if not
  • + *
  • Checks if the Object's Identifier, Author and version equal the one of this class
  • + *
+ * + * @param o The Object to check + * @return true or false depending on the above mentioned checks + */ + @Override + public final boolean equals(final Object o) { + if (this == o) { + return true; + } + if (!(o instanceof PlaceholderExpansion)) { + return false; + } + + final PlaceholderExpansion expansion = (PlaceholderExpansion) o; + + return getIdentifier().equals(expansion.getIdentifier()) && + getAuthor().equals(expansion.getAuthor()) && + getVersion().equals(expansion.getVersion()); + } + + /** + * Returns a String containing the Expansion's name, author and version + * + * @return String containing name, author and version of the expansion + */ + @Override + public final String toString() { + return String.format("PlaceholderExpansion[name: '%s', author: '%s', version: '%s', type: '%s']", getName(), + getAuthor(), getVersion(), getExpansionType()); + } + + // === Deprecated API === + + /** + * @return The plugin name. + * @deprecated As of versions greater than 2.8.7, use {@link #getRequiredPlugin()} + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public String getPlugin() { + return null; + } + + /** + * @return The description of the expansion. + * @deprecated As of versions greater than 2.8.7, use the expansion cloud to show a description + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public String getDescription() { + return null; + } + + /** + * @return The link for the expansion. + * @deprecated As of versions greater than 2.8.7, use the expansion cloud to display a link + */ + @Deprecated + @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") + public String getLink() { + return null; + } + + public enum Type { + + /** + * An expansion provided by a plugin is considered internal + */ + INTERNAL, + + /** + * An expansion loaded from the expansions folder is considered external + */ + EXTERNAL + + } + +} diff --git a/src/main/java/me/clip/placeholderapi/expansion/Relational.java b/spigot/src/main/java/me/clip/placeholderapi/expansion/Relational.java similarity index 71% rename from src/main/java/me/clip/placeholderapi/expansion/Relational.java rename to spigot/src/main/java/me/clip/placeholderapi/expansion/Relational.java index 4b7c7d4..e1996b0 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/Relational.java +++ b/spigot/src/main/java/me/clip/placeholderapi/expansion/Relational.java @@ -25,19 +25,19 @@ import org.bukkit.entity.Player; /** * Implementing this interface allows your {@link me.clip.placeholderapi.expansion.PlaceholderExpansion PlaceholderExpansion} * to be used as a relational placeholder expansion. - * + * *

Relational placeholders take two Players as input and are always prefixed with {@code rel_}, * so {@code %foo_bar%} becomes {@code %rel_foo_bar%} */ public interface Relational { - /** - * This method is called whenever a placeholder starting with {@code rel_} is called. - * - * @param one The first player used for the placeholder. - * @param two The second player used for the placeholder. - * @param identifier The text right after the expansion's name (%expansion_identifier%) - * @return Parsed String from the expansion. - */ - String onPlaceholderRequest(Player one, Player two, String identifier); + /** + * This method is called whenever a placeholder starting with {@code rel_} is called. + * + * @param one The first player used for the placeholder. + * @param two The second player used for the placeholder. + * @param identifier The text right after the expansion's name (%expansion_identifier%) + * @return Parsed String from the expansion. + */ + String onPlaceholderRequest(Player one, Player two, String identifier); } diff --git a/src/main/java/me/clip/placeholderapi/expansion/Taskable.java b/spigot/src/main/java/me/clip/placeholderapi/expansion/Taskable.java similarity index 72% rename from src/main/java/me/clip/placeholderapi/expansion/Taskable.java rename to spigot/src/main/java/me/clip/placeholderapi/expansion/Taskable.java index b4bea67..7d92147 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/Taskable.java +++ b/spigot/src/main/java/me/clip/placeholderapi/expansion/Taskable.java @@ -23,21 +23,21 @@ package me.clip.placeholderapi.expansion; /** * Implementing this interface adds the {@link #start() start} and {@link #stop() stop} void * methods to your {@link me.clip.placeholderapi.expansion.PlaceholderExpansion PlaceholderExpansion}. - * + * *

This can be used to execute methods and tasks whenever the PlaceholderExpansion has been * successfully (un)registered. */ public interface Taskable { - /** - * Called when the implementing class has successfully been registered to the placeholder map. - *
Tasks that need to be performed when this expansion is registered should go here - */ - void start(); + /** + * Called when the implementing class has successfully been registered to the placeholder map. + *
Tasks that need to be performed when this expansion is registered should go here + */ + void start(); - /** - * Called when the implementing class has been unregistered from PlaceholderAPI. - *
Tasks that need to be performed when this expansion has unregistered should go here - */ - void stop(); + /** + * Called when the implementing class has been unregistered from PlaceholderAPI. + *
Tasks that need to be performed when this expansion has unregistered should go here + */ + void stop(); } diff --git a/src/main/java/me/clip/placeholderapi/expansion/Version.java b/spigot/src/main/java/me/clip/placeholderapi/expansion/Version.java similarity index 65% rename from src/main/java/me/clip/placeholderapi/expansion/Version.java rename to spigot/src/main/java/me/clip/placeholderapi/expansion/Version.java index d9ac195..fa1d15d 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/Version.java +++ b/spigot/src/main/java/me/clip/placeholderapi/expansion/Version.java @@ -23,24 +23,24 @@ package me.clip.placeholderapi.expansion; @Deprecated public final class Version { - private final boolean isSpigot; - private final String version; + private final boolean isSpigot; + private final String version; - public Version(String version, boolean isSpigot) { - this.version = version; - this.isSpigot = isSpigot; - } + public Version(String version, boolean isSpigot) { + this.version = version; + this.isSpigot = isSpigot; + } - public String getVersion() { - return version == null ? "unknown" : version; - } + public String getVersion() { + return version == null ? "unknown" : version; + } - public boolean isSpigot() { - return isSpigot; - } + public boolean isSpigot() { + return isSpigot; + } - public boolean compareTo(String version) { - return getVersion().equalsIgnoreCase(version); - } + public boolean compareTo(String version) { + return getVersion().equalsIgnoreCase(version); + } } diff --git a/src/main/java/me/clip/placeholderapi/expansion/VersionSpecific.java b/spigot/src/main/java/me/clip/placeholderapi/expansion/VersionSpecific.java similarity index 75% rename from src/main/java/me/clip/placeholderapi/expansion/VersionSpecific.java rename to spigot/src/main/java/me/clip/placeholderapi/expansion/VersionSpecific.java index 51080cc..bd108f3 100644 --- a/src/main/java/me/clip/placeholderapi/expansion/VersionSpecific.java +++ b/spigot/src/main/java/me/clip/placeholderapi/expansion/VersionSpecific.java @@ -27,19 +27,17 @@ package me.clip.placeholderapi.expansion; * with that version. * * @author Ryan McCarthy - * * @deprecated Will be removed in a future release. */ @Deprecated public interface VersionSpecific { - /** - * This method is called before the expansion is attempted to be registered The server version - * will be passed to this method so you know what version the server is currently running. - * - * @param v The {@link Version} to check against - * - * @return true if your expansion is compatible with the version the server is running. - */ - boolean isCompatibleWith(Version v); + /** + * This method is called before the expansion is attempted to be registered The server version + * will be passed to this method so you know what version the server is currently running. + * + * @param v The {@link Version} to check against + * @return true if your expansion is compatible with the version the server is running. + */ + boolean isCompatibleWith(Version v); } diff --git a/spigot/src/main/java/me/clip/placeholderapi/expansion/cloud/CloudExpansion.java b/spigot/src/main/java/me/clip/placeholderapi/expansion/cloud/CloudExpansion.java new file mode 100644 index 0000000..027c776 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/expansion/cloud/CloudExpansion.java @@ -0,0 +1,207 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.expansion.cloud; + +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import me.clip.placeholderapi.util.TimeUtil; + + +public class CloudExpansion { + + private String name, + author, + latest_version, + description, + source_url, + dependency_url; + + private boolean hasExpansion, + shouldUpdate; + + private long last_update, + ratings_count; + + private double average_rating; + + private List placeholders; + + private List versions; + + public CloudExpansion() { + } + + public String getTimeSinceLastUpdate() { + int time = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - getLastUpdate()); + return TimeUtil.getTime(time); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getAuthor() { + return author; + } + + public void setAuthor(String author) { + this.author = author; + } + + public Version getVersion() { + return getLatestVersion() == null ? null : getVersion(getLatestVersion()); + } + + public Version getVersion(String version) { + return versions == null ? null : versions.stream() + .filter(v -> v.getVersion().equals(version)) + .findFirst() + .orElse(null); + } + + public List getAvailableVersions() { + return versions.stream().map(Version::getVersion).collect(Collectors.toList()); + } + + public String getLatestVersion() { + return latest_version; + } + + public void setLatestVersion(String latest_version) { + this.latest_version = latest_version; + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public String getSourceUrl() { + return source_url; + } + + public void setSourceUrl(String source_url) { + this.source_url = source_url; + } + + public String getDependencyUrl() { + return dependency_url; + } + + public void setDependencyUrl(String dependency_url) { + this.dependency_url = dependency_url; + } + + public boolean hasExpansion() { + return hasExpansion; + } + + public void setHasExpansion(boolean hasExpansion) { + this.hasExpansion = hasExpansion; + } + + public boolean shouldUpdate() { + return shouldUpdate; + } + + public void setShouldUpdate(boolean shouldUpdate) { + this.shouldUpdate = shouldUpdate; + } + + public long getLastUpdate() { + return last_update; + } + + public void setLastUpdate(long last_update) { + this.last_update = last_update; + } + + public long getRatingsCount() { + return ratings_count; + } + + public double getAverage_rating() { + return average_rating; + } + + public List getPlaceholders() { + return placeholders; + } + + public void setPlaceholders(List placeholders) { + this.placeholders = placeholders; + } + + public List getVersions() { + return versions; + } + + public void setVersions(List versions) { + this.versions = versions; + } + + public static class Version { + + private String url, version, release_notes; + private boolean verified; + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getReleaseNotes() { + return release_notes; + } + + public void setReleaseNotes(String release_notes) { + this.release_notes = release_notes; + } + + public boolean isVerified() { + return verified; + } + + public void setVerified(boolean verified) { + this.verified = verified; + } + } +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/expansion/manager/CloudExpansionManager.java b/spigot/src/main/java/me/clip/placeholderapi/expansion/manager/CloudExpansionManager.java new file mode 100644 index 0000000..15f603c --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/expansion/manager/CloudExpansionManager.java @@ -0,0 +1,278 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.expansion.manager; + +import com.google.common.collect.ImmutableMap; +import com.google.common.io.Resources; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.lang.reflect.Type; +import java.net.URL; +import java.nio.channels.Channels; +import java.nio.channels.ReadableByteChannel; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Function; +import java.util.logging.Level; +import java.util.stream.Collector; +import java.util.stream.Collectors; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.expansion.cloud.CloudExpansion; +import me.clip.placeholderapi.util.Msg; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Unmodifiable; + +public final class CloudExpansionManager { + + @NotNull + private static final String API_URL = "https://ecloud.placeholderapi.com/api/v3/"; + + @NotNull + private static final Gson GSON = new Gson(); + @NotNull + private static final Type TYPE = new TypeToken>() {}.getType(); + + @NotNull + private final Collector> INDEXED_NAME_COLLECTOR = Collectors + .toMap(CloudExpansionManager::toIndexName, Function.identity()); + + + @NotNull + private final PlaceholderAPIPlugin plugin; + + @NotNull + private final Map cache = new HashMap<>(); + @NotNull + private final Map> await = new ConcurrentHashMap<>(); + + private final ExecutorService ASYNC_EXECUTOR = + Executors.newCachedThreadPool( + new ThreadFactoryBuilder().setNameFormat("placeholderapi-io-#%1$d").build()); + + public CloudExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) { + this.plugin = plugin; + } + + @NotNull + private static String toIndexName(@NotNull final String name) { + return name.toLowerCase(Locale.ROOT).replace(' ', '_'); + } + + @NotNull + private static String toIndexName(@NotNull final CloudExpansion expansion) { + return toIndexName(expansion.getName()); + } + + public void load() { + clean(); + fetch(); + } + + public void kill() { + clean(); + } + + @NotNull + @Unmodifiable + public Map getCloudExpansions() { + return ImmutableMap.copyOf(cache); + } + + @NotNull + @Unmodifiable + public Map getCloudExpansionsInstalled() { + if (cache.isEmpty()) { + return Collections.emptyMap(); + } + + return cache.values() + .stream() + .filter(CloudExpansion::hasExpansion) + .collect(INDEXED_NAME_COLLECTOR); + } + + @NotNull + @Unmodifiable + public Map getCloudExpansionsByAuthor(@NotNull final String author) { + if (cache.isEmpty()) { + return Collections.emptyMap(); + } + + return cache.values() + .stream() + .filter(expansion -> author.equalsIgnoreCase(expansion.getAuthor())) + .collect(INDEXED_NAME_COLLECTOR); + } + + @NotNull + @Unmodifiable + public Set getCloudExpansionAuthors() { + return cache.values().stream().map(CloudExpansion::getAuthor).collect(Collectors.toSet()); + } + + public int getCloudExpansionAuthorCount() { + return getCloudExpansionAuthors().size(); + } + + public int getCloudUpdateCount() { + return ((int) plugin.getLocalExpansionManager() + .getExpansions() + .stream() + .filter(expansion -> findCloudExpansionByName(expansion.getName()) + .map(CloudExpansion::shouldUpdate).orElse(false)) + .count()); + } + + @NotNull + public Optional findCloudExpansionByName(@NotNull final String name) { + return Optional.ofNullable(cache.get(toIndexName(name))); + } + + public void clean() { + cache.clear(); + + await.values().forEach(future -> future.cancel(true)); + await.clear(); + } + + public void fetch() { + plugin.getLogger().info("Fetching available expansion information..."); + + ASYNC_EXECUTOR.submit( + () -> { + // a defence tactic! use ConcurrentHashMap instead of normal HashMap + Map values = new ConcurrentHashMap<>(); + try { + //noinspection UnstableApiUsage + String json = Resources.toString(new URL(API_URL), StandardCharsets.UTF_8); + values.putAll(GSON.fromJson(json, TYPE)); + + List toRemove = new ArrayList<>(); + + for (Map.Entry entry : values.entrySet()) { + CloudExpansion expansion = entry.getValue(); + if (expansion.getLatestVersion() == null + || expansion.getVersion(expansion.getLatestVersion()) == null) { + toRemove.add(entry.getKey()); + } + } + + for (String name : toRemove) { + values.remove(name); + } + } catch (Throwable e) { + // ugly swallowing of every throwable, but we have to be defensive + plugin.getLogger().log(Level.WARNING, "Failed to download expansion information", e); + } + + // loop through what's left on the main thread + plugin + .getScheduler() + .runTask( + () -> { + try { + for (Map.Entry entry : values.entrySet()) { + String name = entry.getKey(); + CloudExpansion expansion = entry.getValue(); + + expansion.setName(name); + + Optional localOpt = + plugin.getLocalExpansionManager().findExpansionByName(name); + if (localOpt.isPresent()) { + PlaceholderExpansion local = localOpt.get(); + if (local.isRegistered()) { + expansion.setHasExpansion(true); + expansion.setShouldUpdate( + !local.getVersion().equalsIgnoreCase(expansion.getLatestVersion())); + } + } + + cache.put(toIndexName(expansion), expansion); + } + } catch (Throwable e) { + // ugly swallowing of every throwable, but we have to be defensive + plugin + .getLogger() + .log(Level.WARNING, "Failed to download expansion information", e); + } + }); + }); + } + + public boolean isDownloading(@NotNull final CloudExpansion expansion) { + return await.containsKey(toIndexName(expansion)); + } + + @NotNull + public CompletableFuture downloadExpansion(@NotNull final CloudExpansion expansion, + @NotNull final CloudExpansion.Version version) { + final CompletableFuture previous = await.get(toIndexName(expansion)); + if (previous != null) { + return previous; + } + + final File file = new File(plugin.getLocalExpansionManager().getExpansionsFolder(), + "Expansion-" + toIndexName(expansion) + ".jar"); + + final CompletableFuture download = CompletableFuture.supplyAsync(() -> { + try (final ReadableByteChannel source = Channels.newChannel(new URL(version.getUrl()) + .openStream()); final FileOutputStream target = new FileOutputStream(file)) { + target.getChannel().transferFrom(source, 0, Long.MAX_VALUE); + } catch (final IOException ex) { + throw new CompletionException(ex); + } + return file; + }, ASYNC_EXECUTOR); + + download.whenCompleteAsync((value, exception) -> { + await.remove(toIndexName(expansion)); + + if (exception != null) { + Msg.severe("Failed to download %s:%s", exception, expansion.getName(), expansion.getVersion()); + } + }, ASYNC_EXECUTOR); + + await.put(toIndexName(expansion), download); + + return download; + } + +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/expansion/manager/LocalExpansionManager.java b/spigot/src/main/java/me/clip/placeholderapi/expansion/manager/LocalExpansionManager.java new file mode 100644 index 0000000..f321a3e --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/expansion/manager/LocalExpansionManager.java @@ -0,0 +1,498 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.expansion.manager; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; + +import java.io.File; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Level; +import java.util.stream.Collectors; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.events.ExpansionRegisterEvent; +import me.clip.placeholderapi.events.ExpansionUnregisterEvent; +import me.clip.placeholderapi.events.ExpansionsLoadedEvent; +import me.clip.placeholderapi.expansion.Cacheable; +import me.clip.placeholderapi.expansion.Cleanable; +import me.clip.placeholderapi.expansion.Configurable; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.expansion.Taskable; +import me.clip.placeholderapi.expansion.VersionSpecific; +import me.clip.placeholderapi.expansion.cloud.CloudExpansion; +import me.clip.placeholderapi.util.FileUtil; +import me.clip.placeholderapi.util.Futures; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.event.server.PluginDisableEvent; +import org.jetbrains.annotations.ApiStatus; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.annotations.Unmodifiable; + +public final class LocalExpansionManager implements Listener { + + @NotNull + private static final String EXPANSIONS_FOLDER_NAME = "expansions"; + + @NotNull + private static final Set ABSTRACT_EXPANSION_METHODS = Arrays.stream(PlaceholderExpansion.class.getDeclaredMethods()) + .filter(method -> Modifier.isAbstract(method.getModifiers())) + .map(method -> new MethodSignature(method.getName(), method.getParameterTypes())) + .collect(Collectors.toSet()); + + @NotNull + private final File folder; + @NotNull + private final PlaceholderAPIPlugin plugin; + + @NotNull + private final Map expansions = new ConcurrentHashMap<>(); + private final ReentrantLock expansionsLock = new ReentrantLock(); + + + public LocalExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) { + this.plugin = plugin; + this.folder = new File(plugin.getDataFolder(), EXPANSIONS_FOLDER_NAME); + + if (!this.folder.exists() && !folder.mkdirs()) { + Msg.warn("Failed to create expansions folder!"); + } + } + + public void load(@NotNull final CommandSender sender) { + registerAll(sender); + } + + public void kill() { + unregisterAll(); + } + + + @NotNull + public File getExpansionsFolder() { + return folder; + } + + @NotNull + @Unmodifiable + public Collection getIdentifiers() { + expansionsLock.lock(); + try { + return ImmutableSet.copyOf(expansions.keySet()); + } finally { + expansionsLock.unlock(); + } + } + + @NotNull + @Unmodifiable + public Collection getExpansions() { + expansionsLock.lock(); + try { + return ImmutableSet.copyOf(expansions.values()); + } finally { + expansionsLock.unlock(); + } + } + + @Nullable + public PlaceholderExpansion getExpansion(@NotNull final String identifier) { + expansionsLock.lock(); + try { + return expansions.get(identifier.toLowerCase(Locale.ROOT)); + } finally { + expansionsLock.unlock(); + } + } + + @NotNull + public Optional findExpansionByName(@NotNull final String name) { + expansionsLock.lock(); + try { + PlaceholderExpansion bestMatch = null; + for (Map.Entry entry : expansions.entrySet()) { + PlaceholderExpansion expansion = entry.getValue(); + if (expansion.getName().equalsIgnoreCase(name)) { + bestMatch = expansion; + break; + } + } + return Optional.ofNullable(bestMatch); + } finally { + expansionsLock.unlock(); + } + } + + @NotNull + public Optional findExpansionByIdentifier( + @NotNull final String identifier) { + return Optional.ofNullable(getExpansion(identifier)); + } + + + public Optional register( + @NotNull final Class clazz) { + try { + final PlaceholderExpansion expansion = createExpansionInstance(clazz); + + if (expansion == null) { + return Optional.empty(); + } + + Objects.requireNonNull(expansion.getAuthor(), "The expansion author is null!"); + Objects.requireNonNull(expansion.getIdentifier(), "The expansion identifier is null!"); + Objects.requireNonNull(expansion.getVersion(), "The expansion version is null!"); + + if (expansion.getRequiredPlugin() != null && !expansion.getRequiredPlugin().isEmpty()) { + if (!Bukkit.getPluginManager().isPluginEnabled(expansion.getRequiredPlugin())) { + Msg.warn("Cannot load expansion %s due to a missing plugin: %s", expansion.getIdentifier(), + expansion.getRequiredPlugin()); + return Optional.empty(); + } + } + + expansion.setExpansionType(PlaceholderExpansion.Type.EXTERNAL); + + if (!expansion.register()) { + Msg.warn("Cannot load expansion %s due to an unknown issue.", expansion.getIdentifier()); + return Optional.empty(); + } + + return Optional.of(expansion); + } catch (LinkageError | NullPointerException ex) { + final String reason; + + if (ex instanceof LinkageError) { + reason = " (Is a dependency missing?)"; + } else { + reason = " - One of its properties is null which is not allowed!"; + } + + Msg.severe("Failed to load expansion class %s%s", ex, clazz.getSimpleName(), reason); + } + + return Optional.empty(); + } + + /** + * Attempt to register a {@link PlaceholderExpansion} + * + * @param expansion the expansion to register + * @return if the expansion was registered + */ + @ApiStatus.Internal + public boolean register(@NotNull final PlaceholderExpansion expansion) { + final String identifier = expansion.getIdentifier().toLowerCase(Locale.ROOT); + + if (!expansion.canRegister()) { + return false; + } + + // Avoid loading two external expansions with the same identifier + if (expansion.getExpansionType() == PlaceholderExpansion.Type.EXTERNAL && expansions.containsKey(identifier)) { + Msg.warn("Failed to load external expansion %s. Identifier is already in use.", expansion.getIdentifier()); + return false; + } + + if (expansion instanceof Configurable) { + Map defaults = ((Configurable) expansion).getDefaults(); + String pre = "expansions." + identifier + "."; + FileConfiguration cfg = plugin.getConfig(); + boolean save = false; + + if (defaults != null) { + for (Map.Entry entries : defaults.entrySet()) { + if (entries.getKey() == null || entries.getKey().isEmpty()) { + continue; + } + + if (entries.getValue() == null) { + if (cfg.contains(pre + entries.getKey())) { + save = true; + cfg.set(pre + entries.getKey(), null); + } + } else { + if (!cfg.contains(pre + entries.getKey())) { + save = true; + cfg.set(pre + entries.getKey(), entries.getValue()); + } + } + } + } + + if (save) { + plugin.saveConfig(); + plugin.reloadConfig(); + } + } + + if (expansion instanceof VersionSpecific) { + VersionSpecific nms = (VersionSpecific) expansion; + if (!nms.isCompatibleWith(PlaceholderAPIPlugin.getServerVersion())) { + Msg.warn("Your server version is incompatible with expansion %s %s", + expansion.getIdentifier(), expansion.getVersion()); + return false; + } + } + + final PlaceholderExpansion removed = getExpansion(identifier); + if (removed != null && !removed.unregister()) { + return false; + } + + final ExpansionRegisterEvent event = new ExpansionRegisterEvent(expansion); + Bukkit.getPluginManager().callEvent(event); + + if (event.isCancelled()) { + return false; + } + + expansionsLock.lock(); + try { + expansions.put(identifier, expansion); + } finally { + expansionsLock.unlock(); + } + + if (expansion instanceof Listener) { + Bukkit.getPluginManager().registerEvents(((Listener) expansion), plugin); + } + + Msg.info( + "Successfully registered %s expansion: %s [%s]", + expansion.getExpansionType().name().toLowerCase(), + expansion.getIdentifier(), + expansion.getVersion() + ); + + if (expansion instanceof Taskable) { + ((Taskable) expansion).start(); + } + + // Check eCloud for updates only if the expansion is external + if (plugin.getPlaceholderAPIConfig().isCloudEnabled() && expansion.getExpansionType() == PlaceholderExpansion.Type.EXTERNAL) { + final Optional cloudExpansionOptional = plugin.getCloudExpansionManager().findCloudExpansionByName(identifier); + if (cloudExpansionOptional.isPresent()) { + CloudExpansion cloudExpansion = cloudExpansionOptional.get(); + cloudExpansion.setHasExpansion(true); + cloudExpansion.setShouldUpdate(!cloudExpansion.getLatestVersion().equals(expansion.getVersion())); + } + } + + return true; + } + + @ApiStatus.Internal + public boolean unregister(@NotNull final PlaceholderExpansion expansion) { + if (expansions.remove(expansion.getIdentifier().toLowerCase(Locale.ROOT)) == null) { + return false; + } + + Bukkit.getPluginManager().callEvent(new ExpansionUnregisterEvent(expansion)); + + if (expansion instanceof Listener) { + HandlerList.unregisterAll((Listener) expansion); + } + + if (expansion instanceof Taskable) { + ((Taskable) expansion).stop(); + } + + if (expansion instanceof Cacheable) { + ((Cacheable) expansion).clear(); + } + + if (plugin.getPlaceholderAPIConfig().isCloudEnabled()) { + plugin.getCloudExpansionManager().findCloudExpansionByName(expansion.getName()) + .ifPresent(cloud -> { + cloud.setHasExpansion(false); + cloud.setShouldUpdate(false); + }); + } + + return true; + } + + private void registerAll(@NotNull final CommandSender sender) { + Msg.info("Placeholder expansion registration initializing..."); + + Futures.onMainThread(plugin, findExpansionsOnDisk(), (classes, exception) -> { + if (exception != null) { + Msg.severe("Failed to load class files of expansion.", exception); + return; + } + + final List registered = classes.stream() + .filter(Objects::nonNull) + .map(this::register) + .filter(Optional::isPresent) + .map(Optional::get) + .collect(Collectors.toList()); + + final long needsUpdate = registered.stream() + .map(expansion -> plugin.getCloudExpansionManager().findCloudExpansionByName(expansion.getName()).orElse(null)) + .filter(Objects::nonNull) + .filter(CloudExpansion::shouldUpdate) + .count(); + + StringBuilder message = new StringBuilder(registered.size() == 0 ? "&6" : "&a") + .append(registered.size()) + .append(' ') + .append("placeholder hook(s) registered!"); + + if (needsUpdate > 0) { + message.append(' ') + .append("&6") + .append(needsUpdate) + .append(' ') + .append("placeholder hook(s) have an update available."); + } + + + Msg.msg(sender, message.toString()); + + Bukkit.getPluginManager().callEvent(new ExpansionsLoadedEvent(registered)); + }); + } + + private void unregisterAll() { + for (final PlaceholderExpansion expansion : Sets.newHashSet(expansions.values())) { + if (expansion.persist()) { + continue; + } + + expansion.unregister(); + } + } + + @NotNull + public CompletableFuture<@NotNull List<@Nullable Class>> findExpansionsOnDisk() { + File[] files = folder.listFiles((dir, name) -> name.endsWith(".jar")); + if (files == null) { + return CompletableFuture.completedFuture(Collections.emptyList()); + } + + return Arrays.stream(files) + .map(this::findExpansionInFile) + .collect(Futures.collector()); + } + + @NotNull + public CompletableFuture<@Nullable Class> findExpansionInFile( + @NotNull final File file) { + return CompletableFuture.supplyAsync(() -> { + try { + final Class expansionClass = FileUtil.findClass(file, PlaceholderExpansion.class); + + if (expansionClass == null) { + Msg.severe("Failed to load expansion %s, as it does not have a class which" + + " extends PlaceholderExpansion", file.getName()); + return null; + } + + Set expansionMethods = Arrays.stream(expansionClass.getDeclaredMethods()) + .map(method -> new MethodSignature(method.getName(), method.getParameterTypes())) + .collect(Collectors.toSet()); + if (!expansionMethods.containsAll(ABSTRACT_EXPANSION_METHODS)) { + Msg.severe("Failed to load expansion %s, as it does not have the required" + + " methods declared for a PlaceholderExpansion.", file.getName()); + return null; + } + + return expansionClass; + } catch (VerifyError | NoClassDefFoundError e) { + Msg.severe("Failed to load expansion %s (is a dependency missing?)", e, file.getName()); + return null; + } catch (Exception e) { + plugin.getLogger().log(Level.SEVERE, "Failed to load expansion file: " + file.getAbsolutePath(), e); + return null; + } + }); + } + + + @Nullable + public PlaceholderExpansion createExpansionInstance( + @NotNull final Class clazz) throws LinkageError { + try { + return clazz.getDeclaredConstructor().newInstance(); + } catch (final Exception ex) { + if (ex.getCause() instanceof LinkageError) { + throw ((LinkageError) ex.getCause()); + } + + Msg.warn("There was an issue with loading an expansion."); + return null; + } + } + + + @EventHandler + public void onQuit(@NotNull final PlayerQuitEvent event) { + for (final PlaceholderExpansion expansion : getExpansions()) { + if (!(expansion instanceof Cleanable)) { + continue; + } + + ((Cleanable) expansion).cleanup(event.getPlayer()); + } + } + + @EventHandler(priority = EventPriority.HIGH) + public void onPluginDisable(@NotNull final PluginDisableEvent event) { + final String name = event.getPlugin().getName(); + if (name.equals(plugin.getName())) { + return; + } + + for (final PlaceholderExpansion expansion : getExpansions()) { + if (!name.equalsIgnoreCase(expansion.getRequiredPlugin())) { + continue; + } + + expansion.unregister(); + Msg.info("Unregistered placeholder expansion %s", expansion.getIdentifier()); + Msg.info("Reason: required plugin %s was disabled.", name); + } + } + +} diff --git a/src/main/java/me/clip/placeholderapi/expansion/manager/MethodSignature.java b/spigot/src/main/java/me/clip/placeholderapi/expansion/manager/MethodSignature.java similarity index 100% rename from src/main/java/me/clip/placeholderapi/expansion/manager/MethodSignature.java rename to spigot/src/main/java/me/clip/placeholderapi/expansion/manager/MethodSignature.java diff --git a/src/main/java/me/clip/placeholderapi/listeners/ServerLoadEventListener.java b/spigot/src/main/java/me/clip/placeholderapi/listeners/ServerLoadEventListener.java similarity index 72% rename from src/main/java/me/clip/placeholderapi/listeners/ServerLoadEventListener.java rename to spigot/src/main/java/me/clip/placeholderapi/listeners/ServerLoadEventListener.java index 7fdfba3..2843144 100644 --- a/src/main/java/me/clip/placeholderapi/listeners/ServerLoadEventListener.java +++ b/spigot/src/main/java/me/clip/placeholderapi/listeners/ServerLoadEventListener.java @@ -30,19 +30,19 @@ import org.jetbrains.annotations.NotNull; public final class ServerLoadEventListener implements Listener { - @NotNull - private final PlaceholderAPIPlugin plugin; + @NotNull + private final PlaceholderAPIPlugin plugin; - public ServerLoadEventListener(@NotNull final PlaceholderAPIPlugin plugin) { - this.plugin = plugin; + public ServerLoadEventListener(@NotNull final PlaceholderAPIPlugin plugin) { + this.plugin = plugin; - Bukkit.getPluginManager().registerEvents(this, plugin); - } + Bukkit.getPluginManager().registerEvents(this, plugin); + } - @EventHandler - public void onServerLoad(@NotNull final ServerLoadEvent event) { - HandlerList.unregisterAll(this); - plugin.getLocalExpansionManager().load(Bukkit.getConsoleSender()); - } + @EventHandler + public void onServerLoad(@NotNull final ServerLoadEvent event) { + HandlerList.unregisterAll(this); + plugin.getLocalExpansionManager().load(Bukkit.getConsoleSender()); + } } diff --git a/spigot/src/main/java/me/clip/placeholderapi/replacer/CharsReplacer.java b/spigot/src/main/java/me/clip/placeholderapi/replacer/CharsReplacer.java new file mode 100644 index 0000000..4459159 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/replacer/CharsReplacer.java @@ -0,0 +1,138 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.replacer; + +import java.util.Locale; +import java.util.function.Function; + +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import org.bukkit.ChatColor; +import org.bukkit.OfflinePlayer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public final class CharsReplacer implements Replacer { + + @NotNull + private final Closure closure; + + public CharsReplacer(@NotNull final Closure closure) { + this.closure = closure; + } + + + @NotNull + @Override + public String apply(@NotNull final String text, @Nullable final OfflinePlayer player, + @NotNull final Function lookup) { + final char[] chars = text.toCharArray(); + final StringBuilder builder = new StringBuilder(text.length()); + + final StringBuilder identifier = new StringBuilder(); + final StringBuilder parameters = new StringBuilder(); + + for (int i = 0; i < chars.length; i++) { + final char l = chars[i]; + + if (l != closure.head || i + 1 >= chars.length) { + builder.append(l); + continue; + } + + boolean identified = false; + boolean invalid = true; + boolean hadSpace = false; + + while (++i < chars.length) { + final char p = chars[i]; + + if (p == ' ' && !identified) { + hadSpace = true; + break; + } + if (p == closure.tail) { + invalid = false; + break; + } + + if (p == '_' && !identified) { + identified = true; + continue; + } + + if (identified) { + parameters.append(p); + } else { + identifier.append(p); + } + } + + final String identifierString = identifier.toString(); + final String lowercaseIdentifierString = identifierString.toLowerCase(Locale.ROOT); + final String parametersString = parameters.toString(); + + identifier.setLength(0); + parameters.setLength(0); + + if (invalid) { + builder.append(closure.head).append(identifierString); + + if (identified) { + builder.append('_').append(parametersString); + } + + if (hadSpace) { + builder.append(' '); + } + continue; + } + + final PlaceholderExpansion placeholder = lookup.apply(lowercaseIdentifierString); + if (placeholder == null) { + builder.append(closure.head).append(identifierString); + + if (identified) { + builder.append('_'); + } + + builder.append(parametersString).append(closure.tail); + continue; + } + + final String replacement = placeholder.onRequest(player, parametersString); + if (replacement == null) { + builder.append(closure.head).append(identifierString); + + if (identified) { + builder.append('_'); + } + + builder.append(parametersString).append(closure.tail); + continue; + } + + builder.append(replacement); + } + + return builder.toString(); + } + +} diff --git a/src/main/java/me/clip/placeholderapi/replacer/Replacer.java b/spigot/src/main/java/me/clip/placeholderapi/replacer/Replacer.java similarity index 71% rename from src/main/java/me/clip/placeholderapi/replacer/Replacer.java rename to spigot/src/main/java/me/clip/placeholderapi/replacer/Replacer.java index e0c6e48..3cbc13e 100644 --- a/src/main/java/me/clip/placeholderapi/replacer/Replacer.java +++ b/spigot/src/main/java/me/clip/placeholderapi/replacer/Replacer.java @@ -21,6 +21,7 @@ package me.clip.placeholderapi.replacer; import java.util.function.Function; + import me.clip.placeholderapi.expansion.PlaceholderExpansion; import org.bukkit.OfflinePlayer; import org.jetbrains.annotations.NotNull; @@ -28,22 +29,22 @@ import org.jetbrains.annotations.Nullable; public interface Replacer { - @NotNull - String apply(@NotNull final String text, @Nullable final OfflinePlayer player, - @NotNull final Function lookup); + @NotNull + String apply(@NotNull final String text, @Nullable final OfflinePlayer player, + @NotNull final Function lookup); - enum Closure { - BRACKET('{', '}'), - PERCENT('%', '%'); + enum Closure { + BRACKET('{', '}'), + PERCENT('%', '%'); - public final char head, tail; + public final char head, tail; - Closure(final char head, final char tail) { - this.head = head; - this.tail = tail; + Closure(final char head, final char tail) { + this.head = head; + this.tail = tail; + } } - } } diff --git a/src/main/java/me/clip/placeholderapi/scheduler/UniversalRunnable.java b/spigot/src/main/java/me/clip/placeholderapi/scheduler/UniversalRunnable.java similarity index 99% rename from src/main/java/me/clip/placeholderapi/scheduler/UniversalRunnable.java rename to spigot/src/main/java/me/clip/placeholderapi/scheduler/UniversalRunnable.java index 978285b..65ae9b5 100644 --- a/src/main/java/me/clip/placeholderapi/scheduler/UniversalRunnable.java +++ b/spigot/src/main/java/me/clip/placeholderapi/scheduler/UniversalRunnable.java @@ -27,7 +27,9 @@ import me.clip.placeholderapi.scheduler.scheduling.schedulers.TaskScheduler; import me.clip.placeholderapi.scheduler.scheduling.tasks.MyScheduledTask; import org.bukkit.plugin.Plugin; -/** Just modified BukkitRunnable */ +/** + * Just modified BukkitRunnable + */ public abstract class UniversalRunnable implements Runnable { MyScheduledTask task; diff --git a/src/main/java/me/clip/placeholderapi/scheduler/UniversalScheduler.java b/spigot/src/main/java/me/clip/placeholderapi/scheduler/UniversalScheduler.java similarity index 100% rename from src/main/java/me/clip/placeholderapi/scheduler/UniversalScheduler.java rename to spigot/src/main/java/me/clip/placeholderapi/scheduler/UniversalScheduler.java diff --git a/src/main/java/me/clip/placeholderapi/scheduler/bukkit/BukkitScheduledTask.java b/spigot/src/main/java/me/clip/placeholderapi/scheduler/bukkit/BukkitScheduledTask.java similarity index 100% rename from src/main/java/me/clip/placeholderapi/scheduler/bukkit/BukkitScheduledTask.java rename to spigot/src/main/java/me/clip/placeholderapi/scheduler/bukkit/BukkitScheduledTask.java diff --git a/src/main/java/me/clip/placeholderapi/scheduler/bukkit/BukkitScheduler.java b/spigot/src/main/java/me/clip/placeholderapi/scheduler/bukkit/BukkitScheduler.java similarity index 100% rename from src/main/java/me/clip/placeholderapi/scheduler/bukkit/BukkitScheduler.java rename to spigot/src/main/java/me/clip/placeholderapi/scheduler/bukkit/BukkitScheduler.java diff --git a/src/main/java/me/clip/placeholderapi/scheduler/folia/FoliaScheduledTask.java b/spigot/src/main/java/me/clip/placeholderapi/scheduler/folia/FoliaScheduledTask.java similarity index 100% rename from src/main/java/me/clip/placeholderapi/scheduler/folia/FoliaScheduledTask.java rename to spigot/src/main/java/me/clip/placeholderapi/scheduler/folia/FoliaScheduledTask.java diff --git a/src/main/java/me/clip/placeholderapi/scheduler/folia/FoliaScheduler.java b/spigot/src/main/java/me/clip/placeholderapi/scheduler/folia/FoliaScheduler.java similarity index 100% rename from src/main/java/me/clip/placeholderapi/scheduler/folia/FoliaScheduler.java rename to spigot/src/main/java/me/clip/placeholderapi/scheduler/folia/FoliaScheduler.java diff --git a/src/main/java/me/clip/placeholderapi/scheduler/paper/PaperScheduler.java b/spigot/src/main/java/me/clip/placeholderapi/scheduler/paper/PaperScheduler.java similarity index 100% rename from src/main/java/me/clip/placeholderapi/scheduler/paper/PaperScheduler.java rename to spigot/src/main/java/me/clip/placeholderapi/scheduler/paper/PaperScheduler.java diff --git a/src/main/java/me/clip/placeholderapi/scheduler/scheduling/schedulers/TaskScheduler.java b/spigot/src/main/java/me/clip/placeholderapi/scheduler/scheduling/schedulers/TaskScheduler.java similarity index 100% rename from src/main/java/me/clip/placeholderapi/scheduler/scheduling/schedulers/TaskScheduler.java rename to spigot/src/main/java/me/clip/placeholderapi/scheduler/scheduling/schedulers/TaskScheduler.java diff --git a/src/main/java/me/clip/placeholderapi/scheduler/scheduling/tasks/MyScheduledTask.java b/spigot/src/main/java/me/clip/placeholderapi/scheduler/scheduling/tasks/MyScheduledTask.java similarity index 100% rename from src/main/java/me/clip/placeholderapi/scheduler/scheduling/tasks/MyScheduledTask.java rename to spigot/src/main/java/me/clip/placeholderapi/scheduler/scheduling/tasks/MyScheduledTask.java diff --git a/src/main/java/me/clip/placeholderapi/scheduler/utils/JavaUtil.java b/spigot/src/main/java/me/clip/placeholderapi/scheduler/utils/JavaUtil.java similarity index 100% rename from src/main/java/me/clip/placeholderapi/scheduler/utils/JavaUtil.java rename to spigot/src/main/java/me/clip/placeholderapi/scheduler/utils/JavaUtil.java diff --git a/spigot/src/main/java/me/clip/placeholderapi/updatechecker/UpdateChecker.java b/spigot/src/main/java/me/clip/placeholderapi/updatechecker/UpdateChecker.java new file mode 100644 index 0000000..210a214 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/updatechecker/UpdateChecker.java @@ -0,0 +1,128 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.updatechecker; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.Arrays; +import javax.net.ssl.HttpsURLConnection; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import me.clip.placeholderapi.scheduler.scheduling.schedulers.TaskScheduler; +import me.clip.placeholderapi.util.Msg; +import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; + +public class UpdateChecker implements Listener { + + private static final int RESOURCE_ID = 6245; + private final PlaceholderAPIPlugin plugin; + private final TaskScheduler scheduler; + private final String pluginVersion; + private String spigotVersion; + private boolean updateAvailable; + + public UpdateChecker(PlaceholderAPIPlugin plugin) { + this.plugin = plugin; + scheduler = plugin.getScheduler(); + pluginVersion = plugin.getDescription().getVersion(); + } + + public boolean hasUpdateAvailable() { + return updateAvailable; + } + + public String getSpigotVersion() { + return spigotVersion; + } + + public void fetch() { + scheduler.runTaskAsynchronously(() -> { + try { + HttpsURLConnection con = (HttpsURLConnection) new URL( + "https://api.spigotmc.org/legacy/update.php?resource=" + RESOURCE_ID).openConnection(); + con.setRequestMethod("GET"); + spigotVersion = new BufferedReader(new InputStreamReader(con.getInputStream())).readLine(); + } catch (Exception ex) { + plugin.getLogger().info("Failed to check for updates on spigot."); + return; + } + + if (spigotVersion == null || spigotVersion.isEmpty()) { + return; + } + + updateAvailable = spigotIsNewer(); + + if (!updateAvailable) { + return; + } + + scheduler.runTask(() -> { + plugin.getLogger() + .info("An update for PlaceholderAPI (v" + getSpigotVersion() + ") is available at:"); + plugin.getLogger() + .info("https://www.spigotmc.org/resources/placeholderapi." + RESOURCE_ID + "/"); + Bukkit.getPluginManager().registerEvents(this, plugin); + }); + }); + } + + private boolean spigotIsNewer() { + if (spigotVersion == null || spigotVersion.isEmpty()) { + return false; + } + + int[] plV = toReadable(pluginVersion); + int[] spV = toReadable(spigotVersion); + + if (plV[0] < spV[0]) { + return true; + } else if ((plV[1] < spV[1])) { + return true; + } else { + return plV[2] < spV[2]; + } + } + + private int[] toReadable(String version) { + if (version.contains("-DEV")) { + version = version.split("-DEV")[0]; + } + + return Arrays.stream(version.split("\\.")).mapToInt(Integer::parseInt).toArray(); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onJoin(PlayerJoinEvent e) { + if (e.getPlayer().hasPermission("placeholderapi.updatenotify")) { + Msg.msg(e.getPlayer(), + "&bAn update for &fPlaceholder&7API &e(&fPlaceholder&7API &fv" + getSpigotVersion() + + "&e)" + , "&bis available at &ehttps://www.spigotmc.org/resources/placeholderapi." + RESOURCE_ID + + "/"); + } + } +} diff --git a/src/main/java/me/clip/placeholderapi/util/ExpansionSafetyCheck.java b/spigot/src/main/java/me/clip/placeholderapi/util/ExpansionSafetyCheck.java similarity index 71% rename from src/main/java/me/clip/placeholderapi/util/ExpansionSafetyCheck.java rename to spigot/src/main/java/me/clip/placeholderapi/util/ExpansionSafetyCheck.java index 4efe17e..365fb36 100644 --- a/src/main/java/me/clip/placeholderapi/util/ExpansionSafetyCheck.java +++ b/spigot/src/main/java/me/clip/placeholderapi/util/ExpansionSafetyCheck.java @@ -18,14 +18,14 @@ import java.util.stream.Collectors; public final class ExpansionSafetyCheck { private static final String MESSAGE = "\n###############################################\n" + - "###############################################\n" + - "PlaceholderAPI performs checks at startup and /papi reload for known malicious expansions. If you're seeing this message, there are the following malicious expansions in plugins/PlaceholderAPI/expansions.\n" + - "%s" + - "To prevent further infection PlaceholderAPI has stopped the server.\n" + - "If you're seeing this message after updating PAPI, your server may have been infected for some time, so best practice is a complete system wipe and reinstall of your server software and plugins to be safe.\n" + - "If you're seeing this after downloading an expansion however, PAPI hasn't loaded any of the malicious expansions above so you should be safe to simply delete the expansion in question.\n" + - "###############################################\n" + - "###############################################"; + "###############################################\n" + + "PlaceholderAPI performs checks at startup and /papi reload for known malicious expansions. If you're seeing this message, there are the following malicious expansions in plugins/PlaceholderAPI/expansions.\n" + + "%s" + + "To prevent further infection PlaceholderAPI has stopped the server.\n" + + "If you're seeing this message after updating PAPI, your server may have been infected for some time, so best practice is a complete system wipe and reinstall of your server software and plugins to be safe.\n" + + "If you're seeing this after downloading an expansion however, PAPI hasn't loaded any of the malicious expansions above so you should be safe to simply delete the expansion in question.\n" + + "###############################################\n" + + "###############################################"; private final PlaceholderAPIPlugin main; diff --git a/spigot/src/main/java/me/clip/placeholderapi/util/FileUtil.java b/spigot/src/main/java/me/clip/placeholderapi/util/FileUtil.java new file mode 100644 index 0000000..3a78150 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/util/FileUtil.java @@ -0,0 +1,77 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.util; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.List; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; + +public class FileUtil { + + @Nullable + public static Class findClass(@NotNull final File file, + @NotNull final Class clazz) throws IOException, ClassNotFoundException { + if (!file.exists()) { + return null; + } + + final URL jar = file.toURI().toURL(); + final URLClassLoader loader = new URLClassLoader(new URL[]{jar}, clazz.getClassLoader()); + final List matches = new ArrayList<>(); + final List> classes = new ArrayList<>(); + + try (final JarInputStream stream = new JarInputStream(jar.openStream())) { + JarEntry entry; + while ((entry = stream.getNextJarEntry()) != null) { + final String name = entry.getName(); + if (name.isEmpty() || !name.endsWith(".class")) { + continue; + } + + matches.add(name.substring(0, name.lastIndexOf('.')).replace('/', '.')); + } + + for (final String match : matches) { + try { + final Class loaded = loader.loadClass(match); + if (clazz.isAssignableFrom(loaded)) { + classes.add(loaded.asSubclass(clazz)); + } + } catch (final NoClassDefFoundError ignored) { + } + } + } + if (classes.isEmpty()) { + loader.close(); + return null; + } + return classes.get(0); + } + +} diff --git a/src/main/java/me/clip/placeholderapi/util/Format.java b/spigot/src/main/java/me/clip/placeholderapi/util/Format.java similarity index 50% rename from src/main/java/me/clip/placeholderapi/util/Format.java rename to spigot/src/main/java/me/clip/placeholderapi/util/Format.java index a149ec5..bc969c6 100644 --- a/src/main/java/me/clip/placeholderapi/util/Format.java +++ b/spigot/src/main/java/me/clip/placeholderapi/util/Format.java @@ -29,6 +29,7 @@ import static java.util.stream.IntStream.range; import java.util.List; import java.util.Optional; + import org.jetbrains.annotations.NotNull; /** @@ -36,35 +37,35 @@ import org.jetbrains.annotations.NotNull; */ public final class Format { - private Format() {} + private Format() {} - @NotNull - public static Optional> tablify(@NotNull final Align align, - @NotNull final List> rows) { - return findSpacing(rows) - .map(spacing -> buildFormat(align, spacing)) - .map(format -> rows.stream() - .map( - row -> String.format(format, row.toArray()).substring(align == Align.RIGHT ? 2 : 0)) - .collect(toList())); - } + @NotNull + public static Optional> tablify(@NotNull final Align align, + @NotNull final List> rows) { + return findSpacing(rows) + .map(spacing -> buildFormat(align, spacing)) + .map(format -> rows.stream() + .map( + row -> String.format(format, row.toArray()).substring(align == Align.RIGHT ? 2 : 0)) + .collect(toList())); + } - @NotNull - private static String buildFormat(@NotNull final Align align, final int[] spacing) { - return stream(spacing) - .mapToObj(space -> "%" + (align == Align.LEFT ? "-" : "") + (space + 2) + "s") - .collect(joining()); - } + @NotNull + private static String buildFormat(@NotNull final Align align, final int[] spacing) { + return stream(spacing) + .mapToObj(space -> "%" + (align == Align.LEFT ? "-" : "") + (space + 2) + "s") + .collect(joining()); + } - @NotNull - private static Optional findSpacing(@NotNull final List> rows) { - return rows.stream() - .map(row -> row.stream().mapToInt(String::length).toArray()) - .reduce((l, r) -> range(0, min(l.length, r.length)).map(i -> max(l[i], r[i])).toArray()); - } + @NotNull + private static Optional findSpacing(@NotNull final List> rows) { + return rows.stream() + .map(row -> row.stream().mapToInt(String::length).toArray()) + .reduce((l, r) -> range(0, min(l.length, r.length)).map(i -> max(l[i], r[i])).toArray()); + } - public enum Align { - LEFT, RIGHT - } + public enum Align { + LEFT, RIGHT + } } diff --git a/spigot/src/main/java/me/clip/placeholderapi/util/Futures.java b/spigot/src/main/java/me/clip/placeholderapi/util/Futures.java new file mode 100644 index 0000000..ad76040 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/util/Futures.java @@ -0,0 +1,79 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.util; + +import java.util.Collection; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.function.BiConsumer; +import java.util.stream.Collector; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import org.bukkit.Bukkit; +import org.bukkit.plugin.Plugin; +import org.jetbrains.annotations.NotNull; + +public final class Futures { + + private Futures() {} + + + public static void onMainThread(@NotNull final PlaceholderAPIPlugin plugin, + @NotNull final CompletableFuture future, + @NotNull final BiConsumer consumer) { + future.whenComplete((value, exception) -> { + if (Bukkit.isPrimaryThread()) { + consumer.accept(value, exception); + } else { + plugin.getScheduler().runTask(() -> consumer.accept(value, exception)); + } + }); + } + + + @NotNull + public static Collector, ?, CompletableFuture>> collector() { + return Collectors.collectingAndThen(Collectors.toList(), Futures::of); + } + + + @NotNull + public static CompletableFuture> of( + @NotNull final Stream> futures) { + return of(futures.collect(Collectors.toList())); + } + + @NotNull + public static CompletableFuture> of( + @NotNull final Collection> futures) { + return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) + .thenApplyAsync($ -> awaitCompletion(futures)); + } + + @NotNull + private static List awaitCompletion( + @NotNull final Collection> futures) { + return futures.stream().map(CompletableFuture::join).collect(Collectors.toList()); + } + +} diff --git a/spigot/src/main/java/me/clip/placeholderapi/util/Msg.java b/spigot/src/main/java/me/clip/placeholderapi/util/Msg.java new file mode 100644 index 0000000..ed179ad --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/util/Msg.java @@ -0,0 +1,80 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.util; + +import java.util.Arrays; +import java.util.logging.Level; +import java.util.stream.Collectors; + +import me.clip.placeholderapi.PlaceholderAPIPlugin; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.jetbrains.annotations.NotNull; + +public final class Msg { + + public static void log(Level level, String msg, Object... args) { + PlaceholderAPIPlugin.getInstance().getLogger().log(level, String.format(msg, args)); + } + + public static void info(String msg, Object... args) { + log(Level.INFO, msg, args); + } + + public static void warn(String msg, Object... args) { + log(Level.WARNING, msg, args); + } + + public static void warn(String msg, Throwable throwable, Object... args) { + PlaceholderAPIPlugin.getInstance().getLogger().log(Level.WARNING, String.format(msg, args), throwable); + } + + public static void severe(String msg, Object... args) { + log(Level.SEVERE, msg, args); + } + + public static void severe(String msg, Throwable throwable, Object... args) { + PlaceholderAPIPlugin.getInstance().getLogger().log(Level.SEVERE, String.format(msg, args), throwable); + } + + public static void msg(@NotNull final CommandSender sender, @NotNull final String... messages) { + if (messages.length == 0) { + return; + } + + sender.sendMessage(Arrays.stream(messages).map(Msg::color).collect(Collectors.joining("\n"))); + } + + public static void broadcast(@NotNull final String... messages) { + if (messages.length == 0) { + return; + } + + Bukkit.broadcastMessage( + Arrays.stream(messages).map(Msg::color).collect(Collectors.joining("\n"))); + } + + public static String color(@NotNull final String text) { + return ChatColor.translateAlternateColorCodes('&', text); + } + +} diff --git a/src/main/java/me/clip/placeholderapi/util/TimeFormat.java b/spigot/src/main/java/me/clip/placeholderapi/util/TimeFormat.java similarity index 94% rename from src/main/java/me/clip/placeholderapi/util/TimeFormat.java rename to spigot/src/main/java/me/clip/placeholderapi/util/TimeFormat.java index f66f9da..4dc2a88 100644 --- a/src/main/java/me/clip/placeholderapi/util/TimeFormat.java +++ b/spigot/src/main/java/me/clip/placeholderapi/util/TimeFormat.java @@ -21,8 +21,8 @@ package me.clip.placeholderapi.util; public enum TimeFormat { - DAYS, - HOURS, - MINUTES, - SECONDS + DAYS, + HOURS, + MINUTES, + SECONDS } diff --git a/spigot/src/main/java/me/clip/placeholderapi/util/TimeUtil.java b/spigot/src/main/java/me/clip/placeholderapi/util/TimeUtil.java new file mode 100644 index 0000000..24db4d8 --- /dev/null +++ b/spigot/src/main/java/me/clip/placeholderapi/util/TimeUtil.java @@ -0,0 +1,96 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi.util; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.util.StringJoiner; + +public class TimeUtil { + + public static String getRemaining(final int seconds, final TimeFormat type) { + return getRemaining((long) seconds, type); + } + + public static String getRemaining(final long seconds, final TimeFormat type) { + switch (type) { + default: + return String.valueOf(seconds); + + case SECONDS: + return String.valueOf(seconds % 60); + + case MINUTES: + return String.valueOf((seconds / 60) % 60); + + case HOURS: + return String.valueOf((seconds / 3600) % 24); + + case DAYS: + return String.valueOf(seconds / 86400); + } + } + + /** + * Format the given value with s, m, h and d (seconds, minutes, hours and days) + * + * @param duration {@link Duration} (eg, Duration.of(20, {@link ChronoUnit#SECONDS}) for 20 + * seconds) + * @return formatted time + */ + public static String getTime(final Duration duration) { + return getTime(duration.getSeconds()); + } + + public static String getTime(final int seconds) { + return getTime((long) seconds); + } + + public static String getTime(long seconds) { + final StringJoiner joiner = new StringJoiner(" "); + + long minutes = seconds / 60; + long hours = minutes / 60; + final long days = hours / 24; + + seconds %= 60; + minutes %= 60; + hours %= 24; + + if (days > 0) { + joiner.add(days + "d"); + } + + if (hours > 0) { + joiner.add(hours + "h"); + } + + if (minutes > 0) { + joiner.add(minutes + "m"); + } + + if (seconds > 0) { + joiner.add(seconds + "s"); + } + + return joiner.toString(); + } +} diff --git a/src/main/resources/config.yml b/spigot/src/main/resources/config.yml similarity index 100% rename from src/main/resources/config.yml rename to spigot/src/main/resources/config.yml diff --git a/src/main/resources/plugin.yml b/spigot/src/main/resources/plugin.yml similarity index 100% rename from src/main/resources/plugin.yml rename to spigot/src/main/resources/plugin.yml diff --git a/spigot/src/test/java/me/clip/placeholderapi/Values.java b/spigot/src/test/java/me/clip/placeholderapi/Values.java new file mode 100644 index 0000000..002f74a --- /dev/null +++ b/spigot/src/test/java/me/clip/placeholderapi/Values.java @@ -0,0 +1,93 @@ +/* + * This file is part of PlaceholderAPI + * + * PlaceholderAPI + * Copyright (c) 2015 - 2024 PlaceholderAPI Team + * + * PlaceholderAPI 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. + * + * PlaceholderAPI 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 me.clip.placeholderapi; + +import com.google.common.collect.ImmutableMap; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import me.clip.placeholderapi.replacer.CharsReplacer; +import me.clip.placeholderapi.replacer.Replacer; +import org.bukkit.OfflinePlayer; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +public interface Values { + + String SMALL_TEXT = "My name is %player_name%"; + String LARGE_TEXT = "My name is %player_name% and my location is (%player_x%, %player_y%, %player_z%), this placeholder is invalid %server_name%"; + + ImmutableMap PLACEHOLDERS = ImmutableMap.builder() + .put("player", new MockPlayerPlaceholderExpansion()) + .build(); + + + Replacer CHARS_REPLACER = new CharsReplacer(Replacer.Closure.PERCENT); + + + final class MockPlayerPlaceholderExpansion extends PlaceholderExpansion { + + public static final String PLAYER_X = "10"; + public static final String PLAYER_Y = "20"; + public static final String PLAYER_Z = "30"; + public static final String PLAYER_NAME = "Sxtanna"; + + + @NotNull + @Override + public String getIdentifier() { + return "player"; + } + + @NotNull + @Override + public String getAuthor() { + return "Sxtanna"; + } + + @NotNull + @Override + public String getVersion() { + return "1.0"; + } + + @Override + public String onRequest(@Nullable final OfflinePlayer player, @NotNull final String params) { + final String[] parts = params.split("_"); + if (parts.length == 0) { + return null; + } + + switch (parts[0]) { + case "name": + return PLAYER_NAME; + case "x": + return PLAYER_X; + case "y": + return PLAYER_Y; + case "z": + return PLAYER_Z; + } + + return null; + } + + } + +} diff --git a/src/test/java/me/clip/placeholderapi/replacer/ReplacerBenchmarks.java b/spigot/src/test/java/me/clip/placeholderapi/replacer/ReplacerBenchmarks.java similarity index 74% rename from src/test/java/me/clip/placeholderapi/replacer/ReplacerBenchmarks.java rename to spigot/src/test/java/me/clip/placeholderapi/replacer/ReplacerBenchmarks.java index e08de47..1ee6cf7 100644 --- a/src/test/java/me/clip/placeholderapi/replacer/ReplacerBenchmarks.java +++ b/spigot/src/test/java/me/clip/placeholderapi/replacer/ReplacerBenchmarks.java @@ -25,14 +25,14 @@ import org.openjdk.jmh.annotations.Benchmark; public class ReplacerBenchmarks { - @Benchmark - public void measureCharsReplacerSmallText() { - Values.CHARS_REPLACER.apply(Values.SMALL_TEXT, null, Values.PLACEHOLDERS::get); - } + @Benchmark + public void measureCharsReplacerSmallText() { + Values.CHARS_REPLACER.apply(Values.SMALL_TEXT, null, Values.PLACEHOLDERS::get); + } - @Benchmark - public void measureCharsReplacerLargeText() { - Values.CHARS_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get); - } + @Benchmark + public void measureCharsReplacerLargeText() { + Values.CHARS_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get); + } } \ No newline at end of file diff --git a/src/test/java/me/clip/placeholderapi/replacer/ReplacerUnitTester.java b/spigot/src/test/java/me/clip/placeholderapi/replacer/ReplacerUnitTester.java similarity index 55% rename from src/test/java/me/clip/placeholderapi/replacer/ReplacerUnitTester.java rename to spigot/src/test/java/me/clip/placeholderapi/replacer/ReplacerUnitTester.java index f0c914f..a4be43e 100644 --- a/src/test/java/me/clip/placeholderapi/replacer/ReplacerUnitTester.java +++ b/spigot/src/test/java/me/clip/placeholderapi/replacer/ReplacerUnitTester.java @@ -31,33 +31,33 @@ import org.junit.jupiter.api.Test; public final class ReplacerUnitTester { - @Test - void testCharsReplacerProducesExpectedSingleValue() { - assertEquals(PLAYER_NAME, - Values.CHARS_REPLACER.apply("%player_name%", null, Values.PLACEHOLDERS::get)); - } + @Test + void testCharsReplacerProducesExpectedSingleValue() { + assertEquals(PLAYER_NAME, + Values.CHARS_REPLACER.apply("%player_name%", null, Values.PLACEHOLDERS::get)); + } - @Test - void testCharsReplacerProducesExpectedSentence() { - assertEquals(String.format( - "My name is %s and my location is (%s, %s, %s), this placeholder is invalid %%server_name%%", - PLAYER_NAME, PLAYER_X, PLAYER_Y, PLAYER_Z), - Values.CHARS_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get)); - } + @Test + void testCharsReplacerProducesExpectedSentence() { + assertEquals(String.format( + "My name is %s and my location is (%s, %s, %s), this placeholder is invalid %%server_name%%", + PLAYER_NAME, PLAYER_X, PLAYER_Y, PLAYER_Z), + Values.CHARS_REPLACER.apply(Values.LARGE_TEXT, null, Values.PLACEHOLDERS::get)); + } - @Test - void testResultsAreTheSameAsReplacement() { - final String resultChars = Values.CHARS_REPLACER - .apply("%player_name%", null, Values.PLACEHOLDERS::get); + @Test + void testResultsAreTheSameAsReplacement() { + final String resultChars = Values.CHARS_REPLACER + .apply("%player_name%", null, Values.PLACEHOLDERS::get); - assertEquals(PLAYER_NAME, resultChars); - } + assertEquals(PLAYER_NAME, resultChars); + } - @Test - void testCharsReplacerIgnoresMalformed() { - final String text = "10% and %hello world 15%"; + @Test + void testCharsReplacerIgnoresMalformed() { + final String text = "10% and %hello world 15%"; - assertEquals(text, Values.CHARS_REPLACER.apply(text, null, Values.PLACEHOLDERS::get)); - } + assertEquals(text, Values.CHARS_REPLACER.apply(text, null, Values.PLACEHOLDERS::get)); + } } diff --git a/src/main/java/me/clip/placeholderapi/PlaceholderAPI.java b/src/main/java/me/clip/placeholderapi/PlaceholderAPI.java deleted file mode 100644 index 97b6c48..0000000 --- a/src/main/java/me/clip/placeholderapi/PlaceholderAPI.java +++ /dev/null @@ -1,624 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi; - -import com.google.common.collect.ImmutableSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.clip.placeholderapi.expansion.Relational; -import me.clip.placeholderapi.expansion.manager.LocalExpansionManager; -import me.clip.placeholderapi.replacer.CharsReplacer; -import me.clip.placeholderapi.replacer.Replacer; -import me.clip.placeholderapi.replacer.Replacer.Closure; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.NotNull; - -public final class PlaceholderAPI { - - private static final Replacer REPLACER_PERCENT = new CharsReplacer(Closure.PERCENT); - private static final Replacer REPLACER_BRACKET = new CharsReplacer(Closure.BRACKET); - - private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("[%]([^%]+)[%]"); - private static final Pattern BRACKET_PLACEHOLDER_PATTERN = Pattern.compile("[{]([^{}]+)[}]"); - private static final Pattern RELATIONAL_PLACEHOLDER_PATTERN = Pattern - .compile("[%](rel_)([^%]+)[%]"); - - - private PlaceholderAPI() { - } - - // === Current API === - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal %_%}. - * - * @param player Player to parse the placeholders against - * @param text Text to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static String setPlaceholders(final OfflinePlayer player, - @NotNull final String text) { - return REPLACER_PERCENT.apply(text, player, - PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion); - } - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal %_%}. - * - * @param player Player to parse the placeholders against - * @param text List of Strings to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static List setPlaceholders(final OfflinePlayer player, - @NotNull final List text) { - return text.stream().map(line -> setPlaceholders(player, line)).collect(Collectors.toList()); - } - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal %_%}. - * - * @param player Player to parse the placeholders against - * @param text Text to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static String setPlaceholders(final Player player, @NotNull String text) { - return setPlaceholders(((OfflinePlayer) player), text); - } - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal %_%}. - * - * @param player Player to parse the placeholders against - * @param text List of Strings to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static List setPlaceholders(final Player player, @NotNull List<@NotNull String> text) { - return setPlaceholders(((OfflinePlayer) player), text); - } - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal {_}}. - * - * @param player Player to parse the placeholders against - * @param text Text to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static String setBracketPlaceholders(final OfflinePlayer player, - @NotNull final String text) { - return REPLACER_BRACKET.apply(text, player, - PlaceholderAPIPlugin.getInstance().getLocalExpansionManager()::getExpansion); - } - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal {_}}. - * - * @param player Player to parse the placeholders against - * @param text List of Strings to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static List<@NotNull String> setBracketPlaceholders(final OfflinePlayer player, - @NotNull final List<@NotNull String> text) { - return text.stream().map(line -> setBracketPlaceholders(player, line)) - .collect(Collectors.toList()); - } - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal {_}}. - * - * @param player Player to parse the placeholders against - * @param text Text to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static String setBracketPlaceholders(Player player, @NotNull String text) { - return setBracketPlaceholders((OfflinePlayer) player, text); - } - - /** - * Translates all placeholders into their corresponding values. - *
The pattern of a valid placeholder is {@literal {_}}. - * - * @param player Player to parse the placeholders against - * @param text List of Strings to set the placeholder values in - * @return String containing all translated placeholders - */ - @NotNull - public static List setBracketPlaceholders(Player player, @NotNull List text) { - return setBracketPlaceholders((OfflinePlayer) player, text); - } - - /** - * set relational placeholders in the text specified placeholders are matched with the pattern - * {@literal %%} when set with this method - * - * @param one First player to compare - * @param two Second player to compare - * @param text Text to parse the placeholders in - * @return The text containing the parsed relational placeholders - */ - public static String setRelationalPlaceholders(Player one, Player two, String text) { - final Matcher matcher = RELATIONAL_PLACEHOLDER_PATTERN.matcher(text); - - while (matcher.find()) { - final String format = matcher.group(2); - final int index = format.indexOf("_"); - - if (index <= 0 || index >= format.length()) { - continue; - } - - String identifier = format.substring(0, index).toLowerCase(Locale.ROOT); - String params = format.substring(index + 1); - final PlaceholderExpansion expansion = PlaceholderAPIPlugin.getInstance() - .getLocalExpansionManager().getExpansion(identifier); - - if (!(expansion instanceof Relational)) { - continue; - } - - final String value = ((Relational) expansion).onPlaceholderRequest(one, two, params); - - if (value != null) { - text = text.replaceAll(Pattern.quote(matcher.group()), Matcher.quoteReplacement(value)); - } - } - - return text; - } - - /** - * Translate placeholders in the provided List based on the relation of the two provided players. - *
The pattern of a valid placeholder is {@literal %rel__%}. - * - * @param one Player to compare - * @param two Player to compare - * @param text text to parse the placeholder values to - * @return The text containing the parsed relational placeholders - */ - public static List setRelationalPlaceholders(Player one, Player two, List text) { - return text.stream().map(line -> setRelationalPlaceholders(one, two, line)) - .collect(Collectors.toList()); - } - - /** - * Check if a specific placeholder identifier is currently registered - * - * @param identifier The identifier to check - * @return true if identifier is already registered - */ - public static boolean isRegistered(@NotNull final String identifier) { - return PlaceholderAPIPlugin.getInstance().getLocalExpansionManager() - .findExpansionByIdentifier(identifier).isPresent(); - } - - /** - * Get all registered placeholder identifiers - * - * @return A Set of type String containing the identifiers of all registered expansions. - */ - @NotNull - public static Set getRegisteredIdentifiers() { - return ImmutableSet - .copyOf(PlaceholderAPIPlugin.getInstance().getLocalExpansionManager().getIdentifiers()); - } - - /** - * Get the normal placeholder pattern. - * - * @return Regex Pattern of {@literal [%]([^%]+)[%]} - */ - public static Pattern getPlaceholderPattern() { - return PLACEHOLDER_PATTERN; - } - - /** - * Get the bracket placeholder pattern. - * - * @return Regex Pattern of {@literal [{]([^{}]+)[}]} - */ - public static Pattern getBracketPlaceholderPattern() { - return BRACKET_PLACEHOLDER_PATTERN; - } - - /** - * Get the relational placeholder pattern. - * - * @return Regex Pattern of {@literal [%](rel_)([^%]+)[%]} - */ - public static Pattern getRelationalPlaceholderPattern() { - return RELATIONAL_PLACEHOLDER_PATTERN; - } - - /** - * Check if a String contains any PlaceholderAPI placeholders ({@literal - * %_%}). - * - * @param text String to check - * @return true if String contains any matches to the normal placeholder pattern, false otherwise - */ - public static boolean containsPlaceholders(String text) { - return text != null && PLACEHOLDER_PATTERN.matcher(text).find(); - } - - /** - * Check if a String contains any PlaceholderAPI bracket placeholders ({@literal - * {_}}). - * - * @param text String to check - * @return true if String contains any matches to the bracket placeholder pattern, false otherwise - */ - public static boolean containsBracketPlaceholders(String text) { - return text != null && BRACKET_PLACEHOLDER_PATTERN.matcher(text).find(); - } - - // === Deprecated API === - - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static boolean registerExpansion(PlaceholderExpansion expansion) - { - return expansion.register(); - } - - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static boolean unregisterExpansion(PlaceholderExpansion expansion) - { - return expansion.unregister(); - } - - /** - * Get map of registered placeholders - * - * @deprecated Use {@link LocalExpansionManager#getExpansions()} instead. - * - * @return Map of registered placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static Map getPlaceholders() { - return PlaceholderAPIPlugin.getInstance().getLocalExpansionManager() - .getExpansions().stream() - .collect(Collectors.toMap(PlaceholderExpansion::getIdentifier, ex -> ex)); - } - - /** - * @deprecated Please use {@link PlaceholderExpansion} to - * register placeholders instead - * - * @param plugin The Plugin to register with this {@link PlaceholderHook} - * @param placeholderHook The {@link PlaceholderHook} to register - * @return always false - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static boolean registerPlaceholderHook(Plugin plugin, PlaceholderHook placeholderHook) { - Msg.warn("Nag author(s) %s of plugin %s about their usage of the deprecated PlaceholderHook" - + " class! This class will be removed in v2.13.0!", plugin.getDescription().getAuthors(), - plugin.getName()); - return false; - } - - /** - * @deprecated Please use {@link PlaceholderExpansion} to - * register placeholders instead - * - * @param identifier The identifier to use for the {@link PlaceholderHook} - * @param placeholderHook The {@link PlaceholderHook} to register - * @return always false - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static boolean registerPlaceholderHook(String identifier, - PlaceholderHook placeholderHook) { - Msg.warn("%s is attempting to register placeholders via deprecated PlaceholderHook class." - + " This class is no longer supported and will be removed in v2.13.0!", identifier); - return false; - } - - /** - * @deprecated Please use {@link PlaceholderExpansion} to - * unregister placeholders instead - * - * @param plugin The plugin to unregister - * @return always false - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static boolean unregisterPlaceholderHook(Plugin plugin) { - Msg.warn("Nag author(s) %s of plugin %s about their usage of the PlaceholderAPI class." - + " This way of unregistering placeholders is no longer supported and will be removed" - + " in v2.13.0!", plugin.getDescription().getAuthors(), plugin.getName()); - return false; - } - - /** - * @deprecated Please use {@link PlaceholderExpansion} to - * unregister placeholders instead - * - * @param identifier The identifier to unregister - * @return always false - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static boolean unregisterPlaceholderHook(String identifier) { - Msg.warn("%s is attempting to unregister placeholders via PlaceholderAPI class." - + " This way of unregistering placeholders is no longer supported and will be removed" - + " in v2.13.0!", identifier); - return false; - } - - /** - * @deprecated Will be removed in a future release. - * - * @return Set of registered identifiers - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static Set getRegisteredPlaceholderPlugins() { - return getRegisteredIdentifiers(); - } - - /** - * @deprecated Will be removed in a future release. - * - * @return always null - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static Set getExternalPlaceholderPlugins() { - return null; - } - - /** - * @deprecated Please use {@link #setPlaceholders(OfflinePlayer, String)} instead - * - * @param player The offline player to parse the placeholders against - * @param text The text to parse - * @param pattern The Pattern to use - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static String setPlaceholders(OfflinePlayer player, - String text, Pattern pattern, boolean colorize) { - return setPlaceholders(player, text); - } - - /** - * @deprecated Please use {@link #setPlaceholders(OfflinePlayer, List)} instead - * - * @param player The offline player to parse the placeholders against - * @param text The List of text to parse - * @param pattern The Pattern to use - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static List setPlaceholders(OfflinePlayer player, - List text, Pattern pattern, boolean colorize) { - return setPlaceholders(player, text); - } - - /** - * @deprecated Use {@link #setPlaceholders(OfflinePlayer, List)} instead. - * - * @param player The offline player to parse the placeholders against - * @param text The List of text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static List setPlaceholders(OfflinePlayer player, List text, - boolean colorize) { - return setPlaceholders(player, text); - } - - /** - * @deprecated Use {@link #setPlaceholders(OfflinePlayer, List)} instead. - * - * @param player The offline player to parse the placeholders against - * @param text The List of text to parse - * @param pattern The Pattern to use - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static List setPlaceholders(OfflinePlayer player, List text, - Pattern pattern) { - return setPlaceholders(player, text); - } - /** - * @deprecated Will be removed in a future release. - * - * @param player The offline player to parse the placeholders against - * @param text The text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static String setPlaceholders(Player player, String text, boolean colorize) { - return setPlaceholders(player, text); - } - - /** - * @deprecated Will be removed in a future release. - * - * @param player The offline player to parse the placeholders against - * @param text The List of text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static List setPlaceholders(Player player, List text, boolean colorize) { - return setPlaceholders(player, text); - } - - /** - * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. - * - * @param player The offline player to parse the placeholders against - * @param text The text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static String setPlaceholders(OfflinePlayer player, String text, boolean colorize) { - return setPlaceholders(player, text); - } - - /** - * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. - * - * @param player The offline player to parse the placeholders against - * @param text The text to parse - * @param pattern The Pattern to use - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static String setPlaceholders(OfflinePlayer player, String text, Pattern pattern) { - return setPlaceholders(player, text); - } - - /** - * @deprecated Use {@link #setPlaceholders(OfflinePlayer, List)} instead. - * - * @param player The offline player to parse the placeholders against - * @param text The List of text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static List setBracketPlaceholders(OfflinePlayer player, List text, - boolean colorize) { - return setBracketPlaceholders(player, text); - } - - /** - * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. - * - * @param player The offline player to parse the placeholders against - * @param text The text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static String setBracketPlaceholders(OfflinePlayer player, String text, boolean colorize) { - return setBracketPlaceholders(player, text); - } - - /** - * @deprecated Will be removed in a future release. - * - * @param player The offline player to parse the placeholders against - * @param text The text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static String setBracketPlaceholders(Player player, String text, boolean colorize) { - return setBracketPlaceholders(player, text); - } - - /** - * @deprecated Will be removed in a future release. - * - * @param player The offline player to parse the placeholders against - * @param text The List of text to parse - * @param colorize If PlaceholderAPI should also parse color codes - * @return String with the parsed placeholders - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static List setBracketPlaceholders(Player player, List text, - boolean colorize) { - return setBracketPlaceholders(player, text); - } - - /** - * set relational placeholders in the text specified placeholders are matched with the pattern - * {@literal %%} when set with this method - * - * @param one Player to compare - * @param two Player to compare - * @param text Text to parse the placeholders in - * @param colorize If color codes ({@literal &[0-1a-fk-o]}) should be translated - * @return The text containing the parsed relational placeholders - * @deprecated Use {@link #setPlaceholders(OfflinePlayer, String)} instead. - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static String setRelationalPlaceholders(Player one, Player two, String text, - boolean colorize) { - return setRelationalPlaceholders(one, two, text); - } - - /** - * Translate placeholders in the provided list based on the relation of the two provided players. - *
The pattern of a valid placeholder is {@literal %rel__%}. - * - * @param one First player to compare - * @param two Second player to compare - * @param text Text to parse the placeholders in - * @param colorize If color codes ({@literal &[0-1a-fk-o]}) should be translated - * @return The text containing the parsed relational placeholders - * @deprecated Use {@link #setRelationalPlaceholders(Player, Player, List)} instead. - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public static List setRelationalPlaceholders(Player one, Player two, List text, - boolean colorize) { - return setRelationalPlaceholders(one, two, text); - } -} diff --git a/src/main/java/me/clip/placeholderapi/PlaceholderAPIPlugin.java b/src/main/java/me/clip/placeholderapi/PlaceholderAPIPlugin.java deleted file mode 100644 index 76a26ce..0000000 --- a/src/main/java/me/clip/placeholderapi/PlaceholderAPIPlugin.java +++ /dev/null @@ -1,295 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi; - -import java.text.SimpleDateFormat; -import java.util.HashMap; -import java.util.Map; -import me.clip.placeholderapi.commands.PlaceholderCommandRouter; -import me.clip.placeholderapi.configuration.PlaceholderAPIConfig; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.clip.placeholderapi.expansion.Version; -import me.clip.placeholderapi.expansion.manager.CloudExpansionManager; -import me.clip.placeholderapi.expansion.manager.LocalExpansionManager; -import me.clip.placeholderapi.listeners.ServerLoadEventListener; -import me.clip.placeholderapi.scheduler.UniversalScheduler; -import me.clip.placeholderapi.scheduler.scheduling.schedulers.TaskScheduler; -import me.clip.placeholderapi.updatechecker.UpdateChecker; -import me.clip.placeholderapi.util.ExpansionSafetyCheck; -import me.clip.placeholderapi.util.Msg; -import net.kyori.adventure.platform.bukkit.BukkitAudiences; -import org.bstats.bukkit.Metrics; -import org.bstats.charts.AdvancedPie; -import org.bstats.charts.SimplePie; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.command.PluginCommand; -import org.bukkit.event.HandlerList; -import org.bukkit.plugin.java.JavaPlugin; -import org.jetbrains.annotations.NotNull; - -/** - * Yes I have a shit load of work to do... - * - * @author Ryan McCarthy - */ -public final class PlaceholderAPIPlugin extends JavaPlugin { - - @NotNull - private static final Version VERSION; - private static PlaceholderAPIPlugin instance; - - static { - String version = Bukkit.getServer().getBukkitVersion().split("-")[0]; - String suffix; - if (version.chars() - .filter(c -> c == '.') - .count() == 1) { - suffix = "R1"; - version = 'v' + version.replace('.', '_') + '_' + suffix; - } else { - int minor = Integer.parseInt(version.split("\\.")[2].charAt(0) + ""); - version = 'v' + version.replace('.', '_').replace("_" + minor, "") + '_' + "R" + (minor - 1); - } - - boolean isSpigot; - try { - Class.forName("org.spigotmc.SpigotConfig"); - isSpigot = true; - } catch (final ExceptionInInitializerError | ClassNotFoundException ignored) { - isSpigot = false; - } - - VERSION = new Version(version, isSpigot); - } - - @NotNull - private final PlaceholderAPIConfig config = new PlaceholderAPIConfig(this); - - @NotNull - private final LocalExpansionManager localExpansionManager = new LocalExpansionManager(this); - @NotNull - private final CloudExpansionManager cloudExpansionManager = new CloudExpansionManager(this); - @NotNull - private final TaskScheduler scheduler = UniversalScheduler.getScheduler(this); - - private BukkitAudiences adventure; - private boolean safetyCheck = false; - - - /** - * Gets the static instance of the main class for PlaceholderAPI. This class is not the actual API - * class, this is the main class that extends JavaPlugin. For most API methods, use static methods - * available from the class: {@link PlaceholderAPI} - * - * @return PlaceholderAPIPlugin instance - */ - @NotNull - public static PlaceholderAPIPlugin getInstance() { - return instance; - } - - /** - * Get the configurable {@linkplain String} value that should be returned when a boolean is true - * - * @return string value of true - */ - @NotNull - public static String booleanTrue() { - return getInstance().getPlaceholderAPIConfig().booleanTrue(); - } - - /** - * Get the configurable {@linkplain String} value that should be returned when a boolean is false - * - * @return string value of false - */ - @NotNull - public static String booleanFalse() { - return getInstance().getPlaceholderAPIConfig().booleanFalse(); - } - - /** - * Get the configurable {@linkplain SimpleDateFormat} object that is used to parse time for - * generic time based placeholders - * - * @return date format - */ - @NotNull - public static SimpleDateFormat getDateFormat() { - try { - return new SimpleDateFormat(getInstance().getPlaceholderAPIConfig().dateFormat()); - } catch (final IllegalArgumentException ex) { - Msg.warn("Configured date format ('%s') is invalid! Defaulting to 'MM/dd/yy HH:mm:ss'", - ex, getInstance().getPlaceholderAPIConfig().dateFormat()); - return new SimpleDateFormat("MM/dd/yy HH:mm:ss"); - } - } - - @Deprecated - public static Version getServerVersion() { - return VERSION; - } - - @Override - public void onLoad() { - saveDefaultConfig(); - - safetyCheck = new ExpansionSafetyCheck(this).runChecks(); - - if (safetyCheck) { - return; - } - - instance = this; - } - - @Override - public void onEnable() { - if (safetyCheck) { - return; - } - - setupCommand(); - setupMetrics(); - setupExpansions(); - - adventure = BukkitAudiences.create(this); - - if (config.isCloudEnabled()) { - getCloudExpansionManager().load(); - } - - if (config.checkUpdates()) { - new UpdateChecker(this).fetch(); - } - } - - @Override - public void onDisable() { - if (safetyCheck) { - return; - } - - getCloudExpansionManager().kill(); - getLocalExpansionManager().kill(); - - HandlerList.unregisterAll(this); - - scheduler.cancelTasks(this); - - adventure.close(); - adventure = null; - - instance = null; - } - - public void reloadConf(@NotNull final CommandSender sender) { - getLocalExpansionManager().kill(); - - reloadConfig(); - - getLocalExpansionManager().load(sender); - - if (config.isCloudEnabled()) { - getCloudExpansionManager().load(); - } else { - getCloudExpansionManager().kill(); - } - } - - @NotNull - public LocalExpansionManager getLocalExpansionManager() { - return localExpansionManager; - } - - @NotNull - public CloudExpansionManager getCloudExpansionManager() { - return cloudExpansionManager; - } - - @NotNull - public BukkitAudiences getAdventure() { - if(adventure == null) { - throw new IllegalStateException("Tried to access Adventure when the plugin was disabled!"); - } - - return adventure; - } - - @NotNull - public TaskScheduler getScheduler() { - return scheduler; - } - - /** - * Obtain the configuration class for PlaceholderAPI. - * - * @return PlaceholderAPIConfig instance - */ - @NotNull - public PlaceholderAPIConfig getPlaceholderAPIConfig() { - return config; - } - - private void setupCommand() { - final PluginCommand pluginCommand = getCommand("placeholderapi"); - if (pluginCommand == null) { - return; - } - - final PlaceholderCommandRouter router = new PlaceholderCommandRouter(this); - pluginCommand.setExecutor(router); - pluginCommand.setTabCompleter(router); - } - - private void setupMetrics() { - final Metrics metrics = new Metrics(this, 438); - metrics.addCustomChart(new SimplePie("using_expansion_cloud", - () -> getPlaceholderAPIConfig().isCloudEnabled() ? "yes" : "no")); - - metrics.addCustomChart(new SimplePie("using_spigot", () -> getServerVersion().isSpigot() ? "yes" : "no")); - - metrics.addCustomChart(new AdvancedPie("expansions_used", () -> { - final Map values = new HashMap<>(); - - for (final PlaceholderExpansion expansion : getLocalExpansionManager().getExpansions()) { - values.put(expansion.getRequiredPlugin() == null ? expansion.getIdentifier() - : expansion.getRequiredPlugin(), 1); - } - - return values; - })); - } - - private void setupExpansions() { - Bukkit.getPluginManager().registerEvents(getLocalExpansionManager(), this); - - try { - Class.forName("org.bukkit.event.server.ServerLoadEvent"); - new ServerLoadEventListener(this); - } catch (final ClassNotFoundException ignored) { - scheduler - .runTaskLater(() -> getLocalExpansionManager().load(Bukkit.getConsoleSender()), 1); - } - } - -} diff --git a/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommand.java b/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommand.java deleted file mode 100644 index 8136168..0000000 --- a/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommand.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.commands; - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Sets; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.stream.Stream; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.annotations.Unmodifiable; - -public abstract class PlaceholderCommand { - - @NotNull - private final String label; - @NotNull - private final Set alias; - - @Nullable - private String permission; - - - protected PlaceholderCommand(@NotNull final String label, @NotNull final String... alias) { - this.label = label; - this.alias = Sets.newHashSet(alias); - - setPermission("placeholderapi." + label); - } - - @NotNull - public static Stream filterByPermission(@NotNull final CommandSender sender, - @NotNull final Stream commands) { - return commands.filter( - target -> target.getPermission() == null || sender.hasPermission(target.getPermission())); - } - - public static void suggestByParameter(@NotNull final Stream possible, - @NotNull final List suggestions, @Nullable final String parameter) { - if (parameter == null) { - possible.forEach(suggestions::add); - } else { - possible.filter(suggestion -> suggestion.toLowerCase(Locale.ROOT).startsWith(parameter.toLowerCase(Locale.ROOT))) - .forEach(suggestions::add); - } - } - - @NotNull - public final String getLabel() { - return label; - } - - @NotNull - @Unmodifiable - public final Set getAlias() { - return ImmutableSet.copyOf(alias); - } - - @NotNull - @Unmodifiable - public final Set getLabels() { - return ImmutableSet.builder().add(label).addAll(alias).build(); - } - - @Nullable - public final String getPermission() { - return permission; - } - - public void setPermission(@NotNull final String permission) { - this.permission = permission; - } - - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - - } - - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - - } - -} diff --git a/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommandRouter.java b/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommandRouter.java deleted file mode 100644 index 7ea3f42..0000000 --- a/src/main/java/me/clip/placeholderapi/commands/PlaceholderCommandRouter.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.commands; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.stream.Stream; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.commands.impl.cloud.CommandECloud; -import me.clip.placeholderapi.commands.impl.local.CommandDump; -import me.clip.placeholderapi.commands.impl.local.CommandExpansionRegister; -import me.clip.placeholderapi.commands.impl.local.CommandExpansionUnregister; -import me.clip.placeholderapi.commands.impl.local.CommandHelp; -import me.clip.placeholderapi.commands.impl.local.CommandInfo; -import me.clip.placeholderapi.commands.impl.local.CommandList; -import me.clip.placeholderapi.commands.impl.local.CommandParse; -import me.clip.placeholderapi.commands.impl.local.CommandReload; -import me.clip.placeholderapi.commands.impl.local.CommandVersion; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabCompleter; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Unmodifiable; - -public final class PlaceholderCommandRouter implements CommandExecutor, TabCompleter { - - @Unmodifiable - private static final List COMMANDS = ImmutableList.of(new CommandHelp(), - new CommandInfo(), - new CommandList(), - new CommandDump(), - new CommandECloud(), - new CommandParse(), - new CommandReload(), - new CommandVersion(), - new CommandExpansionRegister(), - new CommandExpansionUnregister()); - - - @NotNull - private final PlaceholderAPIPlugin plugin; - @NotNull - @Unmodifiable - private final Map commands; - - - public PlaceholderCommandRouter(@NotNull final PlaceholderAPIPlugin plugin) { - this.plugin = plugin; - - final ImmutableMap.Builder commands = ImmutableMap.builder(); - - for (final PlaceholderCommand command : COMMANDS) { - command.getLabels().forEach(label -> commands.put(label, command)); - } - - this.commands = commands.build(); - } - - - @Override - public boolean onCommand(@NotNull final CommandSender sender, @NotNull final Command command, - @NotNull final String alias, @NotNull final String[] args) { - if (args.length == 0) { - final PlaceholderCommand fallback = commands.get("version"); - if (fallback != null) { - fallback.evaluate(plugin, sender, "", Collections.emptyList()); - } - - return true; - } - - final String search = args[0].toLowerCase(Locale.ROOT); - final PlaceholderCommand target = commands.get(search); - - if (target == null) { - Msg.msg(sender, "&cUnknown command &7" + search); - return true; - } - - final String permission = target.getPermission(); - if (permission != null && !permission.isEmpty() && !sender.hasPermission(permission)) { - Msg.msg(sender, "&cYou do not have permission to do this!"); - return true; - } - - target - .evaluate(plugin, sender, search, Arrays.asList(Arrays.copyOfRange(args, 1, args.length))); - - return true; - } - - @Override - public List onTabComplete(@NotNull final CommandSender sender, - @NotNull final Command command, @NotNull final String alias, @NotNull final String[] args) { - final List suggestions = new ArrayList<>(); - - if (args.length > 1) { - final PlaceholderCommand target = this.commands.get(args[0].toLowerCase(Locale.ROOT)); - - if (target != null) { - target.complete(plugin, sender, args[0].toLowerCase(Locale.ROOT), - Arrays.asList(Arrays.copyOfRange(args, 1, args.length)), suggestions); - } - - return suggestions; - } - - final Stream targets = PlaceholderCommand - .filterByPermission(sender, commands.values().stream()).map(PlaceholderCommand::getLabels) - .flatMap(Collection::stream); - PlaceholderCommand.suggestByParameter(targets, suggestions, args.length == 0 ? null : args[0]); - - return suggestions; - } - -} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloud.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloud.java deleted file mode 100644 index 4d03de1..0000000 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloud.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.cloud; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.commands.PlaceholderCommand; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Unmodifiable; - -import java.util.Collection; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.stream.Stream; - -public final class CommandECloud extends PlaceholderCommand { - - @Unmodifiable - private static final List COMMANDS = ImmutableList - .of(new CommandECloudClear(), - new CommandECloudStatus(), - new CommandECloudUpdate(), - new CommandECloudRefresh(), - new CommandECloudDownload(), - new CommandECloudExpansionInfo(), - new CommandECloudExpansionList(), - new CommandECloudExpansionPlaceholders()); - - static { - COMMANDS - .forEach(command -> command.setPermission("placeholderapi.ecloud." + command.getLabel())); - } - - @NotNull - @Unmodifiable - private final Map commands; - - - public CommandECloud() { - super("ecloud"); - - final ImmutableMap.Builder commands = ImmutableMap.builder(); - - for (final PlaceholderCommand command : COMMANDS) { - command.getLabels().forEach(label -> commands.put(label, command)); - } - - this.commands = commands.build(); - } - - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&b&lPlaceholderAPI &8- &7eCloud Help Menu &8- ", - " ", - "&b/papi &fecloud status", - " &7&oView status of the eCloud", - "&b/papi &fecloud list {page}", - " &7&oList all/author specific available expansions", - "&b/papi &fecloud info {version}", - " &7&oView information about a specific expansion available on the eCloud", - "&b/papi &fecloud placeholders ", - " &7&oView placeholders for an expansion", - "&b/papi &fecloud download {version}", - " &7&oDownload an expansion from the eCloud", - "&b/papi &fecloud update ", - " &7&oUpdate a specific/all installed expansions", - "&b/papi &fecloud refresh", - " &7&oFetch the most up to date list of expansions available.", - "&b/papi &fecloud clear", - " &7&oClear the expansion cloud cache."); - - return; - } - - final String search = params.get(0).toLowerCase(Locale.ROOT); - final PlaceholderCommand target = commands.get(search); - - if (target == null) { - Msg.msg(sender, "&cUnknown command &7ecloud " + search); - return; - } - - final String permission = target.getPermission(); - if (permission != null && !permission.isEmpty() && !sender.hasPermission(permission)) { - Msg.msg(sender, "&cYou do not have permission to do this!"); - return; - } - - if (!plugin.getPlaceholderAPIConfig().isCloudEnabled()) { - Msg.msg(sender, "&cThe eCloud Manager is not enabled! To enable it, set 'cloud_enabled' to true and reload the plugin."); - return; - } - - target.evaluate(plugin, sender, search, params.subList(1, params.size())); - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() <= 1) { - final Stream targets = filterByPermission(sender, commands.values().stream()) - .map(PlaceholderCommand::getLabels).flatMap(Collection::stream); - suggestByParameter(targets, suggestions, params.isEmpty() ? null : params.get(0)); - - return; // send sub commands - } - - final String search = params.get(0).toLowerCase(Locale.ROOT); - final PlaceholderCommand target = commands.get(search); - - if (target == null) { - return; - } - - target.complete(plugin, sender, search, params.subList(1, params.size()), suggestions); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudDownload.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudDownload.java deleted file mode 100644 index 7d8b083..0000000 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudDownload.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.cloud; - -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.stream.Stream; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.commands.PlaceholderCommand; -import me.clip.placeholderapi.expansion.cloud.CloudExpansion; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Unmodifiable; - -public final class CommandECloudDownload extends PlaceholderCommand { - - public CommandECloudDownload() { - super("download"); - } - - private boolean isBlockedExpansion(String name) { - String env = System.getenv("PAPI_BLOCKED_EXPANSIONS"); - if (env == null) { - return false; - } - - return Arrays.stream(env.split(",")) - .anyMatch(s -> s.equalsIgnoreCase(name)); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&cYou must supply the name of an expansion."); - return; - } - - if (isBlockedExpansion(params.get(0))) { - Msg.msg(sender, - "&cThis expansion can't be downloaded."); - return; - } - - final CloudExpansion expansion = plugin.getCloudExpansionManager() - .findCloudExpansionByName(params.get(0)).orElse(null); - if (expansion == null) { - Msg.msg(sender, - "&cFailed to find an expansion named: &f" + params.get(0)); - return; - } - - final CloudExpansion.Version version; - if (params.size() < 2) { - version = expansion.getVersion(expansion.getLatestVersion()); - if (version == null) { - Msg.msg(sender, - "&cCould not find latest version for expansion."); - return; - } - } else { - version = expansion.getVersion(params.get(1)); - if (version == null) { - Msg.msg(sender, - "&cCould not find specified version: &f" + params.get(1), - "&7Available versions: &f" + expansion.getAvailableVersions()); - return; - } - } - - if (!version.isVerified()) { - Msg.msg(sender, "&cThe expansion '&f" + params.get(0) + "&c' is not verified and can only be downloaded manually from &fhttps://ecloud.placeholderapi.com"); - return; - } - - plugin.getCloudExpansionManager().downloadExpansion(expansion, version) - .whenComplete((file, exception) -> { - if (exception != null) { - Msg.msg(sender, - "&cFailed to download expansion: &f" + exception.getMessage()); - return; - } - - Msg.msg(sender, - "&aSuccessfully downloaded expansion &f" + expansion.getName() + " [" + version - .getVersion() + "] &ato file: &f" + file.getName(), - "&aMake sure to type &f/papi reload &ato enable your new expansion!"); - - plugin.getCloudExpansionManager().load(); - }); - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 2) { - return; - } - - if (params.size() <= 1) { - final Stream names = plugin.getCloudExpansionManager().getCloudExpansions().values() - .stream().map(CloudExpansion::getName).map(name -> name.replace(' ', '_')); - suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); - return; - } - - final Optional expansion = plugin.getCloudExpansionManager() - .findCloudExpansionByName(params.get(0)); - if (!expansion.isPresent()) { - return; - } - - suggestByParameter(expansion.get().getAvailableVersions().stream(), suggestions, params.get(1)); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionInfo.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionInfo.java deleted file mode 100644 index 4eaea91..0000000 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionInfo.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.cloud; - -import java.util.List; -import java.util.Optional; -import java.util.stream.Stream; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.commands.PlaceholderCommand; -import me.clip.placeholderapi.expansion.cloud.CloudExpansion; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Unmodifiable; - -public final class CommandECloudExpansionInfo extends PlaceholderCommand { - - public CommandECloudExpansionInfo() { - super("info"); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&cYou must specify the name of the expansion."); - return; - } - - final CloudExpansion expansion = plugin.getCloudExpansionManager() - .findCloudExpansionByName(params.get(0)).orElse(null); - if (expansion == null) { - Msg.msg(sender, - "&cThere is no expansion with the name: &f" + params.get(0)); - return; - } - - final StringBuilder builder = new StringBuilder(); - - builder.append("&bExpansion: &f") - .append(expansion.shouldUpdate() ? "&e" : "&a") - .append(expansion.getName()) - .append('\n') - .append("&bAuthor: &f") - .append(expansion.getAuthor()) - .append('\n'); - - if (params.size() < 2) { - builder.append("&bLatest Version: &f") - .append(expansion.getLatestVersion()) - .append('\n') - .append("&bReleased: &f") - .append(expansion.getTimeSinceLastUpdate()) - .append(" ago") - .append('\n') - .append("&bVerified: ") - .append(expansion.getVersion().isVerified() ? "&a&l✔" : "&c&l❌") - .append('\n') - .append("&bRelease Notes: &f") - .append(expansion.getVersion().getReleaseNotes()) - .append('\n'); - } else { - final CloudExpansion.Version version = expansion.getVersion(params.get(1)); - if (version == null) { - Msg.msg(sender, - "&cCould not find specified version: &f" + params.get(1), - "&aVersions: &f" + expansion.getAvailableVersions()); - return; - } - - builder.append("&bVersion: &f") - .append(version.getVersion()) - .append('\n') - .append("&bVerified: ") - .append(version.isVerified() ? "&a&l✔" : "&c&l❌") - .append('\n') - .append("&bRelease Notes: &f") - .append(version.getReleaseNotes()) - .append('\n') - .append("&bDownload URL: &f") - .append(version.getUrl()) - .append('\n'); - } - - Msg.msg(sender, builder.toString()); - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 2) { - return; - } - - if (params.size() <= 1) { - final Stream names = plugin.getCloudExpansionManager().getCloudExpansions().values() - .stream().map(CloudExpansion::getName).map(name -> name.replace(' ', '_')); - suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); - return; - } - - final Optional expansion = plugin.getCloudExpansionManager() - .findCloudExpansionByName(params.get(0)); - if (!expansion.isPresent()) { - return; - } - - suggestByParameter(expansion.get().getAvailableVersions().stream(), suggestions, params.get(1)); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionList.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionList.java deleted file mode 100644 index 551ba50..0000000 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionList.java +++ /dev/null @@ -1,352 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.cloud; - -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import com.google.common.primitives.Ints; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.commands.PlaceholderCommand; -import me.clip.placeholderapi.configuration.ExpansionSort; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.clip.placeholderapi.expansion.cloud.CloudExpansion; -import me.clip.placeholderapi.util.Format; -import me.clip.placeholderapi.util.Msg; -import net.kyori.adventure.text.Component; -import net.kyori.adventure.text.TextComponent; -import net.kyori.adventure.text.event.ClickEvent; -import net.kyori.adventure.text.event.HoverEvent; -import net.kyori.adventure.text.format.NamedTextColor; -import net.kyori.adventure.text.format.TextDecoration; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Unmodifiable; - -import static net.kyori.adventure.text.Component.*; -import static net.kyori.adventure.text.format.NamedTextColor.*; - -public final class CommandECloudExpansionList extends PlaceholderCommand { - - private static final int PAGE_SIZE = 10; - - @NotNull - private static final Function EXPANSION_NAME = - expansion -> (expansion.shouldUpdate() ? "&6" : expansion.hasExpansion() ? "&a" : "&7") - + expansion.getName(); - @NotNull - private static final Function EXPANSION_AUTHOR = - expansion -> "&f" + expansion.getAuthor(); - @NotNull - private static final Function EXPANSION_VERIFIED = - expansion -> expansion.getVersion().isVerified() ? "&aY" : "&cN"; - @NotNull - private static final Function EXPANSION_LATEST_VERSION = - expansion -> "&f" + expansion.getLatestVersion(); - @NotNull - private static final Function EXPANSION_CURRENT_VERSION = - expansion -> "&f" + PlaceholderAPIPlugin.getInstance().getLocalExpansionManager() - .findExpansionByName(expansion.getName()).map(PlaceholderExpansion::getVersion) - .orElse("Unknown"); - - - @Unmodifiable - private static final Set OPTIONS = ImmutableSet.of("all", "installed"); - - - public CommandECloudExpansionList() { - super("list"); - } - - @NotNull - private static Collection getExpansions(@NotNull final String target, - @NotNull final PlaceholderAPIPlugin plugin) { - switch (target.toLowerCase(Locale.ROOT)) { - case "all": - return plugin.getCloudExpansionManager().getCloudExpansions().values(); - case "installed": - return plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values(); - default: - return plugin.getCloudExpansionManager().getCloudExpansionsByAuthor(target).values(); - } - } - - @NotNull - private static List getPage(@NotNull final List expansions, - final int page) { - final int head = (page * PAGE_SIZE); - final int tail = Math.min(expansions.size(), head + PAGE_SIZE); - - if (expansions.size() < head) { - return Collections.emptyList(); - } - - return expansions.subList(head, tail); - } - - public static void addExpansionTitle(@NotNull final StringBuilder builder, - @NotNull final String target, final int page) { - switch (target.toLowerCase(Locale.ROOT)) { - case "all": - builder.append("&bAll Expansions"); - break; - case "installed": - builder.append("&bInstalled Expansions"); - break; - default: - builder.append("&bExpansions by &f") - .append(target); - break; - } - - if (page == -1) { - builder.append('\n'); - return; - } - - builder.append(" &bPage&7: &a") - .append(page) - .append("&r"); - } - - private static Component getMessage(@NotNull final List expansions, - final int page, final int limit, @NotNull final String target) { - final SimpleDateFormat format = PlaceholderAPIPlugin.getDateFormat(); - - final TextComponent.Builder message = text(); - - for (int index = 0; index < expansions.size(); index++) { - final CloudExpansion expansion = expansions.get(index); - final TextComponent.Builder line = text(); - - final int expansionNumber = index + ((page - 1) * PAGE_SIZE) + 1; - line.append(text(expansionNumber + ". ", DARK_GRAY)); - - final NamedTextColor expansionColour; - - if (expansion.shouldUpdate()) { - expansionColour = GOLD; - } else { - if (expansion.hasExpansion()) { - expansionColour = GREEN; - } else { - expansionColour = GRAY; - } - } - - line.append(text(expansion.getName(), expansionColour)); - - line.clickEvent(ClickEvent.suggestCommand("/papi ecloud download " + expansion.getName())); - - final TextComponent.Builder hoverText = text("Click to download this expansion!", AQUA) - .append(newline()).append(newline()) - .append(text("Author: ", AQUA)).append(text(expansion.getAuthor(), WHITE)) - .append(newline()) - .append(text("Verified: ", AQUA)).append(text(expansion.getVersion().isVerified() ? "✔" : "❌", expansion.getVersion().isVerified() ? GREEN : RED, TextDecoration.BOLD)) - .append(newline()) - .append(text("Released: ", AQUA)).append(text(format.format(expansion.getLastUpdate()), WHITE)) - .toBuilder(); - - Optional.ofNullable(expansion.getDescription()) - .filter(description -> !description.isEmpty()) - .ifPresent(description -> hoverText.append(newline()).append(newline()) - .append(text(description.replace("\r", "").trim(), WHITE)) - ); - - line.hoverEvent(HoverEvent.showText(hoverText.build())); - - if (index != expansions.size() - 1) { - line.append(newline()); - } - - message.append(line.build()); - } - - if (limit > 1) { - message.append(newline()); - - final TextComponent.Builder left = text("◀", page > 1 ? GRAY : DARK_GRAY).toBuilder(); - - if (page > 1) { - left.clickEvent(ClickEvent.runCommand("/papi ecloud list " + target + " " + (page - 1))); - } - - final TextComponent.Builder right = text("▶", page < limit ? GRAY : DARK_GRAY).toBuilder(); - - if (page < limit) { - right.clickEvent(ClickEvent.runCommand("/papi ecloud list " + target + " " + (page + 1))); - } - - message.append(left, text(" " + page + " ", GREEN), right); - } - - return message.build(); - } - - private static void addExpansionTable(@NotNull final List expansions, - @NotNull final StringBuilder message, final int startIndex, - @NotNull final String versionTitle, - @NotNull final Function versionFunction) { - final Map> functions = new LinkedHashMap<>(); - - final AtomicInteger counter = new AtomicInteger(startIndex); - functions.put("&f", expansion -> "&8" + counter.getAndIncrement() + "."); - - functions.put("&9Name", EXPANSION_NAME); - functions.put("&9Author", EXPANSION_AUTHOR); - functions.put("&9Verified", EXPANSION_VERIFIED); - functions.put(versionTitle, versionFunction); - - final List> rows = new ArrayList<>(); - - rows.add(0, new ArrayList<>(functions.keySet())); - - for (final CloudExpansion expansion : expansions) { - rows.add(functions.values().stream().map(function -> function.apply(expansion)) - .map(Objects::toString).collect(Collectors.toList())); - } - - final List table = Format.tablify(Format.Align.LEFT, rows) - .orElse(Collections.emptyList()); - if (table.isEmpty()) { - return; - } - - table.add(1, "&8" + Strings.repeat("-", table.get(0).length() - (rows.get(0).size() * 2))); - - message.append(String.join("\n", table)); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&cYou must specify an option. [all, {author}, installed]"); - return; - } - - final boolean installed = params.get(0).equalsIgnoreCase("installed"); - final List expansions = Lists - .newArrayList(getExpansions(params.get(0), plugin)); - - if (expansions.isEmpty()) { - Msg.msg(sender, - "&cNo expansions available to list."); - return; - } - - expansions - .sort(plugin.getPlaceholderAPIConfig().getExpansionSort().orElse(ExpansionSort.LATEST)); - - if (!(sender instanceof Player) && params.size() < 2) { - final StringBuilder builder = new StringBuilder(); - - addExpansionTitle(builder, params.get(0), -1); - addExpansionTable(expansions, - builder, - 1, - installed ? "&9Version" : "&9Latest Version", - installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION); - - Msg.msg(sender, builder.toString()); - return; - } - - final int page; - - if (params.size() < 2) { - page = 1; - } else { - //noinspection UnstableApiUsage - final Integer parsed = Ints.tryParse(params.get(1)); - if (parsed == null) { - Msg.msg(sender, - "&cPage number must be an integer."); - return; - } - - final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE); - - if (parsed < 1 || parsed > limit) { - Msg.msg(sender, - "&cPage number must be in the range &8[&a1&7..&a" + limit + "&8]"); - return; - } - - page = parsed; - } - - final StringBuilder builder = new StringBuilder(); - final List values = getPage(expansions, page - 1); - - addExpansionTitle(builder, params.get(0), page); - - if (!(sender instanceof Player)) { - addExpansionTable(values, - builder, - ((page - 1) * PAGE_SIZE) + 1, - installed ? "&9Version" : "&9Latest Version", - installed ? EXPANSION_CURRENT_VERSION : EXPANSION_LATEST_VERSION); - - Msg.msg(sender, builder.toString()); - - return; - } - - Msg.msg(sender, builder.toString()); - - final int limit = (int) Math.ceil((double) expansions.size() / PAGE_SIZE); - - final Component message = getMessage(values, page, limit, params.get(0)); - plugin.getAdventure().player((Player) sender).sendMessage(message); - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 2) { - return; - } - - if (params.size() <= 1) { - suggestByParameter( - Sets.union(OPTIONS, plugin.getCloudExpansionManager().getCloudExpansionAuthors()) - .stream(), suggestions, params.isEmpty() ? null : params.get(0)); - return; - } - - suggestByParameter(IntStream.rangeClosed(1, - (int) Math.ceil((double) getExpansions(params.get(0), plugin).size() / PAGE_SIZE)) - .mapToObj(Objects::toString), suggestions, params.get(1)); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionPlaceholders.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionPlaceholders.java deleted file mode 100644 index f379365..0000000 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudExpansionPlaceholders.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.cloud; - -import com.google.common.collect.Lists; -import java.util.List; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.commands.PlaceholderCommand; -import me.clip.placeholderapi.expansion.cloud.CloudExpansion; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Unmodifiable; - -public final class CommandECloudExpansionPlaceholders extends PlaceholderCommand { - - public CommandECloudExpansionPlaceholders() { - super("placeholders"); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&cYou must specify the name of the expansion."); - return; - } - - final CloudExpansion expansion = plugin.getCloudExpansionManager() - .findCloudExpansionByName(params.get(0)).orElse(null); - if (expansion == null) { - Msg.msg(sender, - "&cThere is no expansion with the name: &f" + params.get(0)); - return; - } - - final List placeholders = expansion.getPlaceholders(); - if (placeholders == null || placeholders.isEmpty()) { - Msg.msg(sender, - "&cThe expansion specified does not have placeholders listed."); - return; - } - - final List> partitions = Lists - .partition(placeholders.stream().sorted().collect(Collectors.toList()), 10); - - Msg.msg(sender, - "&6" + placeholders.size() + "&7 placeholders: &a", - partitions.stream().map(partition -> String.join(", ", partition)) - .collect(Collectors.joining("\n"))); - - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 1) { - return; - } - - final Stream names = plugin.getCloudExpansionManager() - .getCloudExpansions() - .values() - .stream() - .map(CloudExpansion::getName) - .map(name -> name.replace(' ', '_')); - - suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudStatus.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudStatus.java deleted file mode 100644 index b9b7ee6..0000000 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudStatus.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.cloud; - -import java.util.List; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.commands.PlaceholderCommand; -import me.clip.placeholderapi.expansion.manager.CloudExpansionManager; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Unmodifiable; - -public final class CommandECloudStatus extends PlaceholderCommand { - - public CommandECloudStatus() { - super("status"); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - final CloudExpansionManager manager = plugin.getCloudExpansionManager(); - - final int updateCount = manager.getCloudUpdateCount(); - final int authorCount = manager.getCloudExpansionAuthorCount(); - final int expansionCount = manager.getCloudExpansions().size(); - - final StringBuilder builder = new StringBuilder(); - - builder.append("&bThere are &a").append(expansionCount) - .append("&b expansions available on the eCloud.").append('\n'); - builder.append("&7A total of &f").append(authorCount) - .append("&7 authors have contributed to the eCloud.").append('\n'); - - if (updateCount > 0) { - builder.append("&eYou have &f").append(updateCount) - .append(updateCount > 1 ? "&e expansions" : "&e expansion").append(" installed that ") - .append(updateCount > 1 ? "have an" : "has an").append(" update available."); - } - - Msg.msg(sender, builder.toString()); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudUpdate.java b/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudUpdate.java deleted file mode 100644 index 4aa8454..0000000 --- a/src/main/java/me/clip/placeholderapi/commands/impl/cloud/CommandECloudUpdate.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.cloud; - -import com.google.common.collect.Lists; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.CompletableFuture; -import java.util.stream.Collectors; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.commands.PlaceholderCommand; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.clip.placeholderapi.expansion.cloud.CloudExpansion; -import me.clip.placeholderapi.util.Futures; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.annotations.Unmodifiable; - -/** - * please don't flame me for this code, I will fix this shit later. - */ -public final class CommandECloudUpdate extends PlaceholderCommand { - - public CommandECloudUpdate() { - super("update"); - } - - private static CompletableFuture>> downloadAndDiscover( - @NotNull final List expansions, @NotNull final PlaceholderAPIPlugin plugin) { - return expansions.stream() - .map(expansion -> plugin.getCloudExpansionManager() - .downloadExpansion(expansion, expansion.getVersion())) - .map(future -> future.thenCompose(plugin.getLocalExpansionManager()::findExpansionInFile)) - .collect(Futures.collector()); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&cYou must define 'all' or the name of an expansion to update."); - return; - } - - final boolean multiple = params.get(0).equalsIgnoreCase("all"); - final List expansions = new ArrayList<>(); - - // gather target expansions - if (multiple) { - expansions.addAll(plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values()); - } else { - plugin.getCloudExpansionManager().findCloudExpansionByName(params.get(0)) - .ifPresent(expansions::add); - } - - // remove the ones that are the latest version - expansions.removeIf(expansion -> !expansion.shouldUpdate()); - - if (expansions.isEmpty()) { - Msg.msg(sender, - "&cNo updates available for " + (!multiple ? "this expansion." - : "your active expansions.")); - return; - } - - Msg.msg(sender, - "&aUpdating expansions: " + expansions.stream().map(CloudExpansion::getName) - .collect(Collectors.joining("&7, &6", "&8[&6", "&8]&r"))); - - Futures.onMainThread(plugin, downloadAndDiscover(expansions, plugin), (classes, exception) -> { - if (exception != null) { - Msg.msg(sender, - "&cFailed to update expansions: &e" + exception.getMessage()); - return; - } - - Msg.msg(sender, - "&aSuccessfully downloaded updates, registering new versions."); - - final String message = classes.stream() - .filter(Objects::nonNull) - .map(plugin.getLocalExpansionManager()::register) - .filter(Optional::isPresent) - .map(Optional::get) - .map(expansion -> " &a" + expansion.getName() + " &f" + expansion.getVersion()) - .collect(Collectors.joining("\n")); - - Msg.msg(sender, - "&7Registered expansions:", message); - - }); - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 1) { - return; - } - - final List installed = Lists - .newArrayList(plugin.getCloudExpansionManager().getCloudExpansionsInstalled().values()); - installed.removeIf(expansion -> !expansion.shouldUpdate()); - - if (!installed.isEmpty() && (params.isEmpty() || "all" - .startsWith(params.get(0).toLowerCase(Locale.ROOT)))) { - suggestions.add("all"); - } - - suggestByParameter( - installed.stream().map(CloudExpansion::getName).map(name -> name.replace(" ", "_")), - suggestions, params.isEmpty() ? null : params.get(0)); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandDump.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandDump.java deleted file mode 100644 index f9d848a..0000000 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandDump.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.local; - -import com.google.common.io.CharStreams; -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.commands.PlaceholderCommand; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.command.CommandSender; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Unmodifiable; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.time.Instant; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.time.format.FormatStyle; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; -import java.util.Locale; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; -import java.util.logging.Level; -import java.util.stream.Collectors; - -public final class CommandDump extends PlaceholderCommand { - - @NotNull - private static final String URL = "https://paste.helpch.at/"; - - @NotNull - private static final Gson gson = new Gson(); - - @NotNull - private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter - .ofLocalizedDateTime(FormatStyle.LONG) - .withLocale(Locale.US) - .withZone(ZoneId.of("UTC")); - - - public CommandDump() { - super("dump"); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - postDump(makeDump(plugin)).whenComplete((key, exception) -> { - if (exception != null) { - plugin.getLogger().log(Level.WARNING, "failed to post dump details", exception); - - Msg.msg(sender, - "&cFailed to post dump details, check console."); - return; - } - - Msg.msg(sender, - "&aSuccessfully posted dump: " + URL + key); - }); - } - - @NotNull - private CompletableFuture postDump(@NotNull final String dump) { - return CompletableFuture.supplyAsync(() -> { - try { - final HttpURLConnection connection = ((HttpURLConnection) new URL(URL + "documents") - .openConnection()); - connection.setRequestMethod("POST"); - connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); - connection.setDoOutput(true); - - connection.connect(); - - try (final OutputStream stream = connection.getOutputStream()) { - stream.write(dump.getBytes(StandardCharsets.UTF_8)); - } - - try (final InputStream stream = connection.getInputStream()) { - final String json = CharStreams.toString(new InputStreamReader(stream, StandardCharsets.UTF_8)); - return gson.fromJson(json, JsonObject.class).get("key").getAsString(); - } - } catch (final IOException ex) { - throw new CompletionException(ex); - } - }); - } - - @NotNull - private String makeDump(@NotNull final PlaceholderAPIPlugin plugin) { - final StringBuilder builder = new StringBuilder(); - - builder.append("Generated: ") - .append(DATE_FORMAT.format(Instant.now())) - .append("\n\n"); - - builder.append("PlaceholderAPI: ") - .append(plugin.getDescription().getVersion()) - .append("\n\n"); - - builder.append("Expansions Registered:") - .append('\n'); - - final List expansions = plugin.getLocalExpansionManager() - .getExpansions() - .stream() - .sorted( - Comparator.comparing(PlaceholderExpansion::getIdentifier) - .thenComparing(PlaceholderExpansion::getAuthor) - ) - .collect(Collectors.toList()); - - int size = expansions.stream().map(e -> e.getIdentifier().length()) - .max(Integer::compareTo) - .orElse(0); - - for (final PlaceholderExpansion expansion : expansions) { - builder.append(" ") - .append(String.format("%-" + size + "s", expansion.getIdentifier())) - .append(" [Author: ") - .append(expansion.getAuthor()) - .append(", Version: ") - .append(expansion.getVersion()) - .append("]\n"); - - } - - builder.append('\n'); - - builder.append("Expansions Directory:") - .append('\n'); - - final String[] jars = plugin.getLocalExpansionManager() - .getExpansionsFolder() - .list((dir, name) -> name.toLowerCase(Locale.ROOT).endsWith(".jar")); - - - if (jars == null) { - builder.append(" ¨[Warning]: Could not load jar files from expansions folder."); - } else { - for (final String jar : jars) { - builder.append(" ") - .append(jar) - .append('\n'); - } - } - - builder.append('\n'); - - builder.append("Server Info: ") - .append(plugin.getServer().getBukkitVersion()) - .append('/') - .append(plugin.getServer().getVersion()) - .append("\n"); - - builder.append("Java Version: ") - .append(System.getProperty("java.version")) - .append("\n\n"); - - builder.append("Plugin Info:") - .append('\n'); - - List plugins = Arrays.stream(plugin.getServer().getPluginManager().getPlugins()) - .sorted(Comparator.comparing(Plugin::getName)) - .collect(Collectors.toList()); - - size = plugins.stream().map(pl -> pl.getName().length()) - .max(Integer::compareTo) - .orElse(0); - - for (final Plugin other : plugins) { - builder.append(" ") - .append(String.format("%-" + size + "s", other.getName())) - .append(" [Authors: [") - .append(String.join(", ", other.getDescription().getAuthors())) - .append("], Version: ") - .append(other.getDescription().getVersion()) - .append("]") - .append("\n"); - } - - return builder.toString(); - } -} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionRegister.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionRegister.java deleted file mode 100644 index a37d793..0000000 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionRegister.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.local; - -import java.io.File; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.logging.Level; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.commands.PlaceholderCommand; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.clip.placeholderapi.expansion.manager.LocalExpansionManager; -import me.clip.placeholderapi.util.Futures; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Unmodifiable; - -public final class CommandExpansionRegister extends PlaceholderCommand { - - public CommandExpansionRegister() { - super("register"); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.size() < 1) { - Msg.msg(sender, - "&cYou must specify the name of an expansion file."); - return; - } - - final LocalExpansionManager manager = plugin.getLocalExpansionManager(); - - final File file = new File(manager.getExpansionsFolder(), params.get(0)); - if (!file.exists() || !file.getParentFile().equals(manager.getExpansionsFolder())) { - Msg.msg(sender, - "&cThe file &f" + file.getName() + "&c doesn't exist!"); - return; - } - - Futures.onMainThread(plugin, manager.findExpansionInFile(file), (clazz, exception) -> { - if (exception != null) { - Msg.msg(sender, - "&cFailed to find expansion in file: &f" + file); - - plugin.getLogger() - .log(Level.WARNING, "failed to find expansion in file: " + file, exception); - return; - } - - if (clazz == null) { - Msg.msg(sender, - "&cNo expansion class found in file: &f" + file); - return; - } - - final Optional expansion = manager.register(clazz); - if (!expansion.isPresent()) { - Msg.msg(sender, - "&cFailed to register expansion from &f" + params.get(0)); - return; - } - - Msg.msg(sender, - "&aSuccessfully registered expansion: &f" + expansion.get().getName()); - - }); - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 1) { - return; - } - - final String[] fileNames = plugin.getLocalExpansionManager().getExpansionsFolder() - .list((dir, name) -> name.endsWith(".jar")); - if (fileNames == null || fileNames.length == 0) { - return; - } - - suggestByParameter(Arrays.stream(fileNames), suggestions, - params.isEmpty() ? null : params.get(0)); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionUnregister.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionUnregister.java deleted file mode 100644 index ff6c6da..0000000 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandExpansionUnregister.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.local; - -import java.util.List; -import java.util.Optional; -import me.clip.placeholderapi.PlaceholderAPI; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.commands.PlaceholderCommand; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Unmodifiable; - -public final class CommandExpansionUnregister extends PlaceholderCommand { - - public CommandExpansionUnregister() { - super("unregister"); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&cYou must specify the name of the expansion."); - return; - } - - final Optional expansion = plugin.getLocalExpansionManager() - .findExpansionByName(params.get(0)); - if (!expansion.isPresent()) { - Msg.msg(sender, - "&cThere is no expansion loaded with the identifier: &f" + params.get(0)); - return; - } - - final String message = !expansion.get().unregister() ? - "&cFailed to unregister expansion: &f" : - "&aSuccessfully unregistered expansion: &f"; - - Msg.msg(sender, message + expansion.get().getName()); - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 1) { - return; - } - - suggestByParameter(PlaceholderAPI.getRegisteredIdentifiers().stream(), suggestions, - params.isEmpty() ? null : params.get(0)); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandHelp.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandHelp.java deleted file mode 100644 index 47c1da8..0000000 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandHelp.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.local; - -import java.util.List; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.commands.PlaceholderCommand; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.command.CommandSender; -import org.bukkit.plugin.PluginDescriptionFile; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Unmodifiable; - -public final class CommandHelp extends PlaceholderCommand { - - public CommandHelp() { - super("help"); - } - - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - final PluginDescriptionFile description = plugin.getDescription(); - - Msg.msg(sender, - "&b&lPlaceholderAPI &8- &7Help Menu &8- &7(&f" + description.getVersion() + "&7)", - " ", - "&b/papi &fbcparse &9 ", - " &7&oParse a message with placeholders and broadcast it", - "&b/papi &fcmdparse &9 ", - " &7&oParse a message with relational placeholders", - "&b/papi &fdump", - " &7&oDump all relevant information needed to help debug issues into a paste link.", - "&b/papi &finfo &9", - " &7&oView information for a specific expansion", - "&b/papi &flist", - " &7&oList active expansions", - "&b/papi &fparse &9 ", - " &7&oParse a message with placeholders", - "&b/papi &fparserel &9 ", - " &7&oParse a message with relational placeholders", - "&b/papi &fregister &9", - " &7&oRegister an expansion by the name of the file", - "&b/papi &freload", - " &7&oReload the config of PAPI", - "&b/papi &funregister &9", - " &7&oUnregister an expansion by name", - "&b/papi &fversion", - " &7&oView plugin info/version"); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandInfo.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandInfo.java deleted file mode 100644 index 95e84c1..0000000 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandInfo.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.local; - -import java.util.List; -import me.clip.placeholderapi.PlaceholderAPI; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.commands.PlaceholderCommand; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Unmodifiable; - -public final class CommandInfo extends PlaceholderCommand { - - public CommandInfo() { - super("info"); - } - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - if (params.isEmpty()) { - Msg.msg(sender, - "&cYou must specify the name of the expansion."); - return; - } - - final PlaceholderExpansion expansion = plugin.getLocalExpansionManager() - .findExpansionByIdentifier(params.get(0)).orElse(null); - if (expansion == null) { - Msg.msg(sender, - "&cThere is no expansion loaded with the identifier: &f" + params.get(0)); - return; - } - - final StringBuilder builder = new StringBuilder(); - - builder.append("&7Placeholder expansion info for: &r") - .append(expansion.getName()) - .append('\n') - .append("&7Status: &r") - .append(expansion.isRegistered() ? "&aRegistered" : "7cNotRegistered") - .append('\n'); - - final String author = expansion.getAuthor(); - if (author != null) { - builder.append("&7Author: &r") - .append(author) - .append('\n'); - } - - final String version = expansion.getVersion(); - if (version != null) { - builder.append("&7Version: &r") - .append(version) - .append('\n'); - } - - final String requiredPlugin = expansion.getRequiredPlugin(); - if (requiredPlugin != null) { - builder.append("&7Requires plugin: &r") - .append(requiredPlugin) - .append('\n'); - } - - final List placeholders = expansion.getPlaceholders(); - if (placeholders != null && !placeholders.isEmpty()) { - builder.append("&8&m-- &7Placeholders &8&m--&r") - .append('\n'); - - for (final String placeholder : placeholders) { - builder.append(placeholder) - .append('\n'); - } - } - - Msg.msg(sender, builder.toString()); - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() > 1) { - return; - } - - suggestByParameter(PlaceholderAPI.getRegisteredIdentifiers().stream(), suggestions, - params.isEmpty() ? null : params.get(0)); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandParse.java b/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandParse.java deleted file mode 100644 index 1ff59b9..0000000 --- a/src/main/java/me/clip/placeholderapi/commands/impl/local/CommandParse.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.commands.impl.local; - -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.stream.Stream; -import me.clip.placeholderapi.PlaceholderAPI; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.commands.PlaceholderCommand; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.annotations.Unmodifiable; - -public final class CommandParse extends PlaceholderCommand { - - public CommandParse() { - super("parse", "bcparse", "parserel", "cmdparse"); - } - - - @Override - public void evaluate(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params) { - switch (alias.toLowerCase(Locale.ROOT)) { - case "parserel": - evaluateParseRelation(sender, params); - break; - case "parse": - evaluateParseSingular(sender, params, false, false); - break; - case "bcparse": - evaluateParseSingular(sender, params, true, false); - break; - case "cmdparse": - evaluateParseSingular(sender, params, false, true); - break; - } - } - - @Override - public void complete(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CommandSender sender, @NotNull final String alias, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - switch (alias.toLowerCase(Locale.ROOT)) { - case "parserel": - completeParseRelation(params, suggestions); - break; - case "parse": - case "bcparse": - case "cmdparse": - completeParseSingular(sender, params, suggestions); - break; - } - } - - - private void evaluateParseSingular(@NotNull final CommandSender sender, - @NotNull @Unmodifiable final List params, final boolean broadcast, - final boolean command) { - if (params.size() < 2) { - Msg.msg(sender, - "&cYou must provide a target and message: &b/papi " - + (command ? "cmdparse" : (broadcast ? "bcparse" : "parse")) - + " &7{target} &a{message}"); - return; - } - - OfflinePlayer player; - - if ("me".equalsIgnoreCase(params.get(0))) { - if (!(sender instanceof Player)) { - Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!"); - return; - } - - player = ((Player) sender); - } else if ("--null".equalsIgnoreCase(params.get(0))) { - player = null; - } else { - final OfflinePlayer target = resolvePlayer(params.get(0)); - if (target == null) { - Msg.msg(sender, "&cFailed to find player: &7" + params.get(0)); - return; - } - - player = target; - } - - final String message = PlaceholderAPI - .setPlaceholders(player, String.join(" ", params.subList(1, params.size()))); - - if (command) { - Bukkit.dispatchCommand(sender, message); - return; - } - - if (broadcast) { - Bukkit.broadcastMessage(message); - } else { - sender.sendMessage(message); - } - } - - private void evaluateParseRelation(@NotNull final CommandSender sender, - @NotNull @Unmodifiable final List params) { - if (params.size() < 3) { - Msg.msg(sender, - "&cYou must supply two targets, and a message: &b/papi parserel &7{target one} " - + "{target two} &a{message}"); - return; - } - - OfflinePlayer playerOne; - - if ("me".equalsIgnoreCase(params.get(0))) { - if (!(sender instanceof Player)) { - Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!"); - return; - } - - playerOne = ((Player) sender); - } else { - playerOne = resolvePlayer(params.get(0)); - } - - if (playerOne == null || !playerOne.isOnline()) { - Msg.msg(sender, "&cFailed to find player: &f" + params.get(0)); - return; - } - - OfflinePlayer playerTwo; - - if ("me".equalsIgnoreCase(params.get(1))) { - if (!(sender instanceof Player)) { - Msg.msg(sender, "&cYou must be a player to use &7me&c as a target!"); - return; - } - - playerTwo = ((Player) sender); - } else { - playerTwo = resolvePlayer(params.get(1)); - } - - if (playerTwo == null || !playerTwo.isOnline()) { - Msg.msg(sender, "&cFailed to find player: &f" + params.get(1)); - return; - } - - final String message = PlaceholderAPI - .setRelationalPlaceholders((Player) playerOne, (Player) playerTwo, - String.join(" ", params.subList(2, params.size()))); - - sender.sendMessage(message); - } - - - private void completeParseSingular(@NotNull final CommandSender sender, - @NotNull @Unmodifiable final List params, @NotNull final List suggestions) { - if (params.size() <= 1) { - if (sender instanceof Player && (params.isEmpty() || "me" - .startsWith(params.get(0).toLowerCase(Locale.ROOT)))) { - suggestions.add("me"); - } - - if ("--null".startsWith(params.get(0).toLowerCase(Locale.ROOT))) { - suggestions.add("--null"); - } - - final Stream names = Bukkit.getOnlinePlayers().stream().map(Player::getName); - suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(0)); - - return; - } - - final String name = params.get(params.size() - 1); - if (!name.startsWith("%") || name.endsWith("%")) { - return; - } - - final int index = name.indexOf('_'); - if (index == -1) { - return; // no arguments supplied yet - } - - final PlaceholderExpansion expansion = PlaceholderAPIPlugin.getInstance() - .getLocalExpansionManager().findExpansionByIdentifier(name.substring(1, index)) - .orElse(null); - if (expansion == null) { - return; - } - - final Set possible = new HashSet<>(expansion.getPlaceholders()); - - PlaceholderAPIPlugin.getInstance() - .getCloudExpansionManager() - .findCloudExpansionByName(expansion.getName()) - .ifPresent(cloud -> possible.addAll(cloud.getPlaceholders())); - - suggestByParameter(possible.stream(), suggestions, params.get(params.size() - 1)); - } - - private void completeParseRelation(@NotNull @Unmodifiable final List params, - @NotNull final List suggestions) { - if (params.size() > 2) { - return; - } - - final Stream names = Bukkit.getOnlinePlayers().stream().map(Player::getName); - suggestByParameter(names, suggestions, params.isEmpty() ? null : params.get(params.size() - 1)); - } - - - @Nullable - private OfflinePlayer resolvePlayer(@NotNull final String name) { - OfflinePlayer target = Bukkit.getPlayerExact(name); - - if (target == null) { - // Not the best option, but Spigot doesn't offer a good replacement (as usual) - target = Bukkit.getOfflinePlayer(name); - - return target.hasPlayedBefore() ? target : null; - } - - return target; - - } - -} diff --git a/src/main/java/me/clip/placeholderapi/configuration/PlaceholderAPIConfig.java b/src/main/java/me/clip/placeholderapi/configuration/PlaceholderAPIConfig.java deleted file mode 100644 index 26c0213..0000000 --- a/src/main/java/me/clip/placeholderapi/configuration/PlaceholderAPIConfig.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.configuration; - -import java.util.Optional; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import org.jetbrains.annotations.NotNull; - -public final class PlaceholderAPIConfig { - - @NotNull - private final PlaceholderAPIPlugin plugin; - - public PlaceholderAPIConfig(@NotNull final PlaceholderAPIPlugin plugin) { - this.plugin = plugin; - } - - - public boolean checkUpdates() { - return plugin.getConfig().getBoolean("check_updates"); - } - - - public boolean isCloudEnabled() { - return plugin.getConfig().getBoolean("cloud_enabled"); - } - - public void setCloudEnabled(boolean state) { - plugin.getConfig().set("cloud_enabled", state); - plugin.saveConfig(); - } - - - public boolean isDebugMode() { - return plugin.getConfig().getBoolean("debug", false); - } - - - public Optional getExpansionSort() { - final String option = plugin.getConfig() - .getString("cloud_sorting", ExpansionSort.LATEST.name()); - - try { - //noinspection ConstantConditions (bad spigot annotation) - return Optional.of(ExpansionSort.valueOf(option.toUpperCase())); - } catch (final IllegalArgumentException ignored) { - return Optional.empty(); - } - } - - - @NotNull - public String dateFormat() { - //noinspection ConstantConditions (bad spigot annotation) - return plugin.getConfig().getString("date_format", "MM/dd/yy HH:mm:ss"); - } - - - @NotNull - public String booleanTrue() { - //noinspection ConstantConditions (bad spigot annotation) - return plugin.getConfig().getString("boolean.true", "true"); - } - - @NotNull - public String booleanFalse() { - //noinspection ConstantConditions (bad spigot annotation) - return plugin.getConfig().getString("boolean.false", "false"); - } - - public boolean detectMaliciousExpansions() { - return plugin.getConfig().getBoolean("detect_malicious_expansions", true); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/events/ExpansionRegisterEvent.java b/src/main/java/me/clip/placeholderapi/events/ExpansionRegisterEvent.java deleted file mode 100644 index 21df3ab..0000000 --- a/src/main/java/me/clip/placeholderapi/events/ExpansionRegisterEvent.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.events; - -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import org.bukkit.event.Cancellable; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -/** - * This event indicates that a single {@link PlaceholderExpansion PlaceholderExpansion} has - * been registered in PlaceholderAPI. - * - *

To know when all Expansions have been registered, use the - * {@link me.clip.placeholderapi.events.ExpansionsLoadedEvent ExpansionsLoadedEvent} instead. - */ -public final class ExpansionRegisterEvent extends Event implements Cancellable { - - @NotNull - private static final HandlerList HANDLERS = new HandlerList(); - @NotNull - private final PlaceholderExpansion expansion; - private boolean cancelled; - - public ExpansionRegisterEvent(@NotNull final PlaceholderExpansion expansion) { - this.expansion = expansion; - } - - @NotNull - public static HandlerList getHandlerList() { - return HANDLERS; - } - - /** - * The {@link PlaceholderExpansion PlaceholderExpansion} that was registered in PlaceholderAPI. - *
The PlaceholderExpansion will be available for use when the event - * {@link #isCancelled() was not cancelled}! - * - * @return Current instance of the registered {@link PlaceholderExpansion PlaceholderExpansion} - */ - @NotNull - public PlaceholderExpansion getExpansion() { - return expansion; - } - - /** - * Indicates if this event was cancelled or not. - *
A cancelled Event will result in the {@link #getExpansion() PlaceholderExpansion} NOT - * being added to PlaceholderAPI's internal list and will therefore be considered not registered - * anymore. - * - * @return Whether the event has been cancelled or not. - */ - @Override - public boolean isCancelled() { - return cancelled; - } - - @Override - public void setCancelled(boolean cancelled) { - this.cancelled = cancelled; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return HANDLERS; - } - -} diff --git a/src/main/java/me/clip/placeholderapi/expansion/NMSVersion.java b/src/main/java/me/clip/placeholderapi/expansion/NMSVersion.java deleted file mode 100644 index 9e658e8..0000000 --- a/src/main/java/me/clip/placeholderapi/expansion/NMSVersion.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.expansion; - -public enum NMSVersion { - - UNKNOWN("unknown"), - SPIGOT_1_7_R1("v1_7_R1"), - SPIGOT_1_7_R2("v1_7_R2"), - SPIGOT_1_7_R3("v1_7_R3"), - SPIGOT_1_7_R4("v1_7_R4"), - SPIGOT_1_8_R1("v1_8_R1"), - SPIGOT_1_8_R2("v1_8_R2"), - SPIGOT_1_8_R3("v1_8_R3"), - SPIGOT_1_9_R1("v1_9_R1"), - SPIGOT_1_9_R2("v1_9_R2"), - SPIGOT_1_10_R1("v1_10_R1"), - SPIGOT_1_11_R1("v1_11_R1"), - SPIGOT_1_12_R1("v1_12_R1"), - SPIGOT_1_13_R1("v1_13_R1"), - SPIGOT_1_13_R2("v1_13_R2"), - SPIGOT_1_14_R1("v1_14_R1"), - SPIGOT_1_15_R1("v1_15_R1"), - SPIGOT_1_16_R1("v1_16_R1"), - SPIGOT_1_16_R2("v1_16_R2"), - SPIGOT_1_16_R3("v1_16_R3"), - SPIGOT_1_17_R1("v1_17_R1"), - SPIGOT_1_18_R1("v1_18_R1"), - SPIGOT_1_19_R1("v1_19_R1"), - SPIGOT_1_19_R2("v1_19_R2"), - SPIGOT_1_19_R3("v1_19_R3"), - SPIGOT_1_20_R1("v1_20_R1"), - SPIGOT_1_20_R2("v1_20_R2"), - SPIGOT_1_20_R3("v1_20_R3"), - SPIGOT_1_20_R4("v1_20_R4"), - SPIGOT_1_21_R1("v1_21_R1"), - SPIGOT_1_21_R2("V1_21_R2"), - SPIGOT_1_21_R3("V1_21_R3"), - SPIGOT_1_21_R4("V1_21_R4"), - SPIGOT_1_21_R5("V1_21_R5"), - SPIGOT_1_21_R6("V1_21_R6"); - - private final String version; - - NMSVersion(String version) { - this.version = version; - } - - public static NMSVersion getVersion(String version) { - for (NMSVersion v : values()) { - if (v.getVersion().equalsIgnoreCase(version)) { - return v; - } - } - - return NMSVersion.UNKNOWN; - } - - public String getVersion() { - return version; - } - -} diff --git a/src/main/java/me/clip/placeholderapi/expansion/PlaceholderExpansion.java b/src/main/java/me/clip/placeholderapi/expansion/PlaceholderExpansion.java deleted file mode 100644 index 3fb24f9..0000000 --- a/src/main/java/me/clip/placeholderapi/expansion/PlaceholderExpansion.java +++ /dev/null @@ -1,479 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.expansion; - -import java.util.Collections; -import java.util.List; -import java.util.logging.Level; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.PlaceholderHook; -import org.bukkit.Bukkit; -import org.bukkit.configuration.ConfigurationSection; -import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.Contract; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -/** - * Any class extending this will be able to get registered as a PlaceholderExpansion. - *
The registration either happens automatically when the jar file containing a - * class extending this one is located under the {@code PlaceholderAPI/expansions} - * directory or when the {@link #register()} method is called by said class. - */ -public abstract class PlaceholderExpansion extends PlaceholderHook { - - /** - * The type is {@link Type#INTERNAL} by default. - * For external expansions, the type is updated on {@link me.clip.placeholderapi.expansion.manager.LocalExpansionManager#register(Class) register}. - * @since 2.11.4 - */ - @ApiStatus.Internal - protected Type expansionType = Type.INTERNAL; - - /** - * The placeholder identifier of this expansion. May not contain {@literal %}, - * {@literal {}} or _ - * - * @return placeholder identifier that is associated with this expansion - */ - @NotNull - public abstract String getIdentifier(); - - /** - * The author of this expansion - * - * @return name of the author for this expansion - */ - @NotNull - public abstract String getAuthor(); - - /** - * The version of this expansion - * - * @return current version of this expansion - */ - @NotNull - public abstract String getVersion(); - - /** - * The name of this expansion - * - * @return {@link #getIdentifier()} by default, name of this expansion if specified - */ - @NotNull - public String getName() { - return getIdentifier(); - } - - /** - * The name of the plugin that this expansion hooks into. by default will null - * - * @return plugin name that this expansion requires to function - */ - @Nullable - public String getRequiredPlugin() { - return getPlugin(); - } - - /** - * The placeholders associated with this expansion - * - * @return placeholder list that this expansion provides - */ - @NotNull - public List getPlaceholders() { - return Collections.emptyList(); - } - - - /** - * Expansions that do not use the ecloud and instead register from the dependency should set this - * to true to ensure that your placeholder expansion is not unregistered when the papi reload - * command is used - * - * @return if this expansion should persist through placeholder reloads - */ - public boolean persist() { - return false; - } - - - /** - * Check if this placeholder identifier has already been registered - * - * @return true if the identifier for this expansion is already registered - */ - public final boolean isRegistered() { - return getPlaceholderAPI().getLocalExpansionManager().findExpansionByIdentifier(getIdentifier()) - .map(it -> it.equals(this)).orElse(false); - } - - - /** - * If any requirements need to be checked before this expansion should register, you can check - * them here - * - * @return true if this hook meets all the requirements to register - */ - public boolean canRegister() { - return getRequiredPlugin() == null - || Bukkit.getPluginManager().getPlugin(getRequiredPlugin()) != null; - } - - /** - * Attempt to register this PlaceholderExpansion - * - * @return true if this expansion is now registered with PlaceholderAPI - */ - public boolean register() { - return getPlaceholderAPI().getLocalExpansionManager().register(this); - } - - /** - * Attempt to unregister this PlaceholderExpansion - * - * @return true if this expansion is now unregistered with PlaceholderAPI - */ - public final boolean unregister() { - return getPlaceholderAPI().getLocalExpansionManager().unregister(this); - } - - - /** - * Quick getter for the {@link PlaceholderAPIPlugin} instance - * - * @return {@link PlaceholderAPIPlugin} instance - */ - @NotNull - public final PlaceholderAPIPlugin getPlaceholderAPI() { - return PlaceholderAPIPlugin.getInstance(); - } - - /** - * Get the type of the expansion - * - * @return the type of the expansion - * @since 2.11.4 - */ - @ApiStatus.Internal - public Type getExpansionType() { - return expansionType; - } - - /** - * Set the type of the expansion - * @param expansionType the new type - * @since 2.11.4 - */ - @ApiStatus.Internal - public void setExpansionType(Type expansionType) { - this.expansionType = expansionType; - } - - // === Configuration === - - /** - * Gets the ConfigurationSection of the expansion located in the config.yml of PlaceholderAPI or - * null when not specified. - *
You may use the {@link Configurable} interface to define default values set - * - * @return ConfigurationSection that this expansion has. - */ - @Nullable - public final ConfigurationSection getConfigSection() { - return getPlaceholderAPI().getConfig().getConfigurationSection("expansions." + getIdentifier()); - } - - /** - * Gets the ConfigurationSection relative to the {@link #getConfigSection() default one} set - * by the expansion or null when the default ConfigurationSection is null - * - * @param path The path to get the ConfigurationSection from. This is relative to the default section - * @return ConfigurationSection relative to the default section - */ - @Nullable - public final ConfigurationSection getConfigSection(@NotNull final String path) { - final ConfigurationSection section = getConfigSection(); - return section == null ? null : section.getConfigurationSection(path); - } - - /** - * Gets the Object relative to the {@link #getConfigSection() default ConfigurationSection} set - * by the expansion or the provided Default Object, when the default ConfigurationSection is null - * - * @param path The path to get the Object from. This is relative to the default section - * @param def The default Object to return when the ConfigurationSection returns null - * @return Object from the provided path or the default one provided - */ - @Nullable - @Contract("_, !null -> !null") - public final Object get(@NotNull final String path, final Object def) { - final ConfigurationSection section = getConfigSection(); - return section == null ? def : section.get(path, def); - } - - /** - * Gets the int relative to the {@link #getConfigSection() default ConfigurationSection} set - * by the expansion or the provided Default int, when the default ConfigurationSection is null - * - * @param path The path to get the int from. This is relative to the default section - * @param def The default int to return when the ConfigurationSection returns null - * @return int from the provided path or the default one provided - */ - public final int getInt(@NotNull final String path, final int def) { - final ConfigurationSection section = getConfigSection(); - return section == null ? def : section.getInt(path, def); - } - - /** - * Gets the long relative to the {@link #getConfigSection() default ConfigurationSection} set - * by the expansion or the provided Default long, when the default ConfigurationSection is null - * - * @param path The path to get the long from. This is relative to the default section - * @param def The default long to return when the ConfigurationSection returns null - * @return long from the provided path or the default one provided - */ - public final long getLong(@NotNull final String path, final long def) { - final ConfigurationSection section = getConfigSection(); - return section == null ? def : section.getLong(path, def); - } - - /** - * Gets the double relative to the {@link #getConfigSection() default ConfigurationSection} set - * by the expansion or the provided Default double, when the default ConfigurationSection is null - * - * @param path The path to get the double from. This is relative to the default section - * @param def The default double to return when the ConfigurationSection returns null - * @return double from the provided path or the default one provided - */ - public final double getDouble(@NotNull final String path, final double def) { - final ConfigurationSection section = getConfigSection(); - return section == null ? def : section.getDouble(path, def); - } - - /** - * Gets the String relative to the {@link #getConfigSection() default ConfigurationSection} set - * by the expansion or the provided Default String, when the default ConfigurationSection is null - * - * @param path The path to get the String from. This is relative to the default section - * @param def The default String to return when the ConfigurationSection returns null. Can be null - * @return String from the provided path or the default one provided - */ - @Nullable - @Contract("_, !null -> !null") - public final String getString(@NotNull final String path, @Nullable final String def) { - final ConfigurationSection section = getConfigSection(); - return section == null ? def : section.getString(path, def); - } - - /** - * Gets a String List relative to the {@link #getConfigSection() default ConfigurationSection} set - * by the expansion or an empty List, when the default ConfigurationSection is null - * - * @param path The path to get the String list from. This is relative to the default section - * @return String list from the provided path or an empty list - */ - @NotNull - public final List getStringList(@NotNull final String path) { - final ConfigurationSection section = getConfigSection(); - return section == null ? Collections.emptyList() : section.getStringList(path); - } - - /** - * Gets the boolean relative to the {@link #getConfigSection() default ConfigurationSection} set - * by the expansion or the default boolean, when the default ConfigurationSection is null - * - * @param path The path to get the boolean from. This is relative to the default section - * @param def The default boolean to return when the ConfigurationSection is null - * @return boolean from the provided path or the default one provided - */ - public final boolean getBoolean(@NotNull final String path, final boolean def) { - final ConfigurationSection section = getConfigSection(); - return section == null ? def : section.getBoolean(path, def); - } - - /** - * Whether the {@link #getConfigSection() default ConfigurationSection} contains the provided path - * or not. This will return {@code false} when either the default section is null, or doesn't - * contain the provided path - * - * @param path The path to check - * @return true when the default ConfigurationSection is not null and contains the path, false otherwise - */ - public final boolean configurationContains(@NotNull final String path) { - final ConfigurationSection section = getConfigSection(); - return section != null && section.contains(path); - } - - /** - * Logs the provided message with the provided Level in the console. - *
The message will be prefixed with {@link #getName() [<expansion name>]} - * - * @param level The Level at which the message should be logged with - * @param msg The message to log - */ - public void log(Level level, String msg) { - getPlaceholderAPI().getLogger().log(level, "[" + getName() + "] " + msg); - } - - /** - * Logs the provided message and Throwable with the provided Level in the console. - *
The message will be prefixed with {@link #getName() [<expansion name>]} - * - * @param level The Level at which the message should be logged with - * @param msg The message to log - * @param throwable The Throwable to log - */ - public void log(Level level, String msg, Throwable throwable) { - getPlaceholderAPI().getLogger().log(level, "[" + getName() + "] " + msg, throwable); - } - - /** - * Logs the provided message with Level "info". - *
The message will be prefixed with {@link #getName() [<expansion name>]} - * - * @param msg The message to log - */ - public void info(String msg) { - log(Level.INFO, msg); - } - - /** - * Logs the provided message with Level "warning". - *
The message will be prefixed with {@link #getName() [<expansion name>]} - * - * @param msg The message to log - */ - public void warning(String msg) { - log(Level.WARNING, msg); - } - - /** - * Logs the provided message with Level "severe" (error). - *
The message will be prefixed with {@link #getName() [<expansion name>]} - * - * @param msg The message to log - */ - public void severe(String msg) { - log(Level.SEVERE, msg); - } - - /** - * Logs the provided message and Throwable with Level "severe" (error). - *
The message will be prefixed with {@link #getName() [<expansion name>]} - * - * @param msg The message to log - * @param throwable The Throwable to log - */ - public void severe(String msg, Throwable throwable) { - log(Level.SEVERE, msg, throwable); - } - - - /** - * Whether the provided Object is an instance of this PlaceholderExpansion. - *
This method will perform the following checks in order: - *

    - *
  • Checks if Object equals the class. Returns true when equal and continues otherwise
  • - *
  • Checks if the Object is an instance of a PlaceholderExpansion. Returns false if not
  • - *
  • Checks if the Object's Identifier, Author and version equal the one of this class
  • - *
- * - * @param o The Object to check - * @return true or false depending on the above mentioned checks - */ - @Override - public final boolean equals(final Object o) { - if (this == o) { - return true; - } - if (!(o instanceof PlaceholderExpansion)) { - return false; - } - - final PlaceholderExpansion expansion = (PlaceholderExpansion) o; - - return getIdentifier().equals(expansion.getIdentifier()) && - getAuthor().equals(expansion.getAuthor()) && - getVersion().equals(expansion.getVersion()); - } - - /** - * Returns a String containing the Expansion's name, author and version - * - * @return String containing name, author and version of the expansion - */ - @Override - public final String toString() { - return String.format("PlaceholderExpansion[name: '%s', author: '%s', version: '%s', type: '%s']", getName(), - getAuthor(), getVersion(), getExpansionType()); - } - - // === Deprecated API === - - /** - * @deprecated As of versions greater than 2.8.7, use {@link #getRequiredPlugin()} - * - * @return The plugin name. - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public String getPlugin() { - return null; - } - - /** - * @deprecated As of versions greater than 2.8.7, use the expansion cloud to show a description - * - * @return The description of the expansion. - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public String getDescription() { - return null; - } - - /** - * @deprecated As of versions greater than 2.8.7, use the expansion cloud to display a link - * - * @return The link for the expansion. - */ - @Deprecated - @ApiStatus.ScheduledForRemoval(inVersion = "2.13.0") - public String getLink() { - return null; - } - - public enum Type { - - /** - * An expansion provided by a plugin is considered internal - */ - INTERNAL, - - /** - * An expansion loaded from the expansions folder is considered external - */ - EXTERNAL - - } - -} diff --git a/src/main/java/me/clip/placeholderapi/expansion/cloud/CloudExpansion.java b/src/main/java/me/clip/placeholderapi/expansion/cloud/CloudExpansion.java deleted file mode 100644 index 94b1ed6..0000000 --- a/src/main/java/me/clip/placeholderapi/expansion/cloud/CloudExpansion.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.expansion.cloud; - -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import me.clip.placeholderapi.util.TimeUtil; - - -public class CloudExpansion { - - private String name, - author, - latest_version, - description, - source_url, - dependency_url; - - private boolean hasExpansion, - shouldUpdate; - - private long last_update, - ratings_count; - - private double average_rating; - - private List placeholders; - - private List versions; - - public CloudExpansion() { - } - - public String getTimeSinceLastUpdate() { - int time = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - getLastUpdate()); - return TimeUtil.getTime(time); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAuthor() { - return author; - } - - public void setAuthor(String author) { - this.author = author; - } - - public Version getVersion() { - return getLatestVersion() == null ? null : getVersion(getLatestVersion()); - } - - public Version getVersion(String version) { - return versions == null ? null : versions.stream() - .filter(v -> v.getVersion().equals(version)) - .findFirst() - .orElse(null); - } - - public List getAvailableVersions() { - return versions.stream().map(Version::getVersion).collect(Collectors.toList()); - } - - public String getLatestVersion() { - return latest_version; - } - - public void setLatestVersion(String latest_version) { - this.latest_version = latest_version; - } - - public String getDescription() { - return description; - } - - public void setDescription(String description) { - this.description = description; - } - - public String getSourceUrl() { - return source_url; - } - - public void setSourceUrl(String source_url) { - this.source_url = source_url; - } - - public String getDependencyUrl() { - return dependency_url; - } - - public void setDependencyUrl(String dependency_url) { - this.dependency_url = dependency_url; - } - - public boolean hasExpansion() { - return hasExpansion; - } - - public void setHasExpansion(boolean hasExpansion) { - this.hasExpansion = hasExpansion; - } - - public boolean shouldUpdate() { - return shouldUpdate; - } - - public void setShouldUpdate(boolean shouldUpdate) { - this.shouldUpdate = shouldUpdate; - } - - public long getLastUpdate() { - return last_update; - } - - public void setLastUpdate(long last_update) { - this.last_update = last_update; - } - - public long getRatingsCount() { - return ratings_count; - } - - public double getAverage_rating() { - return average_rating; - } - - public List getPlaceholders() { - return placeholders; - } - - public void setPlaceholders(List placeholders) { - this.placeholders = placeholders; - } - - public List getVersions() { - return versions; - } - - public void setVersions(List versions) { - this.versions = versions; - } - - public static class Version { - - private String url, version, release_notes; - private boolean verified; - - public String getUrl() { - return url; - } - - public void setUrl(String url) { - this.url = url; - } - - public String getVersion() { - return version; - } - - public void setVersion(String version) { - this.version = version; - } - - public String getReleaseNotes() { - return release_notes; - } - - public void setReleaseNotes(String release_notes) { - this.release_notes = release_notes; - } - - public boolean isVerified() { - return verified; - } - - public void setVerified(boolean verified) { - this.verified = verified; - } - } -} diff --git a/src/main/java/me/clip/placeholderapi/expansion/manager/CloudExpansionManager.java b/src/main/java/me/clip/placeholderapi/expansion/manager/CloudExpansionManager.java deleted file mode 100644 index 16fdc85..0000000 --- a/src/main/java/me/clip/placeholderapi/expansion/manager/CloudExpansionManager.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.expansion.manager; - -import com.google.common.collect.ImmutableMap; -import com.google.common.io.Resources; -import com.google.common.util.concurrent.ThreadFactoryBuilder; -import com.google.gson.Gson; -import com.google.gson.reflect.TypeToken; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.lang.reflect.Type; -import java.net.URL; -import java.nio.channels.Channels; -import java.nio.channels.ReadableByteChannel; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionException; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.function.Function; -import java.util.logging.Level; -import java.util.stream.Collector; -import java.util.stream.Collectors; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.clip.placeholderapi.expansion.cloud.CloudExpansion; -import me.clip.placeholderapi.util.Msg; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Unmodifiable; - -public final class CloudExpansionManager { - - @NotNull - private static final String API_URL = "https://ecloud.placeholderapi.com/api/v3/"; - - @NotNull - private static final Gson GSON = new Gson(); - @NotNull - private static final Type TYPE = new TypeToken>() {}.getType(); - - @NotNull - private final Collector> INDEXED_NAME_COLLECTOR = Collectors - .toMap(CloudExpansionManager::toIndexName, Function.identity()); - - - @NotNull - private final PlaceholderAPIPlugin plugin; - - @NotNull - private final Map cache = new HashMap<>(); - @NotNull - private final Map> await = new ConcurrentHashMap<>(); - - private final ExecutorService ASYNC_EXECUTOR = - Executors.newCachedThreadPool( - new ThreadFactoryBuilder().setNameFormat("placeholderapi-io-#%1$d").build()); - - public CloudExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) { - this.plugin = plugin; - } - - @NotNull - private static String toIndexName(@NotNull final String name) { - return name.toLowerCase(Locale.ROOT).replace(' ', '_'); - } - - @NotNull - private static String toIndexName(@NotNull final CloudExpansion expansion) { - return toIndexName(expansion.getName()); - } - - public void load() { - clean(); - fetch(); - } - - public void kill() { - clean(); - } - - @NotNull - @Unmodifiable - public Map getCloudExpansions() { - return ImmutableMap.copyOf(cache); - } - - @NotNull - @Unmodifiable - public Map getCloudExpansionsInstalled() { - if (cache.isEmpty()) { - return Collections.emptyMap(); - } - - return cache.values() - .stream() - .filter(CloudExpansion::hasExpansion) - .collect(INDEXED_NAME_COLLECTOR); - } - - @NotNull - @Unmodifiable - public Map getCloudExpansionsByAuthor(@NotNull final String author) { - if (cache.isEmpty()) { - return Collections.emptyMap(); - } - - return cache.values() - .stream() - .filter(expansion -> author.equalsIgnoreCase(expansion.getAuthor())) - .collect(INDEXED_NAME_COLLECTOR); - } - - @NotNull - @Unmodifiable - public Set getCloudExpansionAuthors() { - return cache.values().stream().map(CloudExpansion::getAuthor).collect(Collectors.toSet()); - } - - public int getCloudExpansionAuthorCount() { - return getCloudExpansionAuthors().size(); - } - - public int getCloudUpdateCount() { - return ((int) plugin.getLocalExpansionManager() - .getExpansions() - .stream() - .filter(expansion -> findCloudExpansionByName(expansion.getName()) - .map(CloudExpansion::shouldUpdate).orElse(false)) - .count()); - } - - @NotNull - public Optional findCloudExpansionByName(@NotNull final String name) { - return Optional.ofNullable(cache.get(toIndexName(name))); - } - - public void clean() { - cache.clear(); - - await.values().forEach(future -> future.cancel(true)); - await.clear(); - } - - public void fetch() { - plugin.getLogger().info("Fetching available expansion information..."); - - ASYNC_EXECUTOR.submit( - () -> { - // a defence tactic! use ConcurrentHashMap instead of normal HashMap - Map values = new ConcurrentHashMap<>(); - try { - //noinspection UnstableApiUsage - String json = Resources.toString(new URL(API_URL), StandardCharsets.UTF_8); - values.putAll(GSON.fromJson(json, TYPE)); - - List toRemove = new ArrayList<>(); - - for (Map.Entry entry : values.entrySet()) { - CloudExpansion expansion = entry.getValue(); - if (expansion.getLatestVersion() == null - || expansion.getVersion(expansion.getLatestVersion()) == null) { - toRemove.add(entry.getKey()); - } - } - - for (String name : toRemove) { - values.remove(name); - } - } catch (Throwable e) { - // ugly swallowing of every throwable, but we have to be defensive - plugin.getLogger().log(Level.WARNING, "Failed to download expansion information", e); - } - - // loop through what's left on the main thread - plugin - .getScheduler() - .runTask( - () -> { - try { - for (Map.Entry entry : values.entrySet()) { - String name = entry.getKey(); - CloudExpansion expansion = entry.getValue(); - - expansion.setName(name); - - Optional localOpt = - plugin.getLocalExpansionManager().findExpansionByName(name); - if (localOpt.isPresent()) { - PlaceholderExpansion local = localOpt.get(); - if (local.isRegistered()) { - expansion.setHasExpansion(true); - expansion.setShouldUpdate( - !local.getVersion().equalsIgnoreCase(expansion.getLatestVersion())); - } - } - - cache.put(toIndexName(expansion), expansion); - } - } catch (Throwable e) { - // ugly swallowing of every throwable, but we have to be defensive - plugin - .getLogger() - .log(Level.WARNING, "Failed to download expansion information", e); - } - }); - }); - } - - public boolean isDownloading(@NotNull final CloudExpansion expansion) { - return await.containsKey(toIndexName(expansion)); - } - - @NotNull - public CompletableFuture downloadExpansion(@NotNull final CloudExpansion expansion, - @NotNull final CloudExpansion.Version version) { - final CompletableFuture previous = await.get(toIndexName(expansion)); - if (previous != null) { - return previous; - } - - final File file = new File(plugin.getLocalExpansionManager().getExpansionsFolder(), - "Expansion-" + toIndexName(expansion) + ".jar"); - - final CompletableFuture download = CompletableFuture.supplyAsync(() -> { - try (final ReadableByteChannel source = Channels.newChannel(new URL(version.getUrl()) - .openStream()); final FileOutputStream target = new FileOutputStream(file)) { - target.getChannel().transferFrom(source, 0, Long.MAX_VALUE); - } catch (final IOException ex) { - throw new CompletionException(ex); - } - return file; - }, ASYNC_EXECUTOR); - - download.whenCompleteAsync((value, exception) -> { - await.remove(toIndexName(expansion)); - - if (exception != null) { - Msg.severe("Failed to download %s:%s", exception, expansion.getName(), expansion.getVersion()); - } - }, ASYNC_EXECUTOR); - - await.put(toIndexName(expansion), download); - - return download; - } - -} diff --git a/src/main/java/me/clip/placeholderapi/expansion/manager/LocalExpansionManager.java b/src/main/java/me/clip/placeholderapi/expansion/manager/LocalExpansionManager.java deleted file mode 100644 index 6128a64..0000000 --- a/src/main/java/me/clip/placeholderapi/expansion/manager/LocalExpansionManager.java +++ /dev/null @@ -1,495 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.expansion.manager; - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Sets; -import java.io.File; -import java.lang.reflect.Modifier; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.locks.ReentrantLock; -import java.util.logging.Level; -import java.util.stream.Collectors; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.events.ExpansionRegisterEvent; -import me.clip.placeholderapi.events.ExpansionUnregisterEvent; -import me.clip.placeholderapi.events.ExpansionsLoadedEvent; -import me.clip.placeholderapi.expansion.Cacheable; -import me.clip.placeholderapi.expansion.Cleanable; -import me.clip.placeholderapi.expansion.Configurable; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.clip.placeholderapi.expansion.Taskable; -import me.clip.placeholderapi.expansion.VersionSpecific; -import me.clip.placeholderapi.expansion.cloud.CloudExpansion; -import me.clip.placeholderapi.util.FileUtil; -import me.clip.placeholderapi.util.Futures; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.HandlerList; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerQuitEvent; -import org.bukkit.event.server.PluginDisableEvent; -import org.jetbrains.annotations.ApiStatus; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.annotations.Unmodifiable; - -public final class LocalExpansionManager implements Listener { - - @NotNull - private static final String EXPANSIONS_FOLDER_NAME = "expansions"; - - @NotNull - private static final Set ABSTRACT_EXPANSION_METHODS = Arrays.stream(PlaceholderExpansion.class.getDeclaredMethods()) - .filter(method -> Modifier.isAbstract(method.getModifiers())) - .map(method -> new MethodSignature(method.getName(), method.getParameterTypes())) - .collect(Collectors.toSet()); - - @NotNull - private final File folder; - @NotNull - private final PlaceholderAPIPlugin plugin; - - @NotNull - private final Map expansions = new ConcurrentHashMap<>(); - private final ReentrantLock expansionsLock = new ReentrantLock(); - - - public LocalExpansionManager(@NotNull final PlaceholderAPIPlugin plugin) { - this.plugin = plugin; - this.folder = new File(plugin.getDataFolder(), EXPANSIONS_FOLDER_NAME); - - if (!this.folder.exists() && !folder.mkdirs()) { - Msg.warn("Failed to create expansions folder!"); - } - } - - public void load(@NotNull final CommandSender sender) { - registerAll(sender); - } - - public void kill() { - unregisterAll(); - } - - - @NotNull - public File getExpansionsFolder() { - return folder; - } - - @NotNull - @Unmodifiable - public Collection getIdentifiers() { - expansionsLock.lock(); - try { - return ImmutableSet.copyOf(expansions.keySet()); - } finally { - expansionsLock.unlock(); - } - } - - @NotNull - @Unmodifiable - public Collection getExpansions() { - expansionsLock.lock(); - try { - return ImmutableSet.copyOf(expansions.values()); - } finally { - expansionsLock.unlock(); - } - } - - @Nullable - public PlaceholderExpansion getExpansion(@NotNull final String identifier) { - expansionsLock.lock(); - try { - return expansions.get(identifier.toLowerCase(Locale.ROOT)); - } finally { - expansionsLock.unlock(); - } - } - - @NotNull - public Optional findExpansionByName(@NotNull final String name) { - expansionsLock.lock(); - try { - PlaceholderExpansion bestMatch = null; - for (Map.Entry entry : expansions.entrySet()) { - PlaceholderExpansion expansion = entry.getValue(); - if (expansion.getName().equalsIgnoreCase(name)) { - bestMatch = expansion; - break; - } - } - return Optional.ofNullable(bestMatch); - } finally { - expansionsLock.unlock(); - } - } - - @NotNull - public Optional findExpansionByIdentifier( - @NotNull final String identifier) { - return Optional.ofNullable(getExpansion(identifier)); - } - - - public Optional register( - @NotNull final Class clazz) { - try { - final PlaceholderExpansion expansion = createExpansionInstance(clazz); - - if(expansion == null){ - return Optional.empty(); - } - - Objects.requireNonNull(expansion.getAuthor(), "The expansion author is null!"); - Objects.requireNonNull(expansion.getIdentifier(), "The expansion identifier is null!"); - Objects.requireNonNull(expansion.getVersion(), "The expansion version is null!"); - - if (expansion.getRequiredPlugin() != null && !expansion.getRequiredPlugin().isEmpty()) { - if (!Bukkit.getPluginManager().isPluginEnabled(expansion.getRequiredPlugin())) { - Msg.warn("Cannot load expansion %s due to a missing plugin: %s", expansion.getIdentifier(), - expansion.getRequiredPlugin()); - return Optional.empty(); - } - } - - expansion.setExpansionType(PlaceholderExpansion.Type.EXTERNAL); - - if (!expansion.register()) { - Msg.warn("Cannot load expansion %s due to an unknown issue.", expansion.getIdentifier()); - return Optional.empty(); - } - - return Optional.of(expansion); - } catch (LinkageError | NullPointerException ex) { - final String reason; - - if (ex instanceof LinkageError) { - reason = " (Is a dependency missing?)"; - } else { - reason = " - One of its properties is null which is not allowed!"; - } - - Msg.severe("Failed to load expansion class %s%s", ex, clazz.getSimpleName(), reason); - } - - return Optional.empty(); - } - - /** - * Attempt to register a {@link PlaceholderExpansion} - * @param expansion the expansion to register - * @return if the expansion was registered - */ - @ApiStatus.Internal - public boolean register(@NotNull final PlaceholderExpansion expansion) { - final String identifier = expansion.getIdentifier().toLowerCase(Locale.ROOT); - - if (!expansion.canRegister()) { - return false; - } - - // Avoid loading two external expansions with the same identifier - if (expansion.getExpansionType() == PlaceholderExpansion.Type.EXTERNAL && expansions.containsKey(identifier)) { - Msg.warn("Failed to load external expansion %s. Identifier is already in use.", expansion.getIdentifier()); - return false; - } - - if (expansion instanceof Configurable) { - Map defaults = ((Configurable) expansion).getDefaults(); - String pre = "expansions." + identifier + "."; - FileConfiguration cfg = plugin.getConfig(); - boolean save = false; - - if (defaults != null) { - for (Map.Entry entries : defaults.entrySet()) { - if (entries.getKey() == null || entries.getKey().isEmpty()) { - continue; - } - - if (entries.getValue() == null) { - if (cfg.contains(pre + entries.getKey())) { - save = true; - cfg.set(pre + entries.getKey(), null); - } - } else { - if (!cfg.contains(pre + entries.getKey())) { - save = true; - cfg.set(pre + entries.getKey(), entries.getValue()); - } - } - } - } - - if (save) { - plugin.saveConfig(); - plugin.reloadConfig(); - } - } - - if (expansion instanceof VersionSpecific) { - VersionSpecific nms = (VersionSpecific) expansion; - if (!nms.isCompatibleWith(PlaceholderAPIPlugin.getServerVersion())) { - Msg.warn("Your server version is incompatible with expansion %s %s", - expansion.getIdentifier(), expansion.getVersion()); - return false; - } - } - - final PlaceholderExpansion removed = getExpansion(identifier); - if (removed != null && !removed.unregister()) { - return false; - } - - final ExpansionRegisterEvent event = new ExpansionRegisterEvent(expansion); - Bukkit.getPluginManager().callEvent(event); - - if (event.isCancelled()) { - return false; - } - - expansionsLock.lock(); - try { - expansions.put(identifier, expansion); - } finally { - expansionsLock.unlock(); - } - - if (expansion instanceof Listener) { - Bukkit.getPluginManager().registerEvents(((Listener) expansion), plugin); - } - - Msg.info( - "Successfully registered %s expansion: %s [%s]", - expansion.getExpansionType().name().toLowerCase(), - expansion.getIdentifier(), - expansion.getVersion() - ); - - if (expansion instanceof Taskable) { - ((Taskable) expansion).start(); - } - - // Check eCloud for updates only if the expansion is external - if (plugin.getPlaceholderAPIConfig().isCloudEnabled() && expansion.getExpansionType() == PlaceholderExpansion.Type.EXTERNAL) { - final Optional cloudExpansionOptional = plugin.getCloudExpansionManager().findCloudExpansionByName(identifier); - if (cloudExpansionOptional.isPresent()) { - CloudExpansion cloudExpansion = cloudExpansionOptional.get(); - cloudExpansion.setHasExpansion(true); - cloudExpansion.setShouldUpdate(!cloudExpansion.getLatestVersion().equals(expansion.getVersion())); - } - } - - return true; - } - - @ApiStatus.Internal - public boolean unregister(@NotNull final PlaceholderExpansion expansion) { - if (expansions.remove(expansion.getIdentifier().toLowerCase(Locale.ROOT)) == null) { - return false; - } - - Bukkit.getPluginManager().callEvent(new ExpansionUnregisterEvent(expansion)); - - if (expansion instanceof Listener) { - HandlerList.unregisterAll((Listener) expansion); - } - - if (expansion instanceof Taskable) { - ((Taskable) expansion).stop(); - } - - if (expansion instanceof Cacheable) { - ((Cacheable) expansion).clear(); - } - - if (plugin.getPlaceholderAPIConfig().isCloudEnabled()) { - plugin.getCloudExpansionManager().findCloudExpansionByName(expansion.getName()) - .ifPresent(cloud -> { - cloud.setHasExpansion(false); - cloud.setShouldUpdate(false); - }); - } - - return true; - } - - private void registerAll(@NotNull final CommandSender sender) { - Msg.info("Placeholder expansion registration initializing..."); - - Futures.onMainThread(plugin, findExpansionsOnDisk(), (classes, exception) -> { - if (exception != null) { - Msg.severe("Failed to load class files of expansion.", exception); - return; - } - - final List registered = classes.stream() - .filter(Objects::nonNull) - .map(this::register) - .filter(Optional::isPresent) - .map(Optional::get) - .collect(Collectors.toList()); - - final long needsUpdate = registered.stream() - .map(expansion -> plugin.getCloudExpansionManager().findCloudExpansionByName(expansion.getName()).orElse(null)) - .filter(Objects::nonNull) - .filter(CloudExpansion::shouldUpdate) - .count(); - - StringBuilder message = new StringBuilder(registered.size() == 0 ? "&6" : "&a") - .append(registered.size()) - .append(' ') - .append("placeholder hook(s) registered!"); - - if (needsUpdate > 0) { - message.append(' ') - .append("&6") - .append(needsUpdate) - .append(' ') - .append("placeholder hook(s) have an update available."); - } - - - Msg.msg(sender, message.toString()); - - Bukkit.getPluginManager().callEvent(new ExpansionsLoadedEvent(registered)); - }); - } - - private void unregisterAll() { - for (final PlaceholderExpansion expansion : Sets.newHashSet(expansions.values())) { - if (expansion.persist()) { - continue; - } - - expansion.unregister(); - } - } - - @NotNull - public CompletableFuture<@NotNull List<@Nullable Class>> findExpansionsOnDisk() { - File[] files = folder.listFiles((dir, name) -> name.endsWith(".jar")); - if (files == null) { - return CompletableFuture.completedFuture(Collections.emptyList()); - } - - return Arrays.stream(files) - .map(this::findExpansionInFile) - .collect(Futures.collector()); - } - - @NotNull - public CompletableFuture<@Nullable Class> findExpansionInFile( - @NotNull final File file) { - return CompletableFuture.supplyAsync(() -> { - try { - final Class expansionClass = FileUtil.findClass(file, PlaceholderExpansion.class); - - if (expansionClass == null) { - Msg.severe("Failed to load expansion %s, as it does not have a class which" - + " extends PlaceholderExpansion", file.getName()); - return null; - } - - Set expansionMethods = Arrays.stream(expansionClass.getDeclaredMethods()) - .map(method -> new MethodSignature(method.getName(), method.getParameterTypes())) - .collect(Collectors.toSet()); - if (!expansionMethods.containsAll(ABSTRACT_EXPANSION_METHODS)) { - Msg.severe("Failed to load expansion %s, as it does not have the required" - + " methods declared for a PlaceholderExpansion.", file.getName()); - return null; - } - - return expansionClass; - } catch (VerifyError | NoClassDefFoundError e) { - Msg.severe("Failed to load expansion %s (is a dependency missing?)", e, file.getName()); - return null; - } catch (Exception e) { - plugin.getLogger().log(Level.SEVERE, "Failed to load expansion file: " + file.getAbsolutePath(), e); - return null; - } - }); - } - - - @Nullable - public PlaceholderExpansion createExpansionInstance( - @NotNull final Class clazz) throws LinkageError { - try { - return clazz.getDeclaredConstructor().newInstance(); - } catch (final Exception ex) { - if (ex.getCause() instanceof LinkageError) { - throw ((LinkageError) ex.getCause()); - } - - Msg.warn("There was an issue with loading an expansion."); - return null; - } - } - - - @EventHandler - public void onQuit(@NotNull final PlayerQuitEvent event) { - for (final PlaceholderExpansion expansion : getExpansions()) { - if (!(expansion instanceof Cleanable)) { - continue; - } - - ((Cleanable) expansion).cleanup(event.getPlayer()); - } - } - - @EventHandler(priority = EventPriority.HIGH) - public void onPluginDisable(@NotNull final PluginDisableEvent event) { - final String name = event.getPlugin().getName(); - if (name.equals(plugin.getName())) { - return; - } - - for (final PlaceholderExpansion expansion : getExpansions()) { - if (!name.equalsIgnoreCase(expansion.getRequiredPlugin())) { - continue; - } - - expansion.unregister(); - Msg.info("Unregistered placeholder expansion %s", expansion.getIdentifier()); - Msg.info("Reason: required plugin %s was disabled.", name); - } - } - -} diff --git a/src/main/java/me/clip/placeholderapi/replacer/CharsReplacer.java b/src/main/java/me/clip/placeholderapi/replacer/CharsReplacer.java deleted file mode 100644 index fe08457..0000000 --- a/src/main/java/me/clip/placeholderapi/replacer/CharsReplacer.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.replacer; - -import java.util.Locale; -import java.util.function.Function; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import org.bukkit.ChatColor; -import org.bukkit.OfflinePlayer; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public final class CharsReplacer implements Replacer { - - @NotNull - private final Closure closure; - - public CharsReplacer(@NotNull final Closure closure) { - this.closure = closure; - } - - - @NotNull - @Override - public String apply(@NotNull final String text, @Nullable final OfflinePlayer player, - @NotNull final Function lookup) { - final char[] chars = text.toCharArray(); - final StringBuilder builder = new StringBuilder(text.length()); - - final StringBuilder identifier = new StringBuilder(); - final StringBuilder parameters = new StringBuilder(); - - for (int i = 0; i < chars.length; i++) { - final char l = chars[i]; - - if (l != closure.head || i + 1 >= chars.length) { - builder.append(l); - continue; - } - - boolean identified = false; - boolean invalid = true; - boolean hadSpace = false; - - while (++i < chars.length) { - final char p = chars[i]; - - if (p == ' ' && !identified) { - hadSpace = true; - break; - } - if (p == closure.tail) { - invalid = false; - break; - } - - if (p == '_' && !identified) { - identified = true; - continue; - } - - if (identified) { - parameters.append(p); - } else { - identifier.append(p); - } - } - - final String identifierString = identifier.toString(); - final String lowercaseIdentifierString = identifierString.toLowerCase(Locale.ROOT); - final String parametersString = parameters.toString(); - - identifier.setLength(0); - parameters.setLength(0); - - if (invalid) { - builder.append(closure.head).append(identifierString); - - if (identified) { - builder.append('_').append(parametersString); - } - - if (hadSpace) { - builder.append(' '); - } - continue; - } - - final PlaceholderExpansion placeholder = lookup.apply(lowercaseIdentifierString); - if (placeholder == null) { - builder.append(closure.head).append(identifierString); - - if (identified) { - builder.append('_'); - } - - builder.append(parametersString).append(closure.tail); - continue; - } - - final String replacement = placeholder.onRequest(player, parametersString); - if (replacement == null) { - builder.append(closure.head).append(identifierString); - - if (identified) { - builder.append('_'); - } - - builder.append(parametersString).append(closure.tail); - continue; - } - - builder.append(replacement); - } - - return builder.toString(); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/updatechecker/UpdateChecker.java b/src/main/java/me/clip/placeholderapi/updatechecker/UpdateChecker.java deleted file mode 100644 index 8a72fe5..0000000 --- a/src/main/java/me/clip/placeholderapi/updatechecker/UpdateChecker.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.updatechecker; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.Arrays; -import javax.net.ssl.HttpsURLConnection; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import me.clip.placeholderapi.scheduler.scheduling.schedulers.TaskScheduler; -import me.clip.placeholderapi.util.Msg; -import org.bukkit.Bukkit; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerJoinEvent; - -public class UpdateChecker implements Listener { - - private static final int RESOURCE_ID = 6245; - private final PlaceholderAPIPlugin plugin; - private final TaskScheduler scheduler; - private final String pluginVersion; - private String spigotVersion; - private boolean updateAvailable; - - public UpdateChecker(PlaceholderAPIPlugin plugin) { - this.plugin = plugin; - scheduler = plugin.getScheduler(); - pluginVersion = plugin.getDescription().getVersion(); - } - - public boolean hasUpdateAvailable() { - return updateAvailable; - } - - public String getSpigotVersion() { - return spigotVersion; - } - - public void fetch() { - scheduler.runTaskAsynchronously(() -> { - try { - HttpsURLConnection con = (HttpsURLConnection) new URL( - "https://api.spigotmc.org/legacy/update.php?resource=" + RESOURCE_ID).openConnection(); - con.setRequestMethod("GET"); - spigotVersion = new BufferedReader(new InputStreamReader(con.getInputStream())).readLine(); - } catch (Exception ex) { - plugin.getLogger().info("Failed to check for updates on spigot."); - return; - } - - if (spigotVersion == null || spigotVersion.isEmpty()) { - return; - } - - updateAvailable = spigotIsNewer(); - - if (!updateAvailable) { - return; - } - - scheduler.runTask(() -> { - plugin.getLogger() - .info("An update for PlaceholderAPI (v" + getSpigotVersion() + ") is available at:"); - plugin.getLogger() - .info("https://www.spigotmc.org/resources/placeholderapi." + RESOURCE_ID + "/"); - Bukkit.getPluginManager().registerEvents(this, plugin); - }); - }); - } - - private boolean spigotIsNewer() { - if (spigotVersion == null || spigotVersion.isEmpty()) { - return false; - } - - int[] plV = toReadable(pluginVersion); - int[] spV = toReadable(spigotVersion); - - if (plV[0] < spV[0]) { - return true; - } else if ((plV[1] < spV[1])) { - return true; - } else { - return plV[2] < spV[2]; - } - } - - private int[] toReadable(String version) { - if (version.contains("-DEV")) { - version = version.split("-DEV")[0]; - } - - return Arrays.stream(version.split("\\.")).mapToInt(Integer::parseInt).toArray(); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onJoin(PlayerJoinEvent e) { - if (e.getPlayer().hasPermission("placeholderapi.updatenotify")) { - Msg.msg(e.getPlayer(), - "&bAn update for &fPlaceholder&7API &e(&fPlaceholder&7API &fv" + getSpigotVersion() - + "&e)" - , "&bis available at &ehttps://www.spigotmc.org/resources/placeholderapi." + RESOURCE_ID - + "/"); - } - } -} diff --git a/src/main/java/me/clip/placeholderapi/util/FileUtil.java b/src/main/java/me/clip/placeholderapi/util/FileUtil.java deleted file mode 100644 index 5d41c8f..0000000 --- a/src/main/java/me/clip/placeholderapi/util/FileUtil.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.util; - -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.List; -import java.util.jar.JarEntry; -import java.util.jar.JarInputStream; - -public class FileUtil { - - @Nullable - public static Class findClass(@NotNull final File file, - @NotNull final Class clazz) throws IOException, ClassNotFoundException { - if (!file.exists()) { - return null; - } - - final URL jar = file.toURI().toURL(); - final URLClassLoader loader = new URLClassLoader(new URL[]{jar}, clazz.getClassLoader()); - final List matches = new ArrayList<>(); - final List> classes = new ArrayList<>(); - - try (final JarInputStream stream = new JarInputStream(jar.openStream())) { - JarEntry entry; - while ((entry = stream.getNextJarEntry()) != null) { - final String name = entry.getName(); - if (name.isEmpty() || !name.endsWith(".class")) { - continue; - } - - matches.add(name.substring(0, name.lastIndexOf('.')).replace('/', '.')); - } - - for (final String match : matches) { - try { - final Class loaded = loader.loadClass(match); - if (clazz.isAssignableFrom(loaded)) { - classes.add(loaded.asSubclass(clazz)); - } - } catch (final NoClassDefFoundError ignored) { - } - } - } - if (classes.isEmpty()) { - loader.close(); - return null; - } - return classes.get(0); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/util/Futures.java b/src/main/java/me/clip/placeholderapi/util/Futures.java deleted file mode 100644 index 29d7fa7..0000000 --- a/src/main/java/me/clip/placeholderapi/util/Futures.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.util; - -import java.util.Collection; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.function.BiConsumer; -import java.util.stream.Collector; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; -import org.jetbrains.annotations.NotNull; - -public final class Futures { - - private Futures() {} - - - public static void onMainThread(@NotNull final PlaceholderAPIPlugin plugin, - @NotNull final CompletableFuture future, - @NotNull final BiConsumer consumer) { - future.whenComplete((value, exception) -> { - if (Bukkit.isPrimaryThread()) { - consumer.accept(value, exception); - } else { - plugin.getScheduler().runTask(() -> consumer.accept(value, exception)); - } - }); - } - - - @NotNull - public static Collector, ?, CompletableFuture>> collector() { - return Collectors.collectingAndThen(Collectors.toList(), Futures::of); - } - - - @NotNull - public static CompletableFuture> of( - @NotNull final Stream> futures) { - return of(futures.collect(Collectors.toList())); - } - - @NotNull - public static CompletableFuture> of( - @NotNull final Collection> futures) { - return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])) - .thenApplyAsync($ -> awaitCompletion(futures)); - } - - @NotNull - private static List awaitCompletion( - @NotNull final Collection> futures) { - return futures.stream().map(CompletableFuture::join).collect(Collectors.toList()); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/util/Msg.java b/src/main/java/me/clip/placeholderapi/util/Msg.java deleted file mode 100644 index 84307c7..0000000 --- a/src/main/java/me/clip/placeholderapi/util/Msg.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.util; - -import java.util.Arrays; -import java.util.logging.Level; -import java.util.stream.Collectors; -import me.clip.placeholderapi.PlaceholderAPIPlugin; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.jetbrains.annotations.NotNull; - -public final class Msg { - - public static void log(Level level, String msg, Object... args) { - PlaceholderAPIPlugin.getInstance().getLogger().log(level, String.format(msg, args)); - } - - public static void info(String msg, Object... args) { - log(Level.INFO, msg, args); - } - - public static void warn(String msg, Object... args) { - log(Level.WARNING, msg, args); - } - - public static void warn(String msg, Throwable throwable, Object... args){ - PlaceholderAPIPlugin.getInstance().getLogger().log(Level.WARNING, String.format(msg, args), throwable); - } - - public static void severe(String msg, Object... args) { - log(Level.SEVERE, msg, args); - } - - public static void severe(String msg, Throwable throwable, Object... args) { - PlaceholderAPIPlugin.getInstance().getLogger().log(Level.SEVERE, String.format(msg, args), throwable); - } - - public static void msg(@NotNull final CommandSender sender, @NotNull final String... messages) { - if (messages.length == 0) { - return; - } - - sender.sendMessage(Arrays.stream(messages).map(Msg::color).collect(Collectors.joining("\n"))); - } - - public static void broadcast(@NotNull final String... messages) { - if (messages.length == 0) { - return; - } - - Bukkit.broadcastMessage( - Arrays.stream(messages).map(Msg::color).collect(Collectors.joining("\n"))); - } - - public static String color(@NotNull final String text) { - return ChatColor.translateAlternateColorCodes('&', text); - } - -} diff --git a/src/main/java/me/clip/placeholderapi/util/TimeUtil.java b/src/main/java/me/clip/placeholderapi/util/TimeUtil.java deleted file mode 100644 index d23a571..0000000 --- a/src/main/java/me/clip/placeholderapi/util/TimeUtil.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi.util; - -import java.time.Duration; -import java.time.temporal.ChronoUnit; -import java.util.StringJoiner; - -public class TimeUtil { - - public static String getRemaining(final int seconds, final TimeFormat type) { - return getRemaining((long) seconds, type); - } - - public static String getRemaining(final long seconds, final TimeFormat type) { - switch (type) { - default: - return String.valueOf(seconds); - - case SECONDS: - return String.valueOf(seconds % 60); - - case MINUTES: - return String.valueOf((seconds / 60) % 60); - - case HOURS: - return String.valueOf((seconds / 3600) % 24); - - case DAYS: - return String.valueOf(seconds / 86400); - } - } - - /** - * Format the given value with s, m, h and d (seconds, minutes, hours and days) - * - * @param duration {@link Duration} (eg, Duration.of(20, {@link ChronoUnit#SECONDS}) for 20 - * seconds) - * @return formatted time - */ - public static String getTime(final Duration duration) { - return getTime(duration.getSeconds()); - } - - public static String getTime(final int seconds) { - return getTime((long) seconds); - } - - public static String getTime(long seconds) { - final StringJoiner joiner = new StringJoiner(" "); - - long minutes = seconds / 60; - long hours = minutes / 60; - final long days = hours / 24; - - seconds %= 60; - minutes %= 60; - hours %= 24; - - if (days > 0) { - joiner.add(days + "d"); - } - - if (hours > 0) { - joiner.add(hours + "h"); - } - - if (minutes > 0) { - joiner.add(minutes + "m"); - } - - if (seconds > 0) { - joiner.add(seconds + "s"); - } - - return joiner.toString(); - } -} diff --git a/src/test/java/me/clip/placeholderapi/Values.java b/src/test/java/me/clip/placeholderapi/Values.java deleted file mode 100644 index b39ea45..0000000 --- a/src/test/java/me/clip/placeholderapi/Values.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * This file is part of PlaceholderAPI - * - * PlaceholderAPI - * Copyright (c) 2015 - 2024 PlaceholderAPI Team - * - * PlaceholderAPI 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. - * - * PlaceholderAPI 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 me.clip.placeholderapi; - -import com.google.common.collect.ImmutableMap; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.clip.placeholderapi.replacer.CharsReplacer; -import me.clip.placeholderapi.replacer.Replacer; -import org.bukkit.OfflinePlayer; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -public interface Values { - - String SMALL_TEXT = "My name is %player_name%"; - String LARGE_TEXT = "My name is %player_name% and my location is (%player_x%, %player_y%, %player_z%), this placeholder is invalid %server_name%"; - - ImmutableMap PLACEHOLDERS = ImmutableMap.builder() - .put("player", new MockPlayerPlaceholderExpansion()) - .build(); - - - Replacer CHARS_REPLACER = new CharsReplacer(Replacer.Closure.PERCENT); - - - final class MockPlayerPlaceholderExpansion extends PlaceholderExpansion { - - public static final String PLAYER_X = "10"; - public static final String PLAYER_Y = "20"; - public static final String PLAYER_Z = "30"; - public static final String PLAYER_NAME = "Sxtanna"; - - - @NotNull - @Override - public String getIdentifier() { - return "player"; - } - - @NotNull - @Override - public String getAuthor() { - return "Sxtanna"; - } - - @NotNull - @Override - public String getVersion() { - return "1.0"; - } - - @Override - public String onRequest(@Nullable final OfflinePlayer player, @NotNull final String params) { - final String[] parts = params.split("_"); - if (parts.length == 0) { - return null; - } - - switch (parts[0]) { - case "name": - return PLAYER_NAME; - case "x": - return PLAYER_X; - case "y": - return PLAYER_Y; - case "z": - return PLAYER_Z; - } - - return null; - } - - } - -}